clang 22.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 "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Linkage.h"
58#include "clang/Basic/Module.h"
68#include "llvm/ADT/APFixedPoint.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/APSInt.h"
71#include "llvm/ADT/ArrayRef.h"
72#include "llvm/ADT/DenseMap.h"
73#include "llvm/ADT/DenseSet.h"
74#include "llvm/ADT/FoldingSet.h"
75#include "llvm/ADT/PointerUnion.h"
76#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/StringExtras.h"
80#include "llvm/ADT/StringRef.h"
81#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82#include "llvm/Support/Capacity.h"
83#include "llvm/Support/Casting.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/MD5.h"
87#include "llvm/Support/MathExtras.h"
88#include "llvm/Support/SipHash.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/AArch64TargetParser.h"
91#include "llvm/TargetParser/Triple.h"
92#include <algorithm>
93#include <cassert>
94#include <cstddef>
95#include <cstdint>
96#include <cstdlib>
97#include <map>
98#include <memory>
99#include <optional>
100#include <string>
101#include <tuple>
102#include <utility>
103
104using namespace clang;
105
116
117template <> struct llvm::DenseMapInfo<llvm::FoldingSetNodeID> {
118 static FoldingSetNodeID getEmptyKey() { return FoldingSetNodeID{}; }
119
120 static FoldingSetNodeID getTombstoneKey() {
121 FoldingSetNodeID id;
122 for (size_t i = 0; i < sizeof(id) / sizeof(unsigned); ++i) {
123 id.AddInteger(std::numeric_limits<unsigned>::max());
124 }
125 return id;
126 }
127
128 static unsigned getHashValue(const FoldingSetNodeID &Val) {
129 return Val.ComputeHash();
130 }
131
132 static bool isEqual(const FoldingSetNodeID &LHS,
133 const FoldingSetNodeID &RHS) {
134 return LHS == RHS;
135 }
136};
137
138/// \returns The locations that are relevant when searching for Doc comments
139/// related to \p D.
142 assert(D);
143
144 // User can not attach documentation to implicit declarations.
145 if (D->isImplicit())
146 return {};
147
148 // User can not attach documentation to implicit instantiations.
149 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
150 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
151 return {};
152 }
153
154 if (const auto *VD = dyn_cast<VarDecl>(D)) {
155 if (VD->isStaticDataMember() &&
156 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
157 return {};
158 }
159
160 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
161 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
162 return {};
163 }
164
165 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
166 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
167 if (TSK == TSK_ImplicitInstantiation ||
168 TSK == TSK_Undeclared)
169 return {};
170 }
171
172 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
173 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
174 return {};
175 }
176 if (const auto *TD = dyn_cast<TagDecl>(D)) {
177 // When tag declaration (but not definition!) is part of the
178 // decl-specifier-seq of some other declaration, it doesn't get comment
179 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
180 return {};
181 }
182 // TODO: handle comments for function parameters properly.
183 if (isa<ParmVarDecl>(D))
184 return {};
185
186 // TODO: we could look up template parameter documentation in the template
187 // documentation.
191 return {};
192
194 // Find declaration location.
195 // For Objective-C declarations we generally don't expect to have multiple
196 // declarators, thus use declaration starting location as the "declaration
197 // location".
198 // For all other declarations multiple declarators are used quite frequently,
199 // so we use the location of the identifier as the "declaration location".
200 SourceLocation BaseLocation;
204 // Allow association with Y across {} in `typedef struct X {} Y`.
206 BaseLocation = D->getBeginLoc();
207 else
208 BaseLocation = D->getLocation();
209
210 if (!D->getLocation().isMacroID()) {
211 Locations.emplace_back(BaseLocation);
212 } else {
213 const auto *DeclCtx = D->getDeclContext();
214
215 // When encountering definitions generated from a macro (that are not
216 // contained by another declaration in the macro) we need to try and find
217 // the comment at the location of the expansion but if there is no comment
218 // there we should retry to see if there is a comment inside the macro as
219 // well. To this end we return first BaseLocation to first look at the
220 // expansion site, the second value is the spelling location of the
221 // beginning of the declaration defined inside the macro.
222 if (!(DeclCtx &&
223 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
224 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
225 }
226
227 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
228 // we don't refer to the macro argument location at the expansion site (this
229 // can happen if the name's spelling is provided via macro argument), and
230 // always to the declaration itself.
231 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
232 }
233
234 return Locations;
235}
236
238 const Decl *D, const SourceLocation RepresentativeLocForDecl,
239 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
240 // If the declaration doesn't map directly to a location in a file, we
241 // can't find the comment.
242 if (RepresentativeLocForDecl.isInvalid() ||
243 !RepresentativeLocForDecl.isFileID())
244 return nullptr;
245
246 // If there are no comments anywhere, we won't find anything.
247 if (CommentsInTheFile.empty())
248 return nullptr;
249
250 // Decompose the location for the declaration and find the beginning of the
251 // file buffer.
252 const FileIDAndOffset DeclLocDecomp =
253 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
254
255 // Slow path.
256 auto OffsetCommentBehindDecl =
257 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
258
259 // First check whether we have a trailing comment.
260 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
261 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
262 if ((CommentBehindDecl->isDocumentation() ||
263 LangOpts.CommentOpts.ParseAllComments) &&
264 CommentBehindDecl->isTrailingComment() &&
267
268 // Check that Doxygen trailing comment comes after the declaration, starts
269 // on the same line and in the same file as the declaration.
270 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
271 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
272 OffsetCommentBehindDecl->first)) {
273 return CommentBehindDecl;
274 }
275 }
276 }
277
278 // The comment just after the declaration was not a trailing comment.
279 // Let's look at the previous comment.
280 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
281 return nullptr;
282
283 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
284 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
285
286 // Check that we actually have a non-member Doxygen comment.
287 if (!(CommentBeforeDecl->isDocumentation() ||
288 LangOpts.CommentOpts.ParseAllComments) ||
289 CommentBeforeDecl->isTrailingComment())
290 return nullptr;
291
292 // Decompose the end of the comment.
293 const unsigned CommentEndOffset =
294 Comments.getCommentEndOffset(CommentBeforeDecl);
295
296 // Get the corresponding buffer.
297 bool Invalid = false;
298 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
299 &Invalid).data();
300 if (Invalid)
301 return nullptr;
302
303 // Extract text between the comment and declaration.
304 StringRef Text(Buffer + CommentEndOffset,
305 DeclLocDecomp.second - CommentEndOffset);
306
307 // There should be no other declarations or preprocessor directives between
308 // comment and declaration.
309 if (Text.find_last_of(";{}#@") != StringRef::npos)
310 return nullptr;
311
312 return CommentBeforeDecl;
313}
314
316 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
317
318 for (const auto DeclLoc : DeclLocs) {
319 // If the declaration doesn't map directly to a location in a file, we
320 // can't find the comment.
321 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
322 continue;
323
325 ExternalSource->ReadComments();
326 CommentsLoaded = true;
327 }
328
329 if (Comments.empty())
330 continue;
331
332 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
333 if (!File.isValid())
334 continue;
335
336 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
337 if (!CommentsInThisFile || CommentsInThisFile->empty())
338 continue;
339
340 if (RawComment *Comment =
341 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
342 return Comment;
343 }
344
345 return nullptr;
346}
347
349 assert(LangOpts.RetainCommentsFromSystemHeaders ||
350 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
351 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
352}
353
354/// If we have a 'templated' declaration for a template, adjust 'D' to
355/// refer to the actual template.
356/// If we have an implicit instantiation, adjust 'D' to refer to template.
357static const Decl &adjustDeclToTemplate(const Decl &D) {
358 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
359 // Is this function declaration part of a function template?
360 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
361 return *FTD;
362
363 // Nothing to do if function is not an implicit instantiation.
364 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
365 return D;
366
367 // Function is an implicit instantiation of a function template?
368 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
369 return *FTD;
370
371 // Function is instantiated from a member definition of a class template?
372 if (const FunctionDecl *MemberDecl =
374 return *MemberDecl;
375
376 return D;
377 }
378 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
379 // Static data member is instantiated from a member definition of a class
380 // template?
381 if (VD->isStaticDataMember())
382 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
383 return *MemberDecl;
384
385 return D;
386 }
387 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
388 // Is this class declaration part of a class template?
389 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
390 return *CTD;
391
392 // Class is an implicit instantiation of a class template or partial
393 // specialization?
394 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
395 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
396 return D;
397 llvm::PointerUnion<ClassTemplateDecl *,
400 return isa<ClassTemplateDecl *>(PU)
401 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
402 : *static_cast<const Decl *>(
404 }
405
406 // Class is instantiated from a member definition of a class template?
407 if (const MemberSpecializationInfo *Info =
408 CRD->getMemberSpecializationInfo())
409 return *Info->getInstantiatedFrom();
410
411 return D;
412 }
413 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
414 // Enum is instantiated from a member definition of a class template?
415 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
416 return *MemberDecl;
417
418 return D;
419 }
420 // FIXME: Adjust alias templates?
421 return D;
422}
423
425 const Decl *D,
426 const Decl **OriginalDecl) const {
427 if (!D) {
428 if (OriginalDecl)
429 OriginalDecl = nullptr;
430 return nullptr;
431 }
432
433 D = &adjustDeclToTemplate(*D);
434
435 // Any comment directly attached to D?
436 {
437 auto DeclComment = DeclRawComments.find(D);
438 if (DeclComment != DeclRawComments.end()) {
439 if (OriginalDecl)
440 *OriginalDecl = D;
441 return DeclComment->second;
442 }
443 }
444
445 // Any comment attached to any redeclaration of D?
446 const Decl *CanonicalD = D->getCanonicalDecl();
447 if (!CanonicalD)
448 return nullptr;
449
450 {
451 auto RedeclComment = RedeclChainComments.find(CanonicalD);
452 if (RedeclComment != RedeclChainComments.end()) {
453 if (OriginalDecl)
454 *OriginalDecl = RedeclComment->second;
455 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
456 assert(CommentAtRedecl != DeclRawComments.end() &&
457 "This decl is supposed to have comment attached.");
458 return CommentAtRedecl->second;
459 }
460 }
461
462 // Any redeclarations of D that we haven't checked for comments yet?
463 const Decl *LastCheckedRedecl = [&]() {
464 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
465 bool CanUseCommentlessCache = false;
466 if (LastChecked) {
467 for (auto *Redecl : CanonicalD->redecls()) {
468 if (Redecl == D) {
469 CanUseCommentlessCache = true;
470 break;
471 }
472 if (Redecl == LastChecked)
473 break;
474 }
475 }
476 // FIXME: This could be improved so that even if CanUseCommentlessCache
477 // is false, once we've traversed past CanonicalD we still skip ahead
478 // LastChecked.
479 return CanUseCommentlessCache ? LastChecked : nullptr;
480 }();
481
482 for (const Decl *Redecl : D->redecls()) {
483 assert(Redecl);
484 // Skip all redeclarations that have been checked previously.
485 if (LastCheckedRedecl) {
486 if (LastCheckedRedecl == Redecl) {
487 LastCheckedRedecl = nullptr;
488 }
489 continue;
490 }
491 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
492 if (RedeclComment) {
493 cacheRawCommentForDecl(*Redecl, *RedeclComment);
494 if (OriginalDecl)
495 *OriginalDecl = Redecl;
496 return RedeclComment;
497 }
498 CommentlessRedeclChains[CanonicalD] = Redecl;
499 }
500
501 if (OriginalDecl)
502 *OriginalDecl = nullptr;
503 return nullptr;
504}
505
507 const RawComment &Comment) const {
508 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
509 DeclRawComments.try_emplace(&OriginalD, &Comment);
510 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
511 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
512 CommentlessRedeclChains.erase(CanonicalDecl);
513}
514
515static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
517 const DeclContext *DC = ObjCMethod->getDeclContext();
518 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
519 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
520 if (!ID)
521 return;
522 // Add redeclared method here.
523 for (const auto *Ext : ID->known_extensions()) {
524 if (ObjCMethodDecl *RedeclaredMethod =
525 Ext->getMethod(ObjCMethod->getSelector(),
526 ObjCMethod->isInstanceMethod()))
527 Redeclared.push_back(RedeclaredMethod);
528 }
529 }
530}
531
533 const Preprocessor *PP) {
534 if (Comments.empty() || Decls.empty())
535 return;
536
537 FileID File;
538 for (const Decl *D : Decls) {
539 if (D->isInvalidDecl())
540 continue;
541
542 D = &adjustDeclToTemplate(*D);
543 SourceLocation Loc = D->getLocation();
544 if (Loc.isValid()) {
545 // See if there are any new comments that are not attached to a decl.
546 // The location doesn't have to be precise - we care only about the file.
547 File = SourceMgr.getDecomposedLoc(Loc).first;
548 break;
549 }
550 }
551
552 if (File.isInvalid())
553 return;
554
555 auto CommentsInThisFile = Comments.getCommentsInFile(File);
556 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
557 CommentsInThisFile->rbegin()->second->isAttached())
558 return;
559
560 // There is at least one comment not attached to a decl.
561 // Maybe it should be attached to one of Decls?
562 //
563 // Note that this way we pick up not only comments that precede the
564 // declaration, but also comments that *follow* the declaration -- thanks to
565 // the lookahead in the lexer: we've consumed the semicolon and looked
566 // ahead through comments.
567 for (const Decl *D : Decls) {
568 assert(D);
569 if (D->isInvalidDecl())
570 continue;
571
572 D = &adjustDeclToTemplate(*D);
573
574 if (DeclRawComments.count(D) > 0)
575 continue;
576
577 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
578
579 for (const auto DeclLoc : DeclLocs) {
580 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
581 continue;
582
583 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
584 D, DeclLoc, *CommentsInThisFile)) {
585 cacheRawCommentForDecl(*D, *DocComment);
586 comments::FullComment *FC = DocComment->parse(*this, PP, D);
587 ParsedComments[D->getCanonicalDecl()] = FC;
588 break;
589 }
590 }
591 }
592}
593
595 const Decl *D) const {
596 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
597 ThisDeclInfo->CommentDecl = D;
598 ThisDeclInfo->IsFilled = false;
599 ThisDeclInfo->fill();
600 ThisDeclInfo->CommentDecl = FC->getDecl();
601 if (!ThisDeclInfo->TemplateParameters)
602 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
604 new (*this) comments::FullComment(FC->getBlocks(),
605 ThisDeclInfo);
606 return CFC;
607}
608
611 return RC ? RC->parse(*this, nullptr, D) : nullptr;
612}
613
615 const Decl *D,
616 const Preprocessor *PP) const {
617 if (!D || D->isInvalidDecl())
618 return nullptr;
619 D = &adjustDeclToTemplate(*D);
620
621 const Decl *Canonical = D->getCanonicalDecl();
622 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
623 ParsedComments.find(Canonical);
624
625 if (Pos != ParsedComments.end()) {
626 if (Canonical != D) {
627 comments::FullComment *FC = Pos->second;
629 return CFC;
630 }
631 return Pos->second;
632 }
633
634 const Decl *OriginalDecl = nullptr;
635
636 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
637 if (!RC) {
640 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
641 if (OMD && OMD->isPropertyAccessor())
642 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
643 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
644 return cloneFullComment(FC, D);
645 if (OMD)
646 addRedeclaredMethods(OMD, Overridden);
647 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
648 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
649 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
650 return cloneFullComment(FC, D);
651 }
652 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
653 // Attach any tag type's documentation to its typedef if latter
654 // does not have one of its own.
655 QualType QT = TD->getUnderlyingType();
656 if (const auto *TT = QT->getAs<TagType>())
657 if (comments::FullComment *FC =
658 getCommentForDecl(TT->getOriginalDecl(), PP))
659 return cloneFullComment(FC, D);
660 }
661 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
662 while (IC->getSuperClass()) {
663 IC = IC->getSuperClass();
665 return cloneFullComment(FC, D);
666 }
667 }
668 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
669 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
671 return cloneFullComment(FC, D);
672 }
673 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
674 if (!(RD = RD->getDefinition()))
675 return nullptr;
676 // Check non-virtual bases.
677 for (const auto &I : RD->bases()) {
678 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
679 continue;
680 QualType Ty = I.getType();
681 if (Ty.isNull())
682 continue;
684 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
685 continue;
686
688 return cloneFullComment(FC, D);
689 }
690 }
691 // Check virtual bases.
692 for (const auto &I : RD->vbases()) {
693 if (I.getAccessSpecifier() != AS_public)
694 continue;
695 QualType Ty = I.getType();
696 if (Ty.isNull())
697 continue;
698 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
699 if (!(VirtualBase= VirtualBase->getDefinition()))
700 continue;
702 return cloneFullComment(FC, D);
703 }
704 }
705 }
706 return nullptr;
707 }
708
709 // If the RawComment was attached to other redeclaration of this Decl, we
710 // should parse the comment in context of that other Decl. This is important
711 // because comments can contain references to parameter names which can be
712 // different across redeclarations.
713 if (D != OriginalDecl && OriginalDecl)
714 return getCommentForDecl(OriginalDecl, PP);
715
716 comments::FullComment *FC = RC->parse(*this, PP, D);
717 ParsedComments[Canonical] = FC;
718 return FC;
719}
720
721void ASTContext::CanonicalTemplateTemplateParm::Profile(
722 llvm::FoldingSetNodeID &ID, const ASTContext &C,
724 ID.AddInteger(Parm->getDepth());
725 ID.AddInteger(Parm->getPosition());
726 ID.AddBoolean(Parm->isParameterPack());
727 ID.AddInteger(Parm->templateParameterKind());
728
730 ID.AddInteger(Params->size());
732 PEnd = Params->end();
733 P != PEnd; ++P) {
734 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
735 ID.AddInteger(0);
736 ID.AddBoolean(TTP->isParameterPack());
737 ID.AddInteger(
738 TTP->getNumExpansionParameters().toInternalRepresentation());
739 continue;
740 }
741
742 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
743 ID.AddInteger(1);
744 ID.AddBoolean(NTTP->isParameterPack());
745 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
746 .getAsOpaquePtr());
747 if (NTTP->isExpandedParameterPack()) {
748 ID.AddBoolean(true);
749 ID.AddInteger(NTTP->getNumExpansionTypes());
750 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
751 QualType T = NTTP->getExpansionType(I);
752 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
753 }
754 } else
755 ID.AddBoolean(false);
756 continue;
757 }
758
759 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
760 ID.AddInteger(2);
761 Profile(ID, C, TTP);
762 }
763}
764
765TemplateTemplateParmDecl *
767 TemplateTemplateParmDecl *TTP) const {
768 // Check if we already have a canonical template template parameter.
769 llvm::FoldingSetNodeID ID;
770 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
771 void *InsertPos = nullptr;
772 CanonicalTemplateTemplateParm *Canonical
773 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
774 if (Canonical)
775 return Canonical->getParam();
776
777 // Build a canonical template parameter list.
779 SmallVector<NamedDecl *, 4> CanonParams;
780 CanonParams.reserve(Params->size());
782 PEnd = Params->end();
783 P != PEnd; ++P) {
784 // Note that, per C++20 [temp.over.link]/6, when determining whether
785 // template-parameters are equivalent, constraints are ignored.
786 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
789 TTP->getDepth(), TTP->getIndex(), nullptr, false,
790 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
791 TTP->getNumExpansionParameters());
792 CanonParams.push_back(NewTTP);
793 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
797 if (NTTP->isExpandedParameterPack()) {
798 SmallVector<QualType, 2> ExpandedTypes;
800 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
801 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
802 ExpandedTInfos.push_back(
803 getTrivialTypeSourceInfo(ExpandedTypes.back()));
804 }
805
809 NTTP->getDepth(),
810 NTTP->getPosition(), nullptr,
811 T,
812 TInfo,
813 ExpandedTypes,
814 ExpandedTInfos);
815 } else {
819 NTTP->getDepth(),
820 NTTP->getPosition(), nullptr,
821 T,
822 NTTP->isParameterPack(),
823 TInfo);
824 }
825 CanonParams.push_back(Param);
826 } else
827 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
829 }
830
833 TTP->getPosition(), TTP->isParameterPack(), nullptr,
835 /*Typename=*/false,
837 CanonParams, SourceLocation(),
838 /*RequiresClause=*/nullptr));
839
840 // Get the new insert position for the node we care about.
841 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
842 assert(!Canonical && "Shouldn't be in the map!");
843 (void)Canonical;
844
845 // Create the canonical template template parameter entry.
846 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
847 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
848 return CanonTTP;
849}
850
853 TemplateTemplateParmDecl *TTP) const {
854 llvm::FoldingSetNodeID ID;
855 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
856 void *InsertPos = nullptr;
857 CanonicalTemplateTemplateParm *Canonical =
858 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
859 return Canonical ? Canonical->getParam() : nullptr;
860}
861
864 TemplateTemplateParmDecl *CanonTTP) const {
865 llvm::FoldingSetNodeID ID;
866 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
867 void *InsertPos = nullptr;
868 if (auto *Existing =
869 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
870 return Existing->getParam();
871 CanonTemplateTemplateParms.InsertNode(
872 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
873 return CanonTTP;
874}
875
876/// Check if a type can have its sanitizer instrumentation elided based on its
877/// presence within an ignorelist.
879 const QualType &Ty) const {
880 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
881 return NoSanitizeL->containsType(Mask, TyName);
882}
883
885 auto Kind = getTargetInfo().getCXXABI().getKind();
886 return getLangOpts().CXXABI.value_or(Kind);
887}
888
889CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
890 if (!LangOpts.CPlusPlus) return nullptr;
891
892 switch (getCXXABIKind()) {
893 case TargetCXXABI::AppleARM64:
894 case TargetCXXABI::Fuchsia:
895 case TargetCXXABI::GenericARM: // Same as Itanium at this level
896 case TargetCXXABI::iOS:
897 case TargetCXXABI::WatchOS:
898 case TargetCXXABI::GenericAArch64:
899 case TargetCXXABI::GenericMIPS:
900 case TargetCXXABI::GenericItanium:
901 case TargetCXXABI::WebAssembly:
902 case TargetCXXABI::XL:
903 return CreateItaniumCXXABI(*this);
904 case TargetCXXABI::Microsoft:
905 return CreateMicrosoftCXXABI(*this);
906 }
907 llvm_unreachable("Invalid CXXABI type!");
908}
909
911 if (!InterpContext) {
912 InterpContext.reset(new interp::Context(*this));
913 }
914 return *InterpContext;
915}
916
918 if (!ParentMapCtx)
919 ParentMapCtx.reset(new ParentMapContext(*this));
920 return *ParentMapCtx;
921}
922
924 const LangOptions &LangOpts) {
925 switch (LangOpts.getAddressSpaceMapMangling()) {
927 return TI.useAddressSpaceMapMangling();
929 return true;
931 return false;
932 }
933 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
934}
935
937 IdentifierTable &idents, SelectorTable &sels,
939 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
940 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
941 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
942 DependentSizedMatrixTypes(this_()),
943 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
944 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
945 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
946 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
947 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
948 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
949 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
950 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
951 LangOpts.XRayNeverInstrumentFiles,
952 LangOpts.XRayAttrListFiles, SM)),
953 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
954 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
955 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
956 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
957 CompCategories(this_()), LastSDM(nullptr, 0) {
959}
960
962 // Release the DenseMaps associated with DeclContext objects.
963 // FIXME: Is this the ideal solution?
964 ReleaseDeclContextMaps();
965
966 // Call all of the deallocation functions on all of their targets.
967 for (auto &Pair : Deallocations)
968 (Pair.first)(Pair.second);
969 Deallocations.clear();
970
971 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
972 // because they can contain DenseMaps.
973 for (llvm::DenseMap<const ObjCInterfaceDecl *,
975 I = ObjCLayouts.begin(),
976 E = ObjCLayouts.end();
977 I != E;)
978 // Increment in loop to prevent using deallocated memory.
979 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
980 R->Destroy(*this);
981 ObjCLayouts.clear();
982
983 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
984 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
985 // Increment in loop to prevent using deallocated memory.
986 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
987 R->Destroy(*this);
988 }
989 ASTRecordLayouts.clear();
990
991 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
992 AEnd = DeclAttrs.end();
993 A != AEnd; ++A)
994 A->second->~AttrVec();
995 DeclAttrs.clear();
996
997 for (const auto &Value : ModuleInitializers)
998 Value.second->~PerModuleInitializers();
999 ModuleInitializers.clear();
1000}
1001
1003
1004void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1005 TraversalScope = TopLevelDecls;
1007}
1008
1009void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1010 Deallocations.push_back({Callback, Data});
1011}
1012
1013void
1017
1019 llvm::errs() << "\n*** AST Context Stats:\n";
1020 llvm::errs() << " " << Types.size() << " types total.\n";
1021
1022 unsigned counts[] = {
1023#define TYPE(Name, Parent) 0,
1024#define ABSTRACT_TYPE(Name, Parent)
1025#include "clang/AST/TypeNodes.inc"
1026 0 // Extra
1027 };
1028
1029 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1030 Type *T = Types[i];
1031 counts[(unsigned)T->getTypeClass()]++;
1032 }
1033
1034 unsigned Idx = 0;
1035 unsigned TotalBytes = 0;
1036#define TYPE(Name, Parent) \
1037 if (counts[Idx]) \
1038 llvm::errs() << " " << counts[Idx] << " " << #Name \
1039 << " types, " << sizeof(Name##Type) << " each " \
1040 << "(" << counts[Idx] * sizeof(Name##Type) \
1041 << " bytes)\n"; \
1042 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1043 ++Idx;
1044#define ABSTRACT_TYPE(Name, Parent)
1045#include "clang/AST/TypeNodes.inc"
1046
1047 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1048
1049 // Implicit special member functions.
1050 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1052 << " implicit default constructors created\n";
1053 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1055 << " implicit copy constructors created\n";
1056 if (getLangOpts().CPlusPlus)
1057 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1059 << " implicit move constructors created\n";
1060 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1062 << " implicit copy assignment operators created\n";
1063 if (getLangOpts().CPlusPlus)
1064 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1066 << " implicit move assignment operators created\n";
1067 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1069 << " implicit destructors created\n";
1070
1071 if (ExternalSource) {
1072 llvm::errs() << "\n";
1073 ExternalSource->PrintStats();
1074 }
1075
1076 BumpAlloc.PrintStats();
1077}
1078
1080 bool NotifyListeners) {
1081 if (NotifyListeners)
1082 if (auto *Listener = getASTMutationListener();
1084 Listener->RedefinedHiddenDefinition(ND, M);
1085
1086 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1087}
1088
1090 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1091 if (It == MergedDefModules.end())
1092 return;
1093
1094 auto &Merged = It->second;
1095 llvm::DenseSet<Module*> Found;
1096 for (Module *&M : Merged)
1097 if (!Found.insert(M).second)
1098 M = nullptr;
1099 llvm::erase(Merged, nullptr);
1100}
1101
1104 auto MergedIt =
1105 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1106 if (MergedIt == MergedDefModules.end())
1107 return {};
1108 return MergedIt->second;
1109}
1110
1111void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1112 if (LazyInitializers.empty())
1113 return;
1114
1115 auto *Source = Ctx.getExternalSource();
1116 assert(Source && "lazy initializers but no external source");
1117
1118 auto LazyInits = std::move(LazyInitializers);
1119 LazyInitializers.clear();
1120
1121 for (auto ID : LazyInits)
1122 Initializers.push_back(Source->GetExternalDecl(ID));
1123
1124 assert(LazyInitializers.empty() &&
1125 "GetExternalDecl for lazy module initializer added more inits");
1126}
1127
1129 // One special case: if we add a module initializer that imports another
1130 // module, and that module's only initializer is an ImportDecl, simplify.
1131 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1132 auto It = ModuleInitializers.find(ID->getImportedModule());
1133
1134 // Maybe the ImportDecl does nothing at all. (Common case.)
1135 if (It == ModuleInitializers.end())
1136 return;
1137
1138 // Maybe the ImportDecl only imports another ImportDecl.
1139 auto &Imported = *It->second;
1140 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1141 Imported.resolve(*this);
1142 auto *OnlyDecl = Imported.Initializers.front();
1143 if (isa<ImportDecl>(OnlyDecl))
1144 D = OnlyDecl;
1145 }
1146 }
1147
1148 auto *&Inits = ModuleInitializers[M];
1149 if (!Inits)
1150 Inits = new (*this) PerModuleInitializers;
1151 Inits->Initializers.push_back(D);
1152}
1153
1156 auto *&Inits = ModuleInitializers[M];
1157 if (!Inits)
1158 Inits = new (*this) PerModuleInitializers;
1159 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1160 IDs.begin(), IDs.end());
1161}
1162
1164 auto It = ModuleInitializers.find(M);
1165 if (It == ModuleInitializers.end())
1166 return {};
1167
1168 auto *Inits = It->second;
1169 Inits->resolve(*this);
1170 return Inits->Initializers;
1171}
1172
1174 assert(M->isNamedModule());
1175 assert(!CurrentCXXNamedModule &&
1176 "We should set named module for ASTContext for only once");
1177 CurrentCXXNamedModule = M;
1178}
1179
1180bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1181 if (!M1 != !M2)
1182 return false;
1183
1184 /// Get the representative module for M. The representative module is the
1185 /// first module unit for a specific primary module name. So that the module
1186 /// units have the same representative module belongs to the same module.
1187 ///
1188 /// The process is helpful to reduce the expensive string operations.
1189 auto GetRepresentativeModule = [this](const Module *M) {
1190 auto Iter = SameModuleLookupSet.find(M);
1191 if (Iter != SameModuleLookupSet.end())
1192 return Iter->second;
1193
1194 const Module *RepresentativeModule =
1195 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1196 .first->second;
1197 SameModuleLookupSet[M] = RepresentativeModule;
1198 return RepresentativeModule;
1199 };
1200
1201 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1202 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1203}
1204
1206 if (!ExternCContext)
1207 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1208
1209 return ExternCContext;
1210}
1211
1222
1223#define BuiltinTemplate(BTName) \
1224 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1225 if (!Decl##BTName) \
1226 Decl##BTName = \
1227 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1228 return Decl##BTName; \
1229 }
1230#include "clang/Basic/BuiltinTemplates.inc"
1231
1233 RecordDecl::TagKind TK) const {
1234 SourceLocation Loc;
1235 RecordDecl *NewDecl;
1236 if (getLangOpts().CPlusPlus)
1237 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1238 Loc, &Idents.get(Name));
1239 else
1240 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1241 &Idents.get(Name));
1242 NewDecl->setImplicit();
1243 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1244 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1245 return NewDecl;
1246}
1247
1249 StringRef Name) const {
1252 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1253 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1254 NewDecl->setImplicit();
1255 return NewDecl;
1256}
1257
1259 if (!Int128Decl)
1260 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1261 return Int128Decl;
1262}
1263
1265 if (!UInt128Decl)
1266 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1267 return UInt128Decl;
1268}
1269
1270void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1271 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1273 Types.push_back(Ty);
1274}
1275
1277 const TargetInfo *AuxTarget) {
1278 assert((!this->Target || this->Target == &Target) &&
1279 "Incorrect target reinitialization");
1280 assert(VoidTy.isNull() && "Context reinitialized?");
1281
1282 this->Target = &Target;
1283 this->AuxTarget = AuxTarget;
1284
1285 ABI.reset(createCXXABI(Target));
1286 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1287
1288 // C99 6.2.5p19.
1289 InitBuiltinType(VoidTy, BuiltinType::Void);
1290
1291 // C99 6.2.5p2.
1292 InitBuiltinType(BoolTy, BuiltinType::Bool);
1293 // C99 6.2.5p3.
1294 if (LangOpts.CharIsSigned)
1295 InitBuiltinType(CharTy, BuiltinType::Char_S);
1296 else
1297 InitBuiltinType(CharTy, BuiltinType::Char_U);
1298 // C99 6.2.5p4.
1299 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1300 InitBuiltinType(ShortTy, BuiltinType::Short);
1301 InitBuiltinType(IntTy, BuiltinType::Int);
1302 InitBuiltinType(LongTy, BuiltinType::Long);
1303 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1304
1305 // C99 6.2.5p6.
1306 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1307 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1308 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1309 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1310 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1311
1312 // C99 6.2.5p10.
1313 InitBuiltinType(FloatTy, BuiltinType::Float);
1314 InitBuiltinType(DoubleTy, BuiltinType::Double);
1315 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1316
1317 // GNU extension, __float128 for IEEE quadruple precision
1318 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1319
1320 // __ibm128 for IBM extended precision
1321 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1322
1323 // C11 extension ISO/IEC TS 18661-3
1324 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1325
1326 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1327 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1328 InitBuiltinType(AccumTy, BuiltinType::Accum);
1329 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1330 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1331 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1332 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1333 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1334 InitBuiltinType(FractTy, BuiltinType::Fract);
1335 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1336 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1337 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1338 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1339 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1340 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1341 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1342 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1343 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1344 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1345 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1346 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1347 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1348 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1349 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1350 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1351
1352 // GNU extension, 128-bit integers.
1353 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1354 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1355
1356 // C++ 3.9.1p5
1357 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1358 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1359 else // -fshort-wchar makes wchar_t be unsigned.
1360 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1361 if (LangOpts.CPlusPlus && LangOpts.WChar)
1363 else {
1364 // C99 (or C++ using -fno-wchar).
1365 WideCharTy = getFromTargetType(Target.getWCharType());
1366 }
1367
1368 WIntTy = getFromTargetType(Target.getWIntType());
1369
1370 // C++20 (proposed)
1371 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1372
1373 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1374 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1375 else // C99
1376 Char16Ty = getFromTargetType(Target.getChar16Type());
1377
1378 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1379 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1380 else // C99
1381 Char32Ty = getFromTargetType(Target.getChar32Type());
1382
1383 // Placeholder type for type-dependent expressions whose type is
1384 // completely unknown. No code should ever check a type against
1385 // DependentTy and users should never see it; however, it is here to
1386 // help diagnose failures to properly check for type-dependent
1387 // expressions.
1388 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1389
1390 // Placeholder type for functions.
1391 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1392
1393 // Placeholder type for bound members.
1394 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1395
1396 // Placeholder type for unresolved templates.
1397 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1398
1399 // Placeholder type for pseudo-objects.
1400 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1401
1402 // "any" type; useful for debugger-like clients.
1403 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1404
1405 // Placeholder type for unbridged ARC casts.
1406 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1407
1408 // Placeholder type for builtin functions.
1409 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1410
1411 // Placeholder type for OMP array sections.
1412 if (LangOpts.OpenMP) {
1413 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1414 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1415 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1416 }
1417 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1418 // don't bother, as we're just using the same type as OMP.
1419 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1420 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1421 }
1422 if (LangOpts.MatrixTypes)
1423 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1424
1425 // Builtin types for 'id', 'Class', and 'SEL'.
1426 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1427 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1428 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1429
1430 if (LangOpts.OpenCL) {
1431#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1432 InitBuiltinType(SingletonId, BuiltinType::Id);
1433#include "clang/Basic/OpenCLImageTypes.def"
1434
1435 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1436 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1437 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1438 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1439 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1440
1441#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1442 InitBuiltinType(Id##Ty, BuiltinType::Id);
1443#include "clang/Basic/OpenCLExtensionTypes.def"
1444 }
1445
1446 if (LangOpts.HLSL) {
1447#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1448 InitBuiltinType(SingletonId, BuiltinType::Id);
1449#include "clang/Basic/HLSLIntangibleTypes.def"
1450 }
1451
1452 if (Target.hasAArch64ACLETypes() ||
1453 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1454#define SVE_TYPE(Name, Id, SingletonId) \
1455 InitBuiltinType(SingletonId, BuiltinType::Id);
1456#include "clang/Basic/AArch64ACLETypes.def"
1457 }
1458
1459 if (Target.getTriple().isPPC64()) {
1460#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1461 InitBuiltinType(Id##Ty, BuiltinType::Id);
1462#include "clang/Basic/PPCTypes.def"
1463#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1464 InitBuiltinType(Id##Ty, BuiltinType::Id);
1465#include "clang/Basic/PPCTypes.def"
1466 }
1467
1468 if (Target.hasRISCVVTypes()) {
1469#define RVV_TYPE(Name, Id, SingletonId) \
1470 InitBuiltinType(SingletonId, BuiltinType::Id);
1471#include "clang/Basic/RISCVVTypes.def"
1472 }
1473
1474 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1475#define WASM_TYPE(Name, Id, SingletonId) \
1476 InitBuiltinType(SingletonId, BuiltinType::Id);
1477#include "clang/Basic/WebAssemblyReferenceTypes.def"
1478 }
1479
1480 if (Target.getTriple().isAMDGPU() ||
1481 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1482#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1483 InitBuiltinType(SingletonId, BuiltinType::Id);
1484#include "clang/Basic/AMDGPUTypes.def"
1485 }
1486
1487 // Builtin type for __objc_yes and __objc_no
1488 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1490
1491 ObjCConstantStringType = QualType();
1492
1493 ObjCSuperType = QualType();
1494
1495 // void * type
1496 if (LangOpts.OpenCLGenericAddressSpace) {
1497 auto Q = VoidTy.getQualifiers();
1498 Q.setAddressSpace(LangAS::opencl_generic);
1500 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1501 } else {
1503 }
1504
1505 // nullptr type (C++0x 2.14.7)
1506 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1507
1508 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1509 InitBuiltinType(HalfTy, BuiltinType::Half);
1510
1511 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1512
1513 // Builtin type used to help define __builtin_va_list.
1514 VaListTagDecl = nullptr;
1515
1516 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1517 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1520 }
1521}
1522
1524 return SourceMgr.getDiagnostics();
1525}
1526
1528 AttrVec *&Result = DeclAttrs[D];
1529 if (!Result) {
1530 void *Mem = Allocate(sizeof(AttrVec));
1531 Result = new (Mem) AttrVec;
1532 }
1533
1534 return *Result;
1535}
1536
1537/// Erase the attributes corresponding to the given declaration.
1539 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1540 if (Pos != DeclAttrs.end()) {
1541 Pos->second->~AttrVec();
1542 DeclAttrs.erase(Pos);
1543 }
1544}
1545
1546// FIXME: Remove ?
1549 assert(Var->isStaticDataMember() && "Not a static data member");
1551 .dyn_cast<MemberSpecializationInfo *>();
1552}
1553
1556 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1557 TemplateOrInstantiation.find(Var);
1558 if (Pos == TemplateOrInstantiation.end())
1559 return {};
1560
1561 return Pos->second;
1562}
1563
1564void
1567 SourceLocation PointOfInstantiation) {
1568 assert(Inst->isStaticDataMember() && "Not a static data member");
1569 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1571 Tmpl, TSK, PointOfInstantiation));
1572}
1573
1574void
1577 assert(!TemplateOrInstantiation[Inst] &&
1578 "Already noted what the variable was instantiated from");
1579 TemplateOrInstantiation[Inst] = TSI;
1580}
1581
1582NamedDecl *
1584 return InstantiatedFromUsingDecl.lookup(UUD);
1585}
1586
1587void
1589 assert((isa<UsingDecl>(Pattern) ||
1592 "pattern decl is not a using decl");
1593 assert((isa<UsingDecl>(Inst) ||
1596 "instantiation did not produce a using decl");
1597 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1598 InstantiatedFromUsingDecl[Inst] = Pattern;
1599}
1600
1603 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1604}
1605
1607 UsingEnumDecl *Pattern) {
1608 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1609 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1610}
1611
1614 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1615}
1616
1617void
1619 UsingShadowDecl *Pattern) {
1620 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1621 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1622}
1623
1624FieldDecl *
1626 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1627}
1628
1630 FieldDecl *Tmpl) {
1631 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1632 "Instantiated field decl is not unnamed");
1633 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1634 "Template field decl is not unnamed");
1635 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1636 "Already noted what unnamed field was instantiated from");
1637
1638 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1639}
1640
1645
1650
1651unsigned
1653 auto Range = overridden_methods(Method);
1654 return Range.end() - Range.begin();
1655}
1656
1659 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1660 OverriddenMethods.find(Method->getCanonicalDecl());
1661 if (Pos == OverriddenMethods.end())
1662 return overridden_method_range(nullptr, nullptr);
1663 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1664}
1665
1667 const CXXMethodDecl *Overridden) {
1668 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1669 OverriddenMethods[Method].push_back(Overridden);
1670}
1671
1673 const NamedDecl *D,
1674 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1675 assert(D);
1676
1677 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1678 Overridden.append(overridden_methods_begin(CXXMethod),
1679 overridden_methods_end(CXXMethod));
1680 return;
1681 }
1682
1683 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1684 if (!Method)
1685 return;
1686
1688 Method->getOverriddenMethods(OverDecls);
1689 Overridden.append(OverDecls.begin(), OverDecls.end());
1690}
1691
1692std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1694 assert(RD);
1695 CXXRecordDecl *D = RD->getDefinition();
1696 auto it = RelocatableClasses.find(D);
1697 if (it != RelocatableClasses.end())
1698 return it->getSecond();
1699 return std::nullopt;
1700}
1701
1704 assert(RD);
1705 CXXRecordDecl *D = RD->getDefinition();
1706 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1707 RelocatableClasses.insert({D, Info});
1708}
1709
1711 const ASTContext &Context, const CXXRecordDecl *Class) {
1712 if (!Class->isPolymorphic())
1713 return false;
1714 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1715 using AuthAttr = VTablePointerAuthenticationAttr;
1716 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1717 if (!ExplicitAuth)
1718 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1719 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1720 ExplicitAuth->getAddressDiscrimination();
1721 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1722 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1723 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1724}
1725
1726ASTContext::PointerAuthContent
1727ASTContext::findPointerAuthContent(QualType T) const {
1728 assert(isPointerAuthenticationAvailable());
1729
1730 T = T.getCanonicalType();
1731 if (T.hasAddressDiscriminatedPointerAuth())
1732 return PointerAuthContent::AddressDiscriminatedData;
1733 const RecordDecl *RD = T->getAsRecordDecl();
1734 if (!RD)
1735 return PointerAuthContent::None;
1736
1737 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1738 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1739 return Existing->second;
1740
1741 PointerAuthContent Result = PointerAuthContent::None;
1742
1743 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1744 auto [ResultIter, DidAdd] =
1745 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1746 (void)ResultIter;
1747 (void)DidAdd;
1748 assert(DidAdd);
1749 return Result;
1750 };
1751 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1752 static_assert(PointerAuthContent::None <
1753 PointerAuthContent::AddressDiscriminatedVTable);
1754 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1755 PointerAuthContent::AddressDiscriminatedData);
1756 if (NewResult > Result)
1757 Result = NewResult;
1758 return Result != PointerAuthContent::AddressDiscriminatedData;
1759 };
1760 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1762 !ShouldContinueAfterUpdate(
1763 PointerAuthContent::AddressDiscriminatedVTable))
1764 return SaveResultAndReturn();
1765 for (auto Base : CXXRD->bases()) {
1766 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1767 return SaveResultAndReturn();
1768 }
1769 }
1770 for (auto *FieldDecl : RD->fields()) {
1771 if (!ShouldContinueAfterUpdate(
1772 findPointerAuthContent(FieldDecl->getType())))
1773 return SaveResultAndReturn();
1774 }
1775 return SaveResultAndReturn();
1776}
1777
1779 assert(!Import->getNextLocalImport() &&
1780 "Import declaration already in the chain");
1781 assert(!Import->isFromASTFile() && "Non-local import declaration");
1782 if (!FirstLocalImport) {
1783 FirstLocalImport = Import;
1784 LastLocalImport = Import;
1785 return;
1786 }
1787
1788 LastLocalImport->setNextLocalImport(Import);
1789 LastLocalImport = Import;
1790}
1791
1792//===----------------------------------------------------------------------===//
1793// Type Sizing and Analysis
1794//===----------------------------------------------------------------------===//
1795
1796/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1797/// scalar floating point type.
1798const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1799 switch (T->castAs<BuiltinType>()->getKind()) {
1800 default:
1801 llvm_unreachable("Not a floating point type!");
1802 case BuiltinType::BFloat16:
1803 return Target->getBFloat16Format();
1804 case BuiltinType::Float16:
1805 return Target->getHalfFormat();
1806 case BuiltinType::Half:
1807 return Target->getHalfFormat();
1808 case BuiltinType::Float: return Target->getFloatFormat();
1809 case BuiltinType::Double: return Target->getDoubleFormat();
1810 case BuiltinType::Ibm128:
1811 return Target->getIbm128Format();
1812 case BuiltinType::LongDouble:
1813 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1814 return AuxTarget->getLongDoubleFormat();
1815 return Target->getLongDoubleFormat();
1816 case BuiltinType::Float128:
1817 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1818 return AuxTarget->getFloat128Format();
1819 return Target->getFloat128Format();
1820 }
1821}
1822
1823CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1824 unsigned Align = Target->getCharWidth();
1825
1826 const unsigned AlignFromAttr = D->getMaxAlignment();
1827 if (AlignFromAttr)
1828 Align = AlignFromAttr;
1829
1830 // __attribute__((aligned)) can increase or decrease alignment
1831 // *except* on a struct or struct member, where it only increases
1832 // alignment unless 'packed' is also specified.
1833 //
1834 // It is an error for alignas to decrease alignment, so we can
1835 // ignore that possibility; Sema should diagnose it.
1836 bool UseAlignAttrOnly;
1837 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1838 UseAlignAttrOnly =
1839 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1840 else
1841 UseAlignAttrOnly = AlignFromAttr != 0;
1842 // If we're using the align attribute only, just ignore everything
1843 // else about the declaration and its type.
1844 if (UseAlignAttrOnly) {
1845 // do nothing
1846 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1847 QualType T = VD->getType();
1848 if (const auto *RT = T->getAs<ReferenceType>()) {
1849 if (ForAlignof)
1850 T = RT->getPointeeType();
1851 else
1852 T = getPointerType(RT->getPointeeType());
1853 }
1854 QualType BaseT = getBaseElementType(T);
1855 if (T->isFunctionType())
1856 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1857 else if (!BaseT->isIncompleteType()) {
1858 // Adjust alignments of declarations with array type by the
1859 // large-array alignment on the target.
1860 if (const ArrayType *arrayType = getAsArrayType(T)) {
1861 unsigned MinWidth = Target->getLargeArrayMinWidth();
1862 if (!ForAlignof && MinWidth) {
1864 Align = std::max(Align, Target->getLargeArrayAlign());
1867 Align = std::max(Align, Target->getLargeArrayAlign());
1868 }
1869 }
1870 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1871 if (BaseT.getQualifiers().hasUnaligned())
1872 Align = Target->getCharWidth();
1873 }
1874
1875 // Ensure minimum alignment for global variables.
1876 if (const auto *VD = dyn_cast<VarDecl>(D))
1877 if (VD->hasGlobalStorage() && !ForAlignof) {
1878 uint64_t TypeSize =
1879 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1880 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1881 }
1882
1883 // Fields can be subject to extra alignment constraints, like if
1884 // the field is packed, the struct is packed, or the struct has a
1885 // a max-field-alignment constraint (#pragma pack). So calculate
1886 // the actual alignment of the field within the struct, and then
1887 // (as we're expected to) constrain that by the alignment of the type.
1888 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1889 const RecordDecl *Parent = Field->getParent();
1890 // We can only produce a sensible answer if the record is valid.
1891 if (!Parent->isInvalidDecl()) {
1892 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1893
1894 // Start with the record's overall alignment.
1895 unsigned FieldAlign = toBits(Layout.getAlignment());
1896
1897 // Use the GCD of that and the offset within the record.
1898 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1899 if (Offset > 0) {
1900 // Alignment is always a power of 2, so the GCD will be a power of 2,
1901 // which means we get to do this crazy thing instead of Euclid's.
1902 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1903 if (LowBitOfOffset < FieldAlign)
1904 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1905 }
1906
1907 Align = std::min(Align, FieldAlign);
1908 }
1909 }
1910 }
1911
1912 // Some targets have hard limitation on the maximum requestable alignment in
1913 // aligned attribute for static variables.
1914 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1915 const auto *VD = dyn_cast<VarDecl>(D);
1916 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1917 Align = std::min(Align, MaxAlignedAttr);
1918
1919 return toCharUnitsFromBits(Align);
1920}
1921
1923 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1924}
1925
1926// getTypeInfoDataSizeInChars - Return the size of a type, in
1927// chars. If the type is a record, its data size is returned. This is
1928// the size of the memcpy that's performed when assigning this type
1929// using a trivial copy/move assignment operator.
1932
1933 // In C++, objects can sometimes be allocated into the tail padding
1934 // of a base-class subobject. We decide whether that's possible
1935 // during class layout, so here we can just trust the layout results.
1936 if (getLangOpts().CPlusPlus) {
1937 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1938 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1939 Info.Width = layout.getDataSize();
1940 }
1941 }
1942
1943 return Info;
1944}
1945
1946/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1947/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1950 const ConstantArrayType *CAT) {
1951 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1952 uint64_t Size = CAT->getZExtSize();
1953 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1954 (uint64_t)(-1)/Size) &&
1955 "Overflow in array type char size evaluation");
1956 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1957 unsigned Align = EltInfo.Align.getQuantity();
1958 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1959 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1960 Width = llvm::alignTo(Width, Align);
1963 EltInfo.AlignRequirement);
1964}
1965
1967 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1968 return getConstantArrayInfoInChars(*this, CAT);
1969 TypeInfo Info = getTypeInfo(T);
1972}
1973
1977
1979 // HLSL doesn't promote all small integer types to int, it
1980 // just uses the rank-based promotion rules for all types.
1981 if (getLangOpts().HLSL)
1982 return false;
1983
1984 if (const auto *BT = T->getAs<BuiltinType>())
1985 switch (BT->getKind()) {
1986 case BuiltinType::Bool:
1987 case BuiltinType::Char_S:
1988 case BuiltinType::Char_U:
1989 case BuiltinType::SChar:
1990 case BuiltinType::UChar:
1991 case BuiltinType::Short:
1992 case BuiltinType::UShort:
1993 case BuiltinType::WChar_S:
1994 case BuiltinType::WChar_U:
1995 case BuiltinType::Char8:
1996 case BuiltinType::Char16:
1997 case BuiltinType::Char32:
1998 return true;
1999 default:
2000 return false;
2001 }
2002
2003 // Enumerated types are promotable to their compatible integer types
2004 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2005 if (const auto *ED = T->getAsEnumDecl()) {
2006 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2007 ED->isScoped())
2008 return false;
2009
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
2019
2021 return isAlignmentRequired(T.getTypePtr());
2022}
2023
2025 bool NeedsPreferredAlignment) const {
2026 // An alignment on a typedef overrides anything else.
2027 if (const auto *TT = T->getAs<TypedefType>())
2028 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2029 return Align;
2030
2031 // If we have an (array of) complete type, we're done.
2033 if (!T->isIncompleteType())
2034 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2035
2036 // If we had an array type, its element type might be a typedef
2037 // type with an alignment attribute.
2038 if (const auto *TT = T->getAs<TypedefType>())
2039 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2040 return Align;
2041
2042 // Otherwise, see if the declaration of the type had an attribute.
2043 if (const auto *TD = T->getAsTagDecl())
2044 return TD->getMaxAlignment();
2045
2046 return 0;
2047}
2048
2050 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2051 if (I != MemoizedTypeInfo.end())
2052 return I->second;
2053
2054 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2055 TypeInfo TI = getTypeInfoImpl(T);
2056 MemoizedTypeInfo[T] = TI;
2057 return TI;
2058}
2059
2060/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2061/// method does not work on incomplete types.
2062///
2063/// FIXME: Pointers into different addr spaces could have different sizes and
2064/// alignment requirements: getPointerInfo should take an AddrSpace, this
2065/// should take a QualType, &c.
2066TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2067 uint64_t Width = 0;
2068 unsigned Align = 8;
2071 switch (T->getTypeClass()) {
2072#define TYPE(Class, Base)
2073#define ABSTRACT_TYPE(Class, Base)
2074#define NON_CANONICAL_TYPE(Class, Base)
2075#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2076#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2077 case Type::Class: \
2078 assert(!T->isDependentType() && "should not see dependent types here"); \
2079 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2080#include "clang/AST/TypeNodes.inc"
2081 llvm_unreachable("Should not see dependent types");
2082
2083 case Type::FunctionNoProto:
2084 case Type::FunctionProto:
2085 // GCC extension: alignof(function) = 32 bits
2086 Width = 0;
2087 Align = 32;
2088 break;
2089
2090 case Type::IncompleteArray:
2091 case Type::VariableArray:
2092 case Type::ConstantArray:
2093 case Type::ArrayParameter: {
2094 // Model non-constant sized arrays as size zero, but track the alignment.
2095 uint64_t Size = 0;
2096 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2097 Size = CAT->getZExtSize();
2098
2099 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2100 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2101 "Overflow in array type bit size evaluation");
2102 Width = EltInfo.Width * Size;
2103 Align = EltInfo.Align;
2104 AlignRequirement = EltInfo.AlignRequirement;
2105 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2106 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2107 Width = llvm::alignTo(Width, Align);
2108 break;
2109 }
2110
2111 case Type::ExtVector:
2112 case Type::Vector: {
2113 const auto *VT = cast<VectorType>(T);
2114 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2115 Width = VT->isPackedVectorBoolType(*this)
2116 ? VT->getNumElements()
2117 : EltInfo.Width * VT->getNumElements();
2118 // Enforce at least byte size and alignment.
2119 Width = std::max<unsigned>(8, Width);
2120 Align = std::max<unsigned>(8, Width);
2121
2122 // If the alignment is not a power of 2, round up to the next power of 2.
2123 // This happens for non-power-of-2 length vectors.
2124 if (Align & (Align-1)) {
2125 Align = llvm::bit_ceil(Align);
2126 Width = llvm::alignTo(Width, Align);
2127 }
2128 // Adjust the alignment based on the target max.
2129 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2130 if (TargetVectorAlign && TargetVectorAlign < Align)
2131 Align = TargetVectorAlign;
2132 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2133 // Adjust the alignment for fixed-length SVE vectors. This is important
2134 // for non-power-of-2 vector lengths.
2135 Align = 128;
2136 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2137 // Adjust the alignment for fixed-length SVE predicates.
2138 Align = 16;
2139 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2140 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2141 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2142 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2143 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2144 // Adjust the alignment for fixed-length RVV vectors.
2145 Align = std::min<unsigned>(64, Width);
2146 break;
2147 }
2148
2149 case Type::ConstantMatrix: {
2150 const auto *MT = cast<ConstantMatrixType>(T);
2151 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2152 // The internal layout of a matrix value is implementation defined.
2153 // Initially be ABI compatible with arrays with respect to alignment and
2154 // size.
2155 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2156 Align = ElementInfo.Align;
2157 break;
2158 }
2159
2160 case Type::Builtin:
2161 switch (cast<BuiltinType>(T)->getKind()) {
2162 default: llvm_unreachable("Unknown builtin type!");
2163 case BuiltinType::Void:
2164 // GCC extension: alignof(void) = 8 bits.
2165 Width = 0;
2166 Align = 8;
2167 break;
2168 case BuiltinType::Bool:
2169 Width = Target->getBoolWidth();
2170 Align = Target->getBoolAlign();
2171 break;
2172 case BuiltinType::Char_S:
2173 case BuiltinType::Char_U:
2174 case BuiltinType::UChar:
2175 case BuiltinType::SChar:
2176 case BuiltinType::Char8:
2177 Width = Target->getCharWidth();
2178 Align = Target->getCharAlign();
2179 break;
2180 case BuiltinType::WChar_S:
2181 case BuiltinType::WChar_U:
2182 Width = Target->getWCharWidth();
2183 Align = Target->getWCharAlign();
2184 break;
2185 case BuiltinType::Char16:
2186 Width = Target->getChar16Width();
2187 Align = Target->getChar16Align();
2188 break;
2189 case BuiltinType::Char32:
2190 Width = Target->getChar32Width();
2191 Align = Target->getChar32Align();
2192 break;
2193 case BuiltinType::UShort:
2194 case BuiltinType::Short:
2195 Width = Target->getShortWidth();
2196 Align = Target->getShortAlign();
2197 break;
2198 case BuiltinType::UInt:
2199 case BuiltinType::Int:
2200 Width = Target->getIntWidth();
2201 Align = Target->getIntAlign();
2202 break;
2203 case BuiltinType::ULong:
2204 case BuiltinType::Long:
2205 Width = Target->getLongWidth();
2206 Align = Target->getLongAlign();
2207 break;
2208 case BuiltinType::ULongLong:
2209 case BuiltinType::LongLong:
2210 Width = Target->getLongLongWidth();
2211 Align = Target->getLongLongAlign();
2212 break;
2213 case BuiltinType::Int128:
2214 case BuiltinType::UInt128:
2215 Width = 128;
2216 Align = Target->getInt128Align();
2217 break;
2218 case BuiltinType::ShortAccum:
2219 case BuiltinType::UShortAccum:
2220 case BuiltinType::SatShortAccum:
2221 case BuiltinType::SatUShortAccum:
2222 Width = Target->getShortAccumWidth();
2223 Align = Target->getShortAccumAlign();
2224 break;
2225 case BuiltinType::Accum:
2226 case BuiltinType::UAccum:
2227 case BuiltinType::SatAccum:
2228 case BuiltinType::SatUAccum:
2229 Width = Target->getAccumWidth();
2230 Align = Target->getAccumAlign();
2231 break;
2232 case BuiltinType::LongAccum:
2233 case BuiltinType::ULongAccum:
2234 case BuiltinType::SatLongAccum:
2235 case BuiltinType::SatULongAccum:
2236 Width = Target->getLongAccumWidth();
2237 Align = Target->getLongAccumAlign();
2238 break;
2239 case BuiltinType::ShortFract:
2240 case BuiltinType::UShortFract:
2241 case BuiltinType::SatShortFract:
2242 case BuiltinType::SatUShortFract:
2243 Width = Target->getShortFractWidth();
2244 Align = Target->getShortFractAlign();
2245 break;
2246 case BuiltinType::Fract:
2247 case BuiltinType::UFract:
2248 case BuiltinType::SatFract:
2249 case BuiltinType::SatUFract:
2250 Width = Target->getFractWidth();
2251 Align = Target->getFractAlign();
2252 break;
2253 case BuiltinType::LongFract:
2254 case BuiltinType::ULongFract:
2255 case BuiltinType::SatLongFract:
2256 case BuiltinType::SatULongFract:
2257 Width = Target->getLongFractWidth();
2258 Align = Target->getLongFractAlign();
2259 break;
2260 case BuiltinType::BFloat16:
2261 if (Target->hasBFloat16Type()) {
2262 Width = Target->getBFloat16Width();
2263 Align = Target->getBFloat16Align();
2264 } else if ((getLangOpts().SYCLIsDevice ||
2265 (getLangOpts().OpenMP &&
2266 getLangOpts().OpenMPIsTargetDevice)) &&
2267 AuxTarget->hasBFloat16Type()) {
2268 Width = AuxTarget->getBFloat16Width();
2269 Align = AuxTarget->getBFloat16Align();
2270 }
2271 break;
2272 case BuiltinType::Float16:
2273 case BuiltinType::Half:
2274 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2275 !getLangOpts().OpenMPIsTargetDevice) {
2276 Width = Target->getHalfWidth();
2277 Align = Target->getHalfAlign();
2278 } else {
2279 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2280 "Expected OpenMP device compilation.");
2281 Width = AuxTarget->getHalfWidth();
2282 Align = AuxTarget->getHalfAlign();
2283 }
2284 break;
2285 case BuiltinType::Float:
2286 Width = Target->getFloatWidth();
2287 Align = Target->getFloatAlign();
2288 break;
2289 case BuiltinType::Double:
2290 Width = Target->getDoubleWidth();
2291 Align = Target->getDoubleAlign();
2292 break;
2293 case BuiltinType::Ibm128:
2294 Width = Target->getIbm128Width();
2295 Align = Target->getIbm128Align();
2296 break;
2297 case BuiltinType::LongDouble:
2298 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2299 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2300 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2301 Width = AuxTarget->getLongDoubleWidth();
2302 Align = AuxTarget->getLongDoubleAlign();
2303 } else {
2304 Width = Target->getLongDoubleWidth();
2305 Align = Target->getLongDoubleAlign();
2306 }
2307 break;
2308 case BuiltinType::Float128:
2309 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2310 !getLangOpts().OpenMPIsTargetDevice) {
2311 Width = Target->getFloat128Width();
2312 Align = Target->getFloat128Align();
2313 } else {
2314 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2315 "Expected OpenMP device compilation.");
2316 Width = AuxTarget->getFloat128Width();
2317 Align = AuxTarget->getFloat128Align();
2318 }
2319 break;
2320 case BuiltinType::NullPtr:
2321 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2322 Width = Target->getPointerWidth(LangAS::Default);
2323 Align = Target->getPointerAlign(LangAS::Default);
2324 break;
2325 case BuiltinType::ObjCId:
2326 case BuiltinType::ObjCClass:
2327 case BuiltinType::ObjCSel:
2328 Width = Target->getPointerWidth(LangAS::Default);
2329 Align = Target->getPointerAlign(LangAS::Default);
2330 break;
2331 case BuiltinType::OCLSampler:
2332 case BuiltinType::OCLEvent:
2333 case BuiltinType::OCLClkEvent:
2334 case BuiltinType::OCLQueue:
2335 case BuiltinType::OCLReserveID:
2336#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2337 case BuiltinType::Id:
2338#include "clang/Basic/OpenCLImageTypes.def"
2339#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2340 case BuiltinType::Id:
2341#include "clang/Basic/OpenCLExtensionTypes.def"
2342 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2343 Width = Target->getPointerWidth(AS);
2344 Align = Target->getPointerAlign(AS);
2345 break;
2346 // The SVE types are effectively target-specific. The length of an
2347 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2348 // of 128 bits. There is one predicate bit for each vector byte, so the
2349 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2350 //
2351 // Because the length is only known at runtime, we use a dummy value
2352 // of 0 for the static length. The alignment values are those defined
2353 // by the Procedure Call Standard for the Arm Architecture.
2354#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2355 case BuiltinType::Id: \
2356 Width = 0; \
2357 Align = 128; \
2358 break;
2359#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2360 case BuiltinType::Id: \
2361 Width = 0; \
2362 Align = 16; \
2363 break;
2364#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2365 case BuiltinType::Id: \
2366 Width = 0; \
2367 Align = 16; \
2368 break;
2369#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2370 case BuiltinType::Id: \
2371 Width = Bits; \
2372 Align = Bits; \
2373 break;
2374#include "clang/Basic/AArch64ACLETypes.def"
2375#define PPC_VECTOR_TYPE(Name, Id, Size) \
2376 case BuiltinType::Id: \
2377 Width = Size; \
2378 Align = Size; \
2379 break;
2380#include "clang/Basic/PPCTypes.def"
2381#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2382 IsFP, IsBF) \
2383 case BuiltinType::Id: \
2384 Width = 0; \
2385 Align = ElBits; \
2386 break;
2387#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2388 case BuiltinType::Id: \
2389 Width = 0; \
2390 Align = 8; \
2391 break;
2392#include "clang/Basic/RISCVVTypes.def"
2393#define WASM_TYPE(Name, Id, SingletonId) \
2394 case BuiltinType::Id: \
2395 Width = 0; \
2396 Align = 8; \
2397 break;
2398#include "clang/Basic/WebAssemblyReferenceTypes.def"
2399#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2400 case BuiltinType::ID: \
2401 Width = WIDTH; \
2402 Align = ALIGN; \
2403 break;
2404#include "clang/Basic/AMDGPUTypes.def"
2405#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2406#include "clang/Basic/HLSLIntangibleTypes.def"
2407 Width = Target->getPointerWidth(LangAS::Default);
2408 Align = Target->getPointerAlign(LangAS::Default);
2409 break;
2410 }
2411 break;
2412 case Type::ObjCObjectPointer:
2413 Width = Target->getPointerWidth(LangAS::Default);
2414 Align = Target->getPointerAlign(LangAS::Default);
2415 break;
2416 case Type::BlockPointer:
2417 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2418 Width = Target->getPointerWidth(AS);
2419 Align = Target->getPointerAlign(AS);
2420 break;
2421 case Type::LValueReference:
2422 case Type::RValueReference:
2423 // alignof and sizeof should never enter this code path here, so we go
2424 // the pointer route.
2425 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2426 Width = Target->getPointerWidth(AS);
2427 Align = Target->getPointerAlign(AS);
2428 break;
2429 case Type::Pointer:
2430 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2431 Width = Target->getPointerWidth(AS);
2432 Align = Target->getPointerAlign(AS);
2433 break;
2434 case Type::MemberPointer: {
2435 const auto *MPT = cast<MemberPointerType>(T);
2436 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2437 Width = MPI.Width;
2438 Align = MPI.Align;
2439 break;
2440 }
2441 case Type::Complex: {
2442 // Complex types have the same alignment as their elements, but twice the
2443 // size.
2444 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2445 Width = EltInfo.Width * 2;
2446 Align = EltInfo.Align;
2447 break;
2448 }
2449 case Type::ObjCObject:
2450 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2451 case Type::Adjusted:
2452 case Type::Decayed:
2453 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2454 case Type::ObjCInterface: {
2455 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2456 if (ObjCI->getDecl()->isInvalidDecl()) {
2457 Width = 8;
2458 Align = 8;
2459 break;
2460 }
2461 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2462 Width = toBits(Layout.getSize());
2463 Align = toBits(Layout.getAlignment());
2464 break;
2465 }
2466 case Type::BitInt: {
2467 const auto *EIT = cast<BitIntType>(T);
2468 Align = Target->getBitIntAlign(EIT->getNumBits());
2469 Width = Target->getBitIntWidth(EIT->getNumBits());
2470 break;
2471 }
2472 case Type::Record:
2473 case Type::Enum: {
2474 const auto *TT = cast<TagType>(T);
2475 const TagDecl *TD = TT->getOriginalDecl()->getDefinitionOrSelf();
2476
2477 if (TD->isInvalidDecl()) {
2478 Width = 8;
2479 Align = 8;
2480 break;
2481 }
2482
2483 if (isa<EnumType>(TT)) {
2484 const EnumDecl *ED = cast<EnumDecl>(TD);
2485 TypeInfo Info =
2487 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2488 Info.Align = AttrAlign;
2490 }
2491 return Info;
2492 }
2493
2494 const auto *RD = cast<RecordDecl>(TD);
2495 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2496 Width = toBits(Layout.getSize());
2497 Align = toBits(Layout.getAlignment());
2498 AlignRequirement = RD->hasAttr<AlignedAttr>()
2500 : AlignRequirementKind::None;
2501 break;
2502 }
2503
2504 case Type::SubstTemplateTypeParm:
2506 getReplacementType().getTypePtr());
2507
2508 case Type::Auto:
2509 case Type::DeducedTemplateSpecialization: {
2510 const auto *A = cast<DeducedType>(T);
2511 assert(!A->getDeducedType().isNull() &&
2512 "cannot request the size of an undeduced or dependent auto type");
2513 return getTypeInfo(A->getDeducedType().getTypePtr());
2514 }
2515
2516 case Type::Paren:
2517 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2518
2519 case Type::MacroQualified:
2520 return getTypeInfo(
2522
2523 case Type::ObjCTypeParam:
2524 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2525
2526 case Type::Using:
2527 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2528
2529 case Type::Typedef: {
2530 const auto *TT = cast<TypedefType>(T);
2531 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2532 // If the typedef has an aligned attribute on it, it overrides any computed
2533 // alignment we have. This violates the GCC documentation (which says that
2534 // attribute(aligned) can only round up) but matches its implementation.
2535 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2536 Align = AttrAlign;
2537 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2538 } else {
2539 Align = Info.Align;
2540 AlignRequirement = Info.AlignRequirement;
2541 }
2542 Width = Info.Width;
2543 break;
2544 }
2545
2546 case Type::Attributed:
2547 return getTypeInfo(
2548 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2549
2550 case Type::CountAttributed:
2551 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2552
2553 case Type::BTFTagAttributed:
2554 return getTypeInfo(
2555 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2556
2557 case Type::HLSLAttributedResource:
2558 return getTypeInfo(
2559 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2560
2561 case Type::HLSLInlineSpirv: {
2562 const auto *ST = cast<HLSLInlineSpirvType>(T);
2563 // Size is specified in bytes, convert to bits
2564 Width = ST->getSize() * 8;
2565 Align = ST->getAlignment();
2566 if (Width == 0 && Align == 0) {
2567 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2568 Width = 32;
2569 Align = 32;
2570 }
2571 break;
2572 }
2573
2574 case Type::Atomic: {
2575 // Start with the base type information.
2576 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2577 Width = Info.Width;
2578 Align = Info.Align;
2579
2580 if (!Width) {
2581 // An otherwise zero-sized type should still generate an
2582 // atomic operation.
2583 Width = Target->getCharWidth();
2584 assert(Align);
2585 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2586 // If the size of the type doesn't exceed the platform's max
2587 // atomic promotion width, make the size and alignment more
2588 // favorable to atomic operations:
2589
2590 // Round the size up to a power of 2.
2591 Width = llvm::bit_ceil(Width);
2592
2593 // Set the alignment equal to the size.
2594 Align = static_cast<unsigned>(Width);
2595 }
2596 }
2597 break;
2598
2599 case Type::PredefinedSugar:
2600 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2601
2602 case Type::Pipe:
2603 Width = Target->getPointerWidth(LangAS::opencl_global);
2604 Align = Target->getPointerAlign(LangAS::opencl_global);
2605 break;
2606 }
2607
2608 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2609 return TypeInfo(Width, Align, AlignRequirement);
2610}
2611
2613 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2614 if (I != MemoizedUnadjustedAlign.end())
2615 return I->second;
2616
2617 unsigned UnadjustedAlign;
2618 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2619 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getOriginalDecl());
2620 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2621 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2622 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2623 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2624 } else {
2625 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2626 }
2627
2628 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2629 return UnadjustedAlign;
2630}
2631
2633 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2634 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2635 return SimdAlign;
2636}
2637
2638/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2640 return CharUnits::fromQuantity(BitSize / getCharWidth());
2641}
2642
2643/// toBits - Convert a size in characters to a size in characters.
2644int64_t ASTContext::toBits(CharUnits CharSize) const {
2645 return CharSize.getQuantity() * getCharWidth();
2646}
2647
2648/// getTypeSizeInChars - Return the size of the specified type, in characters.
2649/// This method does not work on incomplete types.
2656
2657/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2658/// characters. This method does not work on incomplete types.
2665
2666/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2667/// type, in characters, before alignment adjustments. This method does
2668/// not work on incomplete types.
2675
2676/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2677/// type for the current target in bits. This can be different than the ABI
2678/// alignment in cases where it is beneficial for performance or backwards
2679/// compatibility preserving to overalign a data type. (Note: despite the name,
2680/// the preferred alignment is ABI-impacting, and not an optimization.)
2682 TypeInfo TI = getTypeInfo(T);
2683 unsigned ABIAlign = TI.Align;
2684
2685 T = T->getBaseElementTypeUnsafe();
2686
2687 // The preferred alignment of member pointers is that of a pointer.
2688 if (T->isMemberPointerType())
2689 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2690
2691 if (!Target->allowsLargerPreferedTypeAlignment())
2692 return ABIAlign;
2693
2694 if (const auto *RD = T->getAsRecordDecl()) {
2695 // When used as part of a typedef, or together with a 'packed' attribute,
2696 // the 'aligned' attribute can be used to decrease alignment. Note that the
2697 // 'packed' case is already taken into consideration when computing the
2698 // alignment, we only need to handle the typedef case here.
2700 RD->isInvalidDecl())
2701 return ABIAlign;
2702
2703 unsigned PreferredAlign = static_cast<unsigned>(
2704 toBits(getASTRecordLayout(RD).PreferredAlignment));
2705 assert(PreferredAlign >= ABIAlign &&
2706 "PreferredAlign should be at least as large as ABIAlign.");
2707 return PreferredAlign;
2708 }
2709
2710 // Double (and, for targets supporting AIX `power` alignment, long double) and
2711 // long long should be naturally aligned (despite requiring less alignment) if
2712 // possible.
2713 if (const auto *CT = T->getAs<ComplexType>())
2714 T = CT->getElementType().getTypePtr();
2715 if (const auto *ED = T->getAsEnumDecl())
2716 T = ED->getIntegerType().getTypePtr();
2717 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2718 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2719 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2720 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2721 Target->defaultsToAIXPowerAlignment()))
2722 // Don't increase the alignment if an alignment attribute was specified on a
2723 // typedef declaration.
2724 if (!TI.isAlignRequired())
2725 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2726
2727 return ABIAlign;
2728}
2729
2730/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2731/// for __attribute__((aligned)) on this target, to be used if no alignment
2732/// value is specified.
2736
2737/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2738/// to a global variable of the specified type.
2740 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2741 return std::max(getPreferredTypeAlign(T),
2742 getMinGlobalAlignOfVar(TypeSize, VD));
2743}
2744
2745/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2746/// should be given to a global variable of the specified type.
2751
2753 const VarDecl *VD) const {
2754 // Make the default handling as that of a non-weak definition in the
2755 // current translation unit.
2756 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2757 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2758}
2759
2761 CharUnits Offset = CharUnits::Zero();
2762 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2763 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2764 Offset += Layout->getBaseClassOffset(Base);
2765 Layout = &getASTRecordLayout(Base);
2766 }
2767 return Offset;
2768}
2769
2771 const ValueDecl *MPD = MP.getMemberPointerDecl();
2774 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2776 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2777 const CXXRecordDecl *Base = RD;
2778 const CXXRecordDecl *Derived = Path[I];
2779 if (DerivedMember)
2780 std::swap(Base, Derived);
2782 RD = Path[I];
2783 }
2784 if (DerivedMember)
2786 return ThisAdjustment;
2787}
2788
2789/// DeepCollectObjCIvars -
2790/// This routine first collects all declared, but not synthesized, ivars in
2791/// super class and then collects all ivars, including those synthesized for
2792/// current class. This routine is used for implementation of current class
2793/// when all ivars, declared and synthesized are known.
2795 bool leafClass,
2797 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2798 DeepCollectObjCIvars(SuperClass, false, Ivars);
2799 if (!leafClass) {
2800 llvm::append_range(Ivars, OI->ivars());
2801 } else {
2802 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2803 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2804 Iv= Iv->getNextIvar())
2805 Ivars.push_back(Iv);
2806 }
2807}
2808
2809/// CollectInheritedProtocols - Collect all protocols in current class and
2810/// those inherited by it.
2813 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2814 // We can use protocol_iterator here instead of
2815 // all_referenced_protocol_iterator since we are walking all categories.
2816 for (auto *Proto : OI->all_referenced_protocols()) {
2817 CollectInheritedProtocols(Proto, Protocols);
2818 }
2819
2820 // Categories of this Interface.
2821 for (const auto *Cat : OI->visible_categories())
2822 CollectInheritedProtocols(Cat, Protocols);
2823
2824 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2825 while (SD) {
2826 CollectInheritedProtocols(SD, Protocols);
2827 SD = SD->getSuperClass();
2828 }
2829 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2830 for (auto *Proto : OC->protocols()) {
2831 CollectInheritedProtocols(Proto, Protocols);
2832 }
2833 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2834 // Insert the protocol.
2835 if (!Protocols.insert(
2836 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2837 return;
2838
2839 for (auto *Proto : OP->protocols())
2840 CollectInheritedProtocols(Proto, Protocols);
2841 }
2842}
2843
2845 const RecordDecl *RD,
2846 bool CheckIfTriviallyCopyable) {
2847 assert(RD->isUnion() && "Must be union type");
2848 CharUnits UnionSize =
2849 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2850
2851 for (const auto *Field : RD->fields()) {
2852 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2853 CheckIfTriviallyCopyable))
2854 return false;
2855 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2856 if (FieldSize != UnionSize)
2857 return false;
2858 }
2859 return !RD->field_empty();
2860}
2861
2862static int64_t getSubobjectOffset(const FieldDecl *Field,
2863 const ASTContext &Context,
2864 const clang::ASTRecordLayout & /*Layout*/) {
2865 return Context.getFieldOffset(Field);
2866}
2867
2868static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2869 const ASTContext &Context,
2870 const clang::ASTRecordLayout &Layout) {
2871 return Context.toBits(Layout.getBaseClassOffset(RD));
2872}
2873
2874static std::optional<int64_t>
2876 const RecordDecl *RD,
2877 bool CheckIfTriviallyCopyable);
2878
2879static std::optional<int64_t>
2880getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2881 bool CheckIfTriviallyCopyable) {
2882 if (const auto *RD = Field->getType()->getAsRecordDecl();
2883 RD && !RD->isUnion())
2884 return structHasUniqueObjectRepresentations(Context, RD,
2885 CheckIfTriviallyCopyable);
2886
2887 // A _BitInt type may not be unique if it has padding bits
2888 // but if it is a bitfield the padding bits are not used.
2889 bool IsBitIntType = Field->getType()->isBitIntType();
2890 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2891 !Context.hasUniqueObjectRepresentations(Field->getType(),
2892 CheckIfTriviallyCopyable))
2893 return std::nullopt;
2894
2895 int64_t FieldSizeInBits =
2896 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2897 if (Field->isBitField()) {
2898 // If we have explicit padding bits, they don't contribute bits
2899 // to the actual object representation, so return 0.
2900 if (Field->isUnnamedBitField())
2901 return 0;
2902
2903 int64_t BitfieldSize = Field->getBitWidthValue();
2904 if (IsBitIntType) {
2905 if ((unsigned)BitfieldSize >
2906 cast<BitIntType>(Field->getType())->getNumBits())
2907 return std::nullopt;
2908 } else if (BitfieldSize > FieldSizeInBits) {
2909 return std::nullopt;
2910 }
2911 FieldSizeInBits = BitfieldSize;
2912 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2913 Field->getType(), CheckIfTriviallyCopyable)) {
2914 return std::nullopt;
2915 }
2916 return FieldSizeInBits;
2917}
2918
2919static std::optional<int64_t>
2921 bool CheckIfTriviallyCopyable) {
2922 return structHasUniqueObjectRepresentations(Context, RD,
2923 CheckIfTriviallyCopyable);
2924}
2925
2926template <typename RangeT>
2928 const RangeT &Subobjects, int64_t CurOffsetInBits,
2929 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2930 bool CheckIfTriviallyCopyable) {
2931 for (const auto *Subobject : Subobjects) {
2932 std::optional<int64_t> SizeInBits =
2933 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2934 if (!SizeInBits)
2935 return std::nullopt;
2936 if (*SizeInBits != 0) {
2937 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2938 if (Offset != CurOffsetInBits)
2939 return std::nullopt;
2940 CurOffsetInBits += *SizeInBits;
2941 }
2942 }
2943 return CurOffsetInBits;
2944}
2945
2946static std::optional<int64_t>
2948 const RecordDecl *RD,
2949 bool CheckIfTriviallyCopyable) {
2950 assert(!RD->isUnion() && "Must be struct/class type");
2951 const auto &Layout = Context.getASTRecordLayout(RD);
2952
2953 int64_t CurOffsetInBits = 0;
2954 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2955 if (ClassDecl->isDynamicClass())
2956 return std::nullopt;
2957
2959 for (const auto &Base : ClassDecl->bases()) {
2960 // Empty types can be inherited from, and non-empty types can potentially
2961 // have tail padding, so just make sure there isn't an error.
2962 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2963 }
2964
2965 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2966 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2967 });
2968
2969 std::optional<int64_t> OffsetAfterBases =
2971 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2972 if (!OffsetAfterBases)
2973 return std::nullopt;
2974 CurOffsetInBits = *OffsetAfterBases;
2975 }
2976
2977 std::optional<int64_t> OffsetAfterFields =
2979 RD->fields(), CurOffsetInBits, Context, Layout,
2980 CheckIfTriviallyCopyable);
2981 if (!OffsetAfterFields)
2982 return std::nullopt;
2983 CurOffsetInBits = *OffsetAfterFields;
2984
2985 return CurOffsetInBits;
2986}
2987
2989 QualType Ty, bool CheckIfTriviallyCopyable) const {
2990 // C++17 [meta.unary.prop]:
2991 // The predicate condition for a template specialization
2992 // has_unique_object_representations<T> shall be satisfied if and only if:
2993 // (9.1) - T is trivially copyable, and
2994 // (9.2) - any two objects of type T with the same value have the same
2995 // object representation, where:
2996 // - two objects of array or non-union class type are considered to have
2997 // the same value if their respective sequences of direct subobjects
2998 // have the same values, and
2999 // - two objects of union type are considered to have the same value if
3000 // they have the same active member and the corresponding members have
3001 // the same value.
3002 // The set of scalar types for which this condition holds is
3003 // implementation-defined. [ Note: If a type has padding bits, the condition
3004 // does not hold; otherwise, the condition holds true for unsigned integral
3005 // types. -- end note ]
3006 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3007
3008 // Arrays are unique only if their element type is unique.
3009 if (Ty->isArrayType())
3011 CheckIfTriviallyCopyable);
3012
3013 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3014 "hasUniqueObjectRepresentations should not be called with an "
3015 "incomplete type");
3016
3017 // (9.1) - T is trivially copyable...
3018 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3019 return false;
3020
3021 // All integrals and enums are unique.
3022 if (Ty->isIntegralOrEnumerationType()) {
3023 // Address discriminated integer types are not unique.
3025 return false;
3026 // Except _BitInt types that have padding bits.
3027 if (const auto *BIT = Ty->getAs<BitIntType>())
3028 return getTypeSize(BIT) == BIT->getNumBits();
3029
3030 return true;
3031 }
3032
3033 // All other pointers are unique.
3034 if (Ty->isPointerType())
3036
3037 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3038 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3039
3040 if (const auto *Record = Ty->getAsRecordDecl()) {
3041 if (Record->isInvalidDecl())
3042 return false;
3043
3044 if (Record->isUnion())
3046 CheckIfTriviallyCopyable);
3047
3048 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3049 *this, Record, CheckIfTriviallyCopyable);
3050
3051 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3052 }
3053
3054 // FIXME: More cases to handle here (list by rsmith):
3055 // vectors (careful about, eg, vector of 3 foo)
3056 // _Complex int and friends
3057 // _Atomic T
3058 // Obj-C block pointers
3059 // Obj-C object pointers
3060 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3061 // clk_event_t, queue_t, reserve_id_t)
3062 // There're also Obj-C class types and the Obj-C selector type, but I think it
3063 // makes sense for those to return false here.
3064
3065 return false;
3066}
3067
3069 unsigned count = 0;
3070 // Count ivars declared in class extension.
3071 for (const auto *Ext : OI->known_extensions())
3072 count += Ext->ivar_size();
3073
3074 // Count ivar defined in this class's implementation. This
3075 // includes synthesized ivars.
3076 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3077 count += ImplDecl->ivar_size();
3078
3079 return count;
3080}
3081
3083 if (!E)
3084 return false;
3085
3086 // nullptr_t is always treated as null.
3087 if (E->getType()->isNullPtrType()) return true;
3088
3089 if (E->getType()->isAnyPointerType() &&
3092 return true;
3093
3094 // Unfortunately, __null has type 'int'.
3095 if (isa<GNUNullExpr>(E)) return true;
3096
3097 return false;
3098}
3099
3100/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3101/// exists.
3103 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3104 I = ObjCImpls.find(D);
3105 if (I != ObjCImpls.end())
3106 return cast<ObjCImplementationDecl>(I->second);
3107 return nullptr;
3108}
3109
3110/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3111/// exists.
3113 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3114 I = ObjCImpls.find(D);
3115 if (I != ObjCImpls.end())
3116 return cast<ObjCCategoryImplDecl>(I->second);
3117 return nullptr;
3118}
3119
3120/// Set the implementation of ObjCInterfaceDecl.
3122 ObjCImplementationDecl *ImplD) {
3123 assert(IFaceD && ImplD && "Passed null params");
3124 ObjCImpls[IFaceD] = ImplD;
3125}
3126
3127/// Set the implementation of ObjCCategoryDecl.
3129 ObjCCategoryImplDecl *ImplD) {
3130 assert(CatD && ImplD && "Passed null params");
3131 ObjCImpls[CatD] = ImplD;
3132}
3133
3134const ObjCMethodDecl *
3136 return ObjCMethodRedecls.lookup(MD);
3137}
3138
3140 const ObjCMethodDecl *Redecl) {
3141 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3142 ObjCMethodRedecls[MD] = Redecl;
3143}
3144
3146 const NamedDecl *ND) const {
3147 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3148 return ID;
3149 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3150 return CD->getClassInterface();
3151 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3152 return IMD->getClassInterface();
3153
3154 return nullptr;
3155}
3156
3157/// Get the copy initialization expression of VarDecl, or nullptr if
3158/// none exists.
3160 assert(VD && "Passed null params");
3161 assert(VD->hasAttr<BlocksAttr>() &&
3162 "getBlockVarCopyInits - not __block var");
3163 auto I = BlockVarCopyInits.find(VD);
3164 if (I != BlockVarCopyInits.end())
3165 return I->second;
3166 return {nullptr, false};
3167}
3168
3169/// Set the copy initialization expression of a block var decl.
3171 bool CanThrow) {
3172 assert(VD && CopyExpr && "Passed null params");
3173 assert(VD->hasAttr<BlocksAttr>() &&
3174 "setBlockVarCopyInits - not __block var");
3175 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3176}
3177
3179 unsigned DataSize) const {
3180 if (!DataSize)
3182 else
3183 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3184 "incorrect data size provided to CreateTypeSourceInfo!");
3185
3186 auto *TInfo =
3187 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3188 new (TInfo) TypeSourceInfo(T, DataSize);
3189 return TInfo;
3190}
3191
3193 SourceLocation L) const {
3195 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3196 return DI;
3197}
3198
3199const ASTRecordLayout &
3201 return getObjCLayout(D);
3202}
3203
3206 bool &AnyNonCanonArgs) {
3207 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3208 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3209 return CanonArgs;
3210}
3211
3214 bool AnyNonCanonArgs = false;
3215 for (auto &Arg : Args) {
3216 TemplateArgument OrigArg = Arg;
3218 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3219 }
3220 return AnyNonCanonArgs;
3221}
3222
3223//===----------------------------------------------------------------------===//
3224// Type creation/memoization methods
3225//===----------------------------------------------------------------------===//
3226
3228ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3229 unsigned fastQuals = quals.getFastQualifiers();
3230 quals.removeFastQualifiers();
3231
3232 // Check if we've already instantiated this type.
3233 llvm::FoldingSetNodeID ID;
3234 ExtQuals::Profile(ID, baseType, quals);
3235 void *insertPos = nullptr;
3236 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3237 assert(eq->getQualifiers() == quals);
3238 return QualType(eq, fastQuals);
3239 }
3240
3241 // If the base type is not canonical, make the appropriate canonical type.
3242 QualType canon;
3243 if (!baseType->isCanonicalUnqualified()) {
3244 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3245 canonSplit.Quals.addConsistentQualifiers(quals);
3246 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3247
3248 // Re-find the insert position.
3249 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3250 }
3251
3252 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3253 ExtQualNodes.InsertNode(eq, insertPos);
3254 return QualType(eq, fastQuals);
3255}
3256
3258 LangAS AddressSpace) const {
3259 QualType CanT = getCanonicalType(T);
3260 if (CanT.getAddressSpace() == AddressSpace)
3261 return T;
3262
3263 // If we are composing extended qualifiers together, merge together
3264 // into one ExtQuals node.
3265 QualifierCollector Quals;
3266 const Type *TypeNode = Quals.strip(T);
3267
3268 // If this type already has an address space specified, it cannot get
3269 // another one.
3270 assert(!Quals.hasAddressSpace() &&
3271 "Type cannot be in multiple addr spaces!");
3272 Quals.addAddressSpace(AddressSpace);
3273
3274 return getExtQualType(TypeNode, Quals);
3275}
3276
3278 // If the type is not qualified with an address space, just return it
3279 // immediately.
3280 if (!T.hasAddressSpace())
3281 return T;
3282
3283 QualifierCollector Quals;
3284 const Type *TypeNode;
3285 // For arrays, strip the qualifier off the element type, then reconstruct the
3286 // array type
3287 if (T.getTypePtr()->isArrayType()) {
3288 T = getUnqualifiedArrayType(T, Quals);
3289 TypeNode = T.getTypePtr();
3290 } else {
3291 // If we are composing extended qualifiers together, merge together
3292 // into one ExtQuals node.
3293 while (T.hasAddressSpace()) {
3294 TypeNode = Quals.strip(T);
3295
3296 // If the type no longer has an address space after stripping qualifiers,
3297 // jump out.
3298 if (!QualType(TypeNode, 0).hasAddressSpace())
3299 break;
3300
3301 // There might be sugar in the way. Strip it and try again.
3302 T = T.getSingleStepDesugaredType(*this);
3303 }
3304 }
3305
3306 Quals.removeAddressSpace();
3307
3308 // Removal of the address space can mean there are no longer any
3309 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3310 // or required.
3311 if (Quals.hasNonFastQualifiers())
3312 return getExtQualType(TypeNode, Quals);
3313 else
3314 return QualType(TypeNode, Quals.getFastQualifiers());
3315}
3316
3317uint16_t
3319 assert(RD->isPolymorphic() &&
3320 "Attempted to get vtable pointer discriminator on a monomorphic type");
3321 std::unique_ptr<MangleContext> MC(createMangleContext());
3322 SmallString<256> Str;
3323 llvm::raw_svector_ostream Out(Str);
3324 MC->mangleCXXVTable(RD, Out);
3325 return llvm::getPointerAuthStableSipHash(Str);
3326}
3327
3328/// Encode a function type for use in the discriminator of a function pointer
3329/// type. We can't use the itanium scheme for this since C has quite permissive
3330/// rules for type compatibility that we need to be compatible with.
3331///
3332/// Formally, this function associates every function pointer type T with an
3333/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3334/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3335/// compatibility requires equivalent treatment under the ABI, so
3336/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3337/// a subset of ~. Crucially, however, it must be a proper subset because
3338/// CCompatible is not an equivalence relation: for example, int[] is compatible
3339/// with both int[1] and int[2], but the latter are not compatible with each
3340/// other. Therefore this encoding function must be careful to only distinguish
3341/// types if there is no third type with which they are both required to be
3342/// compatible.
3344 raw_ostream &OS, QualType QT) {
3345 // FIXME: Consider address space qualifiers.
3346 const Type *T = QT.getCanonicalType().getTypePtr();
3347
3348 // FIXME: Consider using the C++ type mangling when we encounter a construct
3349 // that is incompatible with C.
3350
3351 switch (T->getTypeClass()) {
3352 case Type::Atomic:
3354 Ctx, OS, cast<AtomicType>(T)->getValueType());
3355
3356 case Type::LValueReference:
3357 OS << "R";
3360 return;
3361 case Type::RValueReference:
3362 OS << "O";
3365 return;
3366
3367 case Type::Pointer:
3368 // C11 6.7.6.1p2:
3369 // For two pointer types to be compatible, both shall be identically
3370 // qualified and both shall be pointers to compatible types.
3371 // FIXME: we should also consider pointee types.
3372 OS << "P";
3373 return;
3374
3375 case Type::ObjCObjectPointer:
3376 case Type::BlockPointer:
3377 OS << "P";
3378 return;
3379
3380 case Type::Complex:
3381 OS << "C";
3383 Ctx, OS, cast<ComplexType>(T)->getElementType());
3384
3385 case Type::VariableArray:
3386 case Type::ConstantArray:
3387 case Type::IncompleteArray:
3388 case Type::ArrayParameter:
3389 // C11 6.7.6.2p6:
3390 // For two array types to be compatible, both shall have compatible
3391 // element types, and if both size specifiers are present, and are integer
3392 // constant expressions, then both size specifiers shall have the same
3393 // constant value [...]
3394 //
3395 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3396 // width of the array.
3397 OS << "A";
3399 Ctx, OS, cast<ArrayType>(T)->getElementType());
3400
3401 case Type::ObjCInterface:
3402 case Type::ObjCObject:
3403 OS << "<objc_object>";
3404 return;
3405
3406 case Type::Enum: {
3407 // C11 6.7.2.2p4:
3408 // Each enumerated type shall be compatible with char, a signed integer
3409 // type, or an unsigned integer type.
3410 //
3411 // So we have to treat enum types as integers.
3412 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3414 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3415 }
3416
3417 case Type::FunctionNoProto:
3418 case Type::FunctionProto: {
3419 // C11 6.7.6.3p15:
3420 // For two function types to be compatible, both shall specify compatible
3421 // return types. Moreover, the parameter type lists, if both are present,
3422 // shall agree in the number of parameters and in the use of the ellipsis
3423 // terminator; corresponding parameters shall have compatible types.
3424 //
3425 // That paragraph goes on to describe how unprototyped functions are to be
3426 // handled, which we ignore here. Unprototyped function pointers are hashed
3427 // as though they were prototyped nullary functions since thats probably
3428 // what the user meant. This behavior is non-conforming.
3429 // FIXME: If we add a "custom discriminator" function type attribute we
3430 // should encode functions as their discriminators.
3431 OS << "F";
3432 const auto *FuncType = cast<FunctionType>(T);
3433 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3434 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3435 for (QualType Param : FPT->param_types()) {
3436 Param = Ctx.getSignatureParameterType(Param);
3437 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3438 }
3439 if (FPT->isVariadic())
3440 OS << "z";
3441 }
3442 OS << "E";
3443 return;
3444 }
3445
3446 case Type::MemberPointer: {
3447 OS << "M";
3448 const auto *MPT = T->castAs<MemberPointerType>();
3450 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3451 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3452 return;
3453 }
3454 case Type::ExtVector:
3455 case Type::Vector:
3456 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3457 break;
3458
3459 // Don't bother discriminating based on these types.
3460 case Type::Pipe:
3461 case Type::BitInt:
3462 case Type::ConstantMatrix:
3463 OS << "?";
3464 return;
3465
3466 case Type::Builtin: {
3467 const auto *BTy = T->castAs<BuiltinType>();
3468 switch (BTy->getKind()) {
3469#define SIGNED_TYPE(Id, SingletonId) \
3470 case BuiltinType::Id: \
3471 OS << "i"; \
3472 return;
3473#define UNSIGNED_TYPE(Id, SingletonId) \
3474 case BuiltinType::Id: \
3475 OS << "i"; \
3476 return;
3477#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3478#define BUILTIN_TYPE(Id, SingletonId)
3479#include "clang/AST/BuiltinTypes.def"
3480 llvm_unreachable("placeholder types should not appear here.");
3481
3482 case BuiltinType::Half:
3483 OS << "Dh";
3484 return;
3485 case BuiltinType::Float:
3486 OS << "f";
3487 return;
3488 case BuiltinType::Double:
3489 OS << "d";
3490 return;
3491 case BuiltinType::LongDouble:
3492 OS << "e";
3493 return;
3494 case BuiltinType::Float16:
3495 OS << "DF16_";
3496 return;
3497 case BuiltinType::Float128:
3498 OS << "g";
3499 return;
3500
3501 case BuiltinType::Void:
3502 OS << "v";
3503 return;
3504
3505 case BuiltinType::ObjCId:
3506 case BuiltinType::ObjCClass:
3507 case BuiltinType::ObjCSel:
3508 case BuiltinType::NullPtr:
3509 OS << "P";
3510 return;
3511
3512 // Don't bother discriminating based on OpenCL types.
3513 case BuiltinType::OCLSampler:
3514 case BuiltinType::OCLEvent:
3515 case BuiltinType::OCLClkEvent:
3516 case BuiltinType::OCLQueue:
3517 case BuiltinType::OCLReserveID:
3518 case BuiltinType::BFloat16:
3519 case BuiltinType::VectorQuad:
3520 case BuiltinType::VectorPair:
3521 case BuiltinType::DMR1024:
3522 OS << "?";
3523 return;
3524
3525 // Don't bother discriminating based on these seldom-used types.
3526 case BuiltinType::Ibm128:
3527 return;
3528#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3529 case BuiltinType::Id: \
3530 return;
3531#include "clang/Basic/OpenCLImageTypes.def"
3532#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3533 case BuiltinType::Id: \
3534 return;
3535#include "clang/Basic/OpenCLExtensionTypes.def"
3536#define SVE_TYPE(Name, Id, SingletonId) \
3537 case BuiltinType::Id: \
3538 return;
3539#include "clang/Basic/AArch64ACLETypes.def"
3540#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3541 case BuiltinType::Id: \
3542 return;
3543#include "clang/Basic/HLSLIntangibleTypes.def"
3544 case BuiltinType::Dependent:
3545 llvm_unreachable("should never get here");
3546#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3547#include "clang/Basic/AMDGPUTypes.def"
3548 case BuiltinType::WasmExternRef:
3549#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3550#include "clang/Basic/RISCVVTypes.def"
3551 llvm_unreachable("not yet implemented");
3552 }
3553 llvm_unreachable("should never get here");
3554 }
3555 case Type::Record: {
3556 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3557 const IdentifierInfo *II = RD->getIdentifier();
3558
3559 // In C++, an immediate typedef of an anonymous struct or union
3560 // is considered to name it for ODR purposes, but C's specification
3561 // of type compatibility does not have a similar rule. Using the typedef
3562 // name in function type discriminators anyway, as we do here,
3563 // therefore technically violates the C standard: two function pointer
3564 // types defined in terms of two typedef'd anonymous structs with
3565 // different names are formally still compatible, but we are assigning
3566 // them different discriminators and therefore incompatible ABIs.
3567 //
3568 // This is a relatively minor violation that significantly improves
3569 // discrimination in some cases and has not caused problems in
3570 // practice. Regardless, it is now part of the ABI in places where
3571 // function type discrimination is used, and it can no longer be
3572 // changed except on new platforms.
3573
3574 if (!II)
3575 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3576 II = Typedef->getDeclName().getAsIdentifierInfo();
3577
3578 if (!II) {
3579 OS << "<anonymous_record>";
3580 return;
3581 }
3582 OS << II->getLength() << II->getName();
3583 return;
3584 }
3585 case Type::HLSLAttributedResource:
3586 case Type::HLSLInlineSpirv:
3587 llvm_unreachable("should never get here");
3588 break;
3589 case Type::DeducedTemplateSpecialization:
3590 case Type::Auto:
3591#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3592#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3593#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3594#define ABSTRACT_TYPE(Class, Base)
3595#define TYPE(Class, Base)
3596#include "clang/AST/TypeNodes.inc"
3597 llvm_unreachable("unexpected non-canonical or dependent type!");
3598 return;
3599 }
3600}
3601
3603 assert(!T->isDependentType() &&
3604 "cannot compute type discriminator of a dependent type");
3605
3606 SmallString<256> Str;
3607 llvm::raw_svector_ostream Out(Str);
3608
3609 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3610 T = T->getPointeeType();
3611
3612 if (T->isFunctionType()) {
3614 } else {
3615 T = T.getUnqualifiedType();
3616 // Calls to member function pointers don't need to worry about
3617 // language interop or the laxness of the C type compatibility rules.
3618 // We just mangle the member pointer type directly, which is
3619 // implicitly much stricter about type matching. However, we do
3620 // strip any top-level exception specification before this mangling.
3621 // C++23 requires calls to work when the function type is convertible
3622 // to the pointer type by a function pointer conversion, which can
3623 // change the exception specification. This does not technically
3624 // require the exception specification to not affect representation,
3625 // because the function pointer conversion is still always a direct
3626 // value conversion and therefore an opportunity to resign the
3627 // pointer. (This is in contrast to e.g. qualification conversions,
3628 // which can be applied in nested pointer positions, effectively
3629 // requiring qualified and unqualified representations to match.)
3630 // However, it is pragmatic to ignore exception specifications
3631 // because it allows a certain amount of `noexcept` mismatching
3632 // to not become a visible ODR problem. This also leaves some
3633 // room for the committee to add laxness to function pointer
3634 // conversions in future standards.
3635 if (auto *MPT = T->getAs<MemberPointerType>())
3636 if (MPT->isMemberFunctionPointer()) {
3637 QualType PointeeType = MPT->getPointeeType();
3638 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3639 EST_None) {
3641 T = getMemberPointerType(FT, MPT->getQualifier(),
3642 MPT->getMostRecentCXXRecordDecl());
3643 }
3644 }
3645 std::unique_ptr<MangleContext> MC(createMangleContext());
3646 MC->mangleCanonicalTypeName(T, Out);
3647 }
3648
3649 return llvm::getPointerAuthStableSipHash(Str);
3650}
3651
3653 Qualifiers::GC GCAttr) const {
3654 QualType CanT = getCanonicalType(T);
3655 if (CanT.getObjCGCAttr() == GCAttr)
3656 return T;
3657
3658 if (const auto *ptr = T->getAs<PointerType>()) {
3659 QualType Pointee = ptr->getPointeeType();
3660 if (Pointee->isAnyPointerType()) {
3661 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3662 return getPointerType(ResultType);
3663 }
3664 }
3665
3666 // If we are composing extended qualifiers together, merge together
3667 // into one ExtQuals node.
3668 QualifierCollector Quals;
3669 const Type *TypeNode = Quals.strip(T);
3670
3671 // If this type already has an ObjCGC specified, it cannot get
3672 // another one.
3673 assert(!Quals.hasObjCGCAttr() &&
3674 "Type cannot have multiple ObjCGCs!");
3675 Quals.addObjCGCAttr(GCAttr);
3676
3677 return getExtQualType(TypeNode, Quals);
3678}
3679
3681 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3682 QualType Pointee = Ptr->getPointeeType();
3683 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3684 return getPointerType(removeAddrSpaceQualType(Pointee));
3685 }
3686 }
3687 return T;
3688}
3689
3691 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3692 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3693 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3694
3695 llvm::FoldingSetNodeID ID;
3696 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3697
3698 void *InsertPos = nullptr;
3699 CountAttributedType *CATy =
3700 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3701 if (CATy)
3702 return QualType(CATy, 0);
3703
3704 QualType CanonTy = getCanonicalType(WrappedTy);
3705 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3706 DependentDecls.size());
3708 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3709 OrNull, DependentDecls);
3710 Types.push_back(CATy);
3711 CountAttributedTypes.InsertNode(CATy, InsertPos);
3712
3713 return QualType(CATy, 0);
3714}
3715
3718 llvm::function_ref<QualType(QualType)> Adjust) const {
3719 switch (Orig->getTypeClass()) {
3720 case Type::Attributed: {
3721 const auto *AT = cast<AttributedType>(Orig);
3722 return getAttributedType(AT->getAttrKind(),
3723 adjustType(AT->getModifiedType(), Adjust),
3724 adjustType(AT->getEquivalentType(), Adjust),
3725 AT->getAttr());
3726 }
3727
3728 case Type::BTFTagAttributed: {
3729 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3730 return getBTFTagAttributedType(BTFT->getAttr(),
3731 adjustType(BTFT->getWrappedType(), Adjust));
3732 }
3733
3734 case Type::Paren:
3735 return getParenType(
3736 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3737
3738 case Type::Adjusted: {
3739 const auto *AT = cast<AdjustedType>(Orig);
3740 return getAdjustedType(AT->getOriginalType(),
3741 adjustType(AT->getAdjustedType(), Adjust));
3742 }
3743
3744 case Type::MacroQualified: {
3745 const auto *MQT = cast<MacroQualifiedType>(Orig);
3746 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3747 MQT->getMacroIdentifier());
3748 }
3749
3750 default:
3751 return Adjust(Orig);
3752 }
3753}
3754
3756 FunctionType::ExtInfo Info) {
3757 if (T->getExtInfo() == Info)
3758 return T;
3759
3761 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3762 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3763 } else {
3764 const auto *FPT = cast<FunctionProtoType>(T);
3765 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3766 EPI.ExtInfo = Info;
3767 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3768 }
3769
3770 return cast<FunctionType>(Result.getTypePtr());
3771}
3772
3774 QualType ResultType) {
3775 return adjustType(FunctionType, [&](QualType Orig) {
3776 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3777 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3778
3779 const auto *FPT = Orig->castAs<FunctionProtoType>();
3780 return getFunctionType(ResultType, FPT->getParamTypes(),
3781 FPT->getExtProtoInfo());
3782 });
3783}
3784
3786 QualType ResultType) {
3787 FD = FD->getMostRecentDecl();
3788 while (true) {
3789 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3790 if (FunctionDecl *Next = FD->getPreviousDecl())
3791 FD = Next;
3792 else
3793 break;
3794 }
3796 L->DeducedReturnType(FD, ResultType);
3797}
3798
3799/// Get a function type and produce the equivalent function type with the
3800/// specified exception specification. Type sugar that can be present on a
3801/// declaration of a function with an exception specification is permitted
3802/// and preserved. Other type sugar (for instance, typedefs) is not.
3804 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3805 return adjustType(Orig, [&](QualType Ty) {
3806 const auto *Proto = Ty->castAs<FunctionProtoType>();
3807 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3808 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3809 });
3810}
3811
3819
3821 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3822 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3823 SmallVector<QualType, 16> Args(Proto->param_types().size());
3824 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3825 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3826 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3827 }
3828
3829 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3830 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3831 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3832 }
3833
3834 return T;
3835}
3836
3842
3844 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3845 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3846 EPI.ExtParameterInfos = nullptr;
3847 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3848 }
3849 return T;
3850}
3851
3857
3860 bool AsWritten) {
3861 // Update the type.
3862 QualType Updated =
3864 FD->setType(Updated);
3865
3866 if (!AsWritten)
3867 return;
3868
3869 // Update the type in the type source information too.
3870 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3871 // If the type and the type-as-written differ, we may need to update
3872 // the type-as-written too.
3873 if (TSInfo->getType() != FD->getType())
3874 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3875
3876 // FIXME: When we get proper type location information for exceptions,
3877 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3878 // up the TypeSourceInfo;
3879 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3880 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3881 "TypeLoc size mismatch from updating exception specification");
3882 TSInfo->overrideType(Updated);
3883 }
3884}
3885
3886/// getComplexType - Return the uniqued reference to the type for a complex
3887/// number with the specified element type.
3889 // Unique pointers, to guarantee there is only one pointer of a particular
3890 // structure.
3891 llvm::FoldingSetNodeID ID;
3893
3894 void *InsertPos = nullptr;
3895 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3896 return QualType(CT, 0);
3897
3898 // If the pointee type isn't canonical, this won't be a canonical type either,
3899 // so fill in the canonical type field.
3900 QualType Canonical;
3901 if (!T.isCanonical()) {
3902 Canonical = getComplexType(getCanonicalType(T));
3903
3904 // Get the new insert position for the node we care about.
3905 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3906 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3907 }
3908 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3909 Types.push_back(New);
3910 ComplexTypes.InsertNode(New, InsertPos);
3911 return QualType(New, 0);
3912}
3913
3914/// getPointerType - Return the uniqued reference to the type for a pointer to
3915/// the specified type.
3917 // Unique pointers, to guarantee there is only one pointer of a particular
3918 // structure.
3919 llvm::FoldingSetNodeID ID;
3921
3922 void *InsertPos = nullptr;
3923 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3924 return QualType(PT, 0);
3925
3926 // If the pointee type isn't canonical, this won't be a canonical type either,
3927 // so fill in the canonical type field.
3928 QualType Canonical;
3929 if (!T.isCanonical()) {
3930 Canonical = getPointerType(getCanonicalType(T));
3931
3932 // Get the new insert position for the node we care about.
3933 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3935 }
3936 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3937 Types.push_back(New);
3938 PointerTypes.InsertNode(New, InsertPos);
3939 return QualType(New, 0);
3940}
3941
3943 llvm::FoldingSetNodeID ID;
3944 AdjustedType::Profile(ID, Orig, New);
3945 void *InsertPos = nullptr;
3946 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3947 if (AT)
3948 return QualType(AT, 0);
3949
3950 QualType Canonical = getCanonicalType(New);
3951
3952 // Get the new insert position for the node we care about.
3953 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3954 assert(!AT && "Shouldn't be in the map!");
3955
3956 AT = new (*this, alignof(AdjustedType))
3957 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3958 Types.push_back(AT);
3959 AdjustedTypes.InsertNode(AT, InsertPos);
3960 return QualType(AT, 0);
3961}
3962
3964 llvm::FoldingSetNodeID ID;
3965 AdjustedType::Profile(ID, Orig, Decayed);
3966 void *InsertPos = nullptr;
3967 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3968 if (AT)
3969 return QualType(AT, 0);
3970
3971 QualType Canonical = getCanonicalType(Decayed);
3972
3973 // Get the new insert position for the node we care about.
3974 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3975 assert(!AT && "Shouldn't be in the map!");
3976
3977 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3978 Types.push_back(AT);
3979 AdjustedTypes.InsertNode(AT, InsertPos);
3980 return QualType(AT, 0);
3981}
3982
3984 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3985
3986 QualType Decayed;
3987
3988 // C99 6.7.5.3p7:
3989 // A declaration of a parameter as "array of type" shall be
3990 // adjusted to "qualified pointer to type", where the type
3991 // qualifiers (if any) are those specified within the [ and ] of
3992 // the array type derivation.
3993 if (T->isArrayType())
3994 Decayed = getArrayDecayedType(T);
3995
3996 // C99 6.7.5.3p8:
3997 // A declaration of a parameter as "function returning type"
3998 // shall be adjusted to "pointer to function returning type", as
3999 // in 6.3.2.1.
4000 if (T->isFunctionType())
4001 Decayed = getPointerType(T);
4002
4003 return getDecayedType(T, Decayed);
4004}
4005
4007 if (Ty->isArrayParameterType())
4008 return Ty;
4009 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4010 QualType DTy = Ty.getDesugaredType(*this);
4011 const auto *ATy = cast<ConstantArrayType>(DTy);
4012 llvm::FoldingSetNodeID ID;
4013 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4014 ATy->getSizeExpr(), ATy->getSizeModifier(),
4015 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4016 void *InsertPos = nullptr;
4017 ArrayParameterType *AT =
4018 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4019 if (AT)
4020 return QualType(AT, 0);
4021
4022 QualType Canonical;
4023 if (!DTy.isCanonical()) {
4024 Canonical = getArrayParameterType(getCanonicalType(Ty));
4025
4026 // Get the new insert position for the node we care about.
4027 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4028 assert(!AT && "Shouldn't be in the map!");
4029 }
4030
4031 AT = new (*this, alignof(ArrayParameterType))
4032 ArrayParameterType(ATy, Canonical);
4033 Types.push_back(AT);
4034 ArrayParameterTypes.InsertNode(AT, InsertPos);
4035 return QualType(AT, 0);
4036}
4037
4038/// getBlockPointerType - Return the uniqued reference to the type for
4039/// a pointer to the specified block.
4041 assert(T->isFunctionType() && "block of function types only");
4042 // Unique pointers, to guarantee there is only one block of a particular
4043 // structure.
4044 llvm::FoldingSetNodeID ID;
4046
4047 void *InsertPos = nullptr;
4048 if (BlockPointerType *PT =
4049 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4050 return QualType(PT, 0);
4051
4052 // If the block pointee type isn't canonical, this won't be a canonical
4053 // type either so fill in the canonical type field.
4054 QualType Canonical;
4055 if (!T.isCanonical()) {
4057
4058 // Get the new insert position for the node we care about.
4059 BlockPointerType *NewIP =
4060 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4061 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4062 }
4063 auto *New =
4064 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4065 Types.push_back(New);
4066 BlockPointerTypes.InsertNode(New, InsertPos);
4067 return QualType(New, 0);
4068}
4069
4070/// getLValueReferenceType - Return the uniqued reference to the type for an
4071/// lvalue reference to the specified type.
4073ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4074 assert((!T->isPlaceholderType() ||
4075 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4076 "Unresolved placeholder type");
4077
4078 // Unique pointers, to guarantee there is only one pointer of a particular
4079 // structure.
4080 llvm::FoldingSetNodeID ID;
4081 ReferenceType::Profile(ID, T, SpelledAsLValue);
4082
4083 void *InsertPos = nullptr;
4084 if (LValueReferenceType *RT =
4085 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4086 return QualType(RT, 0);
4087
4088 const auto *InnerRef = T->getAs<ReferenceType>();
4089
4090 // If the referencee type isn't canonical, this won't be a canonical type
4091 // either, so fill in the canonical type field.
4092 QualType Canonical;
4093 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4094 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4095 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4096
4097 // Get the new insert position for the node we care about.
4098 LValueReferenceType *NewIP =
4099 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4100 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4101 }
4102
4103 auto *New = new (*this, alignof(LValueReferenceType))
4104 LValueReferenceType(T, Canonical, SpelledAsLValue);
4105 Types.push_back(New);
4106 LValueReferenceTypes.InsertNode(New, InsertPos);
4107
4108 return QualType(New, 0);
4109}
4110
4111/// getRValueReferenceType - Return the uniqued reference to the type for an
4112/// rvalue reference to the specified type.
4114 assert((!T->isPlaceholderType() ||
4115 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4116 "Unresolved placeholder type");
4117
4118 // Unique pointers, to guarantee there is only one pointer of a particular
4119 // structure.
4120 llvm::FoldingSetNodeID ID;
4121 ReferenceType::Profile(ID, T, false);
4122
4123 void *InsertPos = nullptr;
4124 if (RValueReferenceType *RT =
4125 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4126 return QualType(RT, 0);
4127
4128 const auto *InnerRef = T->getAs<ReferenceType>();
4129
4130 // If the referencee type isn't canonical, this won't be a canonical type
4131 // either, so fill in the canonical type field.
4132 QualType Canonical;
4133 if (InnerRef || !T.isCanonical()) {
4134 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4135 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4136
4137 // Get the new insert position for the node we care about.
4138 RValueReferenceType *NewIP =
4139 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4140 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4141 }
4142
4143 auto *New = new (*this, alignof(RValueReferenceType))
4144 RValueReferenceType(T, Canonical);
4145 Types.push_back(New);
4146 RValueReferenceTypes.InsertNode(New, InsertPos);
4147 return QualType(New, 0);
4148}
4149
4151 NestedNameSpecifier Qualifier,
4152 const CXXRecordDecl *Cls) const {
4153 if (!Qualifier) {
4154 assert(Cls && "At least one of Qualifier or Cls must be provided");
4155 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4156 } else if (!Cls) {
4157 Cls = Qualifier.getAsRecordDecl();
4158 }
4159 // Unique pointers, to guarantee there is only one pointer of a particular
4160 // structure.
4161 llvm::FoldingSetNodeID ID;
4162 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4163
4164 void *InsertPos = nullptr;
4165 if (MemberPointerType *PT =
4166 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4167 return QualType(PT, 0);
4168
4169 NestedNameSpecifier CanonicalQualifier = [&] {
4170 if (!Cls)
4171 return Qualifier.getCanonical();
4172 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4173 assert(R.isCanonical());
4174 return R;
4175 }();
4176 // If the pointee or class type isn't canonical, this won't be a canonical
4177 // type either, so fill in the canonical type field.
4178 QualType Canonical;
4179 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4180 Canonical =
4181 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4182 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4183 // Get the new insert position for the node we care about.
4184 [[maybe_unused]] MemberPointerType *NewIP =
4185 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4186 assert(!NewIP && "Shouldn't be in the map!");
4187 }
4188 auto *New = new (*this, alignof(MemberPointerType))
4189 MemberPointerType(T, Qualifier, Canonical);
4190 Types.push_back(New);
4191 MemberPointerTypes.InsertNode(New, InsertPos);
4192 return QualType(New, 0);
4193}
4194
4195/// getConstantArrayType - Return the unique reference to the type for an
4196/// array of the specified element type.
4198 const llvm::APInt &ArySizeIn,
4199 const Expr *SizeExpr,
4201 unsigned IndexTypeQuals) const {
4202 assert((EltTy->isDependentType() ||
4203 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4204 "Constant array of VLAs is illegal!");
4205
4206 // We only need the size as part of the type if it's instantiation-dependent.
4207 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4208 SizeExpr = nullptr;
4209
4210 // Convert the array size into a canonical width matching the pointer size for
4211 // the target.
4212 llvm::APInt ArySize(ArySizeIn);
4213 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4214
4215 llvm::FoldingSetNodeID ID;
4216 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4217 ASM, IndexTypeQuals);
4218
4219 void *InsertPos = nullptr;
4220 if (ConstantArrayType *ATP =
4221 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4222 return QualType(ATP, 0);
4223
4224 // If the element type isn't canonical or has qualifiers, or the array bound
4225 // is instantiation-dependent, this won't be a canonical type either, so fill
4226 // in the canonical type field.
4227 QualType Canon;
4228 // FIXME: Check below should look for qualifiers behind sugar.
4229 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4230 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4231 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4232 ASM, IndexTypeQuals);
4233 Canon = getQualifiedType(Canon, canonSplit.Quals);
4234
4235 // Get the new insert position for the node we care about.
4236 ConstantArrayType *NewIP =
4237 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4238 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4239 }
4240
4241 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4242 ASM, IndexTypeQuals);
4243 ConstantArrayTypes.InsertNode(New, InsertPos);
4244 Types.push_back(New);
4245 return QualType(New, 0);
4246}
4247
4248/// getVariableArrayDecayedType - Turns the given type, which may be
4249/// variably-modified, into the corresponding type with all the known
4250/// sizes replaced with [*].
4252 // Vastly most common case.
4253 if (!type->isVariablyModifiedType()) return type;
4254
4255 QualType result;
4256
4257 SplitQualType split = type.getSplitDesugaredType();
4258 const Type *ty = split.Ty;
4259 switch (ty->getTypeClass()) {
4260#define TYPE(Class, Base)
4261#define ABSTRACT_TYPE(Class, Base)
4262#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4263#include "clang/AST/TypeNodes.inc"
4264 llvm_unreachable("didn't desugar past all non-canonical types?");
4265
4266 // These types should never be variably-modified.
4267 case Type::Builtin:
4268 case Type::Complex:
4269 case Type::Vector:
4270 case Type::DependentVector:
4271 case Type::ExtVector:
4272 case Type::DependentSizedExtVector:
4273 case Type::ConstantMatrix:
4274 case Type::DependentSizedMatrix:
4275 case Type::DependentAddressSpace:
4276 case Type::ObjCObject:
4277 case Type::ObjCInterface:
4278 case Type::ObjCObjectPointer:
4279 case Type::Record:
4280 case Type::Enum:
4281 case Type::UnresolvedUsing:
4282 case Type::TypeOfExpr:
4283 case Type::TypeOf:
4284 case Type::Decltype:
4285 case Type::UnaryTransform:
4286 case Type::DependentName:
4287 case Type::InjectedClassName:
4288 case Type::TemplateSpecialization:
4289 case Type::DependentTemplateSpecialization:
4290 case Type::TemplateTypeParm:
4291 case Type::SubstTemplateTypeParmPack:
4292 case Type::SubstBuiltinTemplatePack:
4293 case Type::Auto:
4294 case Type::DeducedTemplateSpecialization:
4295 case Type::PackExpansion:
4296 case Type::PackIndexing:
4297 case Type::BitInt:
4298 case Type::DependentBitInt:
4299 case Type::ArrayParameter:
4300 case Type::HLSLAttributedResource:
4301 case Type::HLSLInlineSpirv:
4302 llvm_unreachable("type should never be variably-modified");
4303
4304 // These types can be variably-modified but should never need to
4305 // further decay.
4306 case Type::FunctionNoProto:
4307 case Type::FunctionProto:
4308 case Type::BlockPointer:
4309 case Type::MemberPointer:
4310 case Type::Pipe:
4311 return type;
4312
4313 // These types can be variably-modified. All these modifications
4314 // preserve structure except as noted by comments.
4315 // TODO: if we ever care about optimizing VLAs, there are no-op
4316 // optimizations available here.
4317 case Type::Pointer:
4320 break;
4321
4322 case Type::LValueReference: {
4323 const auto *lv = cast<LValueReferenceType>(ty);
4324 result = getLValueReferenceType(
4325 getVariableArrayDecayedType(lv->getPointeeType()),
4326 lv->isSpelledAsLValue());
4327 break;
4328 }
4329
4330 case Type::RValueReference: {
4331 const auto *lv = cast<RValueReferenceType>(ty);
4332 result = getRValueReferenceType(
4333 getVariableArrayDecayedType(lv->getPointeeType()));
4334 break;
4335 }
4336
4337 case Type::Atomic: {
4338 const auto *at = cast<AtomicType>(ty);
4339 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4340 break;
4341 }
4342
4343 case Type::ConstantArray: {
4344 const auto *cat = cast<ConstantArrayType>(ty);
4345 result = getConstantArrayType(
4346 getVariableArrayDecayedType(cat->getElementType()),
4347 cat->getSize(),
4348 cat->getSizeExpr(),
4349 cat->getSizeModifier(),
4350 cat->getIndexTypeCVRQualifiers());
4351 break;
4352 }
4353
4354 case Type::DependentSizedArray: {
4355 const auto *dat = cast<DependentSizedArrayType>(ty);
4357 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4358 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4359 break;
4360 }
4361
4362 // Turn incomplete types into [*] types.
4363 case Type::IncompleteArray: {
4364 const auto *iat = cast<IncompleteArrayType>(ty);
4365 result =
4367 /*size*/ nullptr, ArraySizeModifier::Normal,
4368 iat->getIndexTypeCVRQualifiers());
4369 break;
4370 }
4371
4372 // Turn VLA types into [*] types.
4373 case Type::VariableArray: {
4374 const auto *vat = cast<VariableArrayType>(ty);
4375 result =
4377 /*size*/ nullptr, ArraySizeModifier::Star,
4378 vat->getIndexTypeCVRQualifiers());
4379 break;
4380 }
4381 }
4382
4383 // Apply the top-level qualifiers from the original.
4384 return getQualifiedType(result, split.Quals);
4385}
4386
4387/// getVariableArrayType - Returns a non-unique reference to the type for a
4388/// variable array of the specified element type.
4391 unsigned IndexTypeQuals) const {
4392 // Since we don't unique expressions, it isn't possible to unique VLA's
4393 // that have an expression provided for their size.
4394 QualType Canon;
4395
4396 // Be sure to pull qualifiers off the element type.
4397 // FIXME: Check below should look for qualifiers behind sugar.
4398 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4399 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4400 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4401 IndexTypeQuals);
4402 Canon = getQualifiedType(Canon, canonSplit.Quals);
4403 }
4404
4405 auto *New = new (*this, alignof(VariableArrayType))
4406 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4407
4408 VariableArrayTypes.push_back(New);
4409 Types.push_back(New);
4410 return QualType(New, 0);
4411}
4412
4413/// getDependentSizedArrayType - Returns a non-unique reference to
4414/// the type for a dependently-sized array of the specified element
4415/// type.
4419 unsigned elementTypeQuals) const {
4420 assert((!numElements || numElements->isTypeDependent() ||
4421 numElements->isValueDependent()) &&
4422 "Size must be type- or value-dependent!");
4423
4424 SplitQualType canonElementType = getCanonicalType(elementType).split();
4425
4426 void *insertPos = nullptr;
4427 llvm::FoldingSetNodeID ID;
4429 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4430 ASM, elementTypeQuals, numElements);
4431
4432 // Look for an existing type with these properties.
4433 DependentSizedArrayType *canonTy =
4434 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4435
4436 // Dependently-sized array types that do not have a specified number
4437 // of elements will have their sizes deduced from a dependent
4438 // initializer.
4439 if (!numElements) {
4440 if (canonTy)
4441 return QualType(canonTy, 0);
4442
4443 auto *newType = new (*this, alignof(DependentSizedArrayType))
4444 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4445 elementTypeQuals);
4446 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4447 Types.push_back(newType);
4448 return QualType(newType, 0);
4449 }
4450
4451 // If we don't have one, build one.
4452 if (!canonTy) {
4453 canonTy = new (*this, alignof(DependentSizedArrayType))
4454 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4455 numElements, ASM, elementTypeQuals);
4456 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4457 Types.push_back(canonTy);
4458 }
4459
4460 // Apply qualifiers from the element type to the array.
4461 QualType canon = getQualifiedType(QualType(canonTy,0),
4462 canonElementType.Quals);
4463
4464 // If we didn't need extra canonicalization for the element type or the size
4465 // expression, then just use that as our result.
4466 if (QualType(canonElementType.Ty, 0) == elementType &&
4467 canonTy->getSizeExpr() == numElements)
4468 return canon;
4469
4470 // Otherwise, we need to build a type which follows the spelling
4471 // of the element type.
4472 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4473 DependentSizedArrayType(elementType, canon, numElements, ASM,
4474 elementTypeQuals);
4475 Types.push_back(sugaredType);
4476 return QualType(sugaredType, 0);
4477}
4478
4481 unsigned elementTypeQuals) const {
4482 llvm::FoldingSetNodeID ID;
4483 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4484
4485 void *insertPos = nullptr;
4486 if (IncompleteArrayType *iat =
4487 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4488 return QualType(iat, 0);
4489
4490 // If the element type isn't canonical, this won't be a canonical type
4491 // either, so fill in the canonical type field. We also have to pull
4492 // qualifiers off the element type.
4493 QualType canon;
4494
4495 // FIXME: Check below should look for qualifiers behind sugar.
4496 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4497 SplitQualType canonSplit = getCanonicalType(elementType).split();
4498 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4499 ASM, elementTypeQuals);
4500 canon = getQualifiedType(canon, canonSplit.Quals);
4501
4502 // Get the new insert position for the node we care about.
4503 IncompleteArrayType *existing =
4504 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4505 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4506 }
4507
4508 auto *newType = new (*this, alignof(IncompleteArrayType))
4509 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4510
4511 IncompleteArrayTypes.InsertNode(newType, insertPos);
4512 Types.push_back(newType);
4513 return QualType(newType, 0);
4514}
4515
4518#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4519 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4520 NUMVECTORS};
4521
4522#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4523 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4524
4525 switch (Ty->getKind()) {
4526 default:
4527 llvm_unreachable("Unsupported builtin vector type");
4528
4529#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4530 ElBits, NF, IsSigned) \
4531 case BuiltinType::Id: \
4532 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4533 llvm::ElementCount::getScalable(NumEls), NF};
4534#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4535 ElBits, NF) \
4536 case BuiltinType::Id: \
4537 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4538 llvm::ElementCount::getScalable(NumEls), NF};
4539#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4540 ElBits, NF) \
4541 case BuiltinType::Id: \
4542 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4543#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4544 ElBits, NF) \
4545 case BuiltinType::Id: \
4546 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4547#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4548 case BuiltinType::Id: \
4549 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4550#include "clang/Basic/AArch64ACLETypes.def"
4551
4552#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4553 IsSigned) \
4554 case BuiltinType::Id: \
4555 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4556 llvm::ElementCount::getScalable(NumEls), NF};
4557#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4558 case BuiltinType::Id: \
4559 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4560 llvm::ElementCount::getScalable(NumEls), NF};
4561#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4562 case BuiltinType::Id: \
4563 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4564#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4565 case BuiltinType::Id: \
4566 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4567#include "clang/Basic/RISCVVTypes.def"
4568 }
4569}
4570
4571/// getExternrefType - Return a WebAssembly externref type, which represents an
4572/// opaque reference to a host value.
4574 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4575#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4576 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4577 return SingletonId;
4578#include "clang/Basic/WebAssemblyReferenceTypes.def"
4579 }
4580 llvm_unreachable(
4581 "shouldn't try to generate type externref outside WebAssembly target");
4582}
4583
4584/// getScalableVectorType - Return the unique reference to a scalable vector
4585/// type of the specified element type and size. VectorType must be a built-in
4586/// type.
4588 unsigned NumFields) const {
4589 if (Target->hasAArch64ACLETypes()) {
4590 uint64_t EltTySize = getTypeSize(EltTy);
4591
4592#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4593 ElBits, NF, IsSigned) \
4594 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4595 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4596 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4597 return SingletonId; \
4598 }
4599#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4600 ElBits, NF) \
4601 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4602 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4603 return SingletonId; \
4604 }
4605#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4606 ElBits, NF) \
4607 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4608 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4609 return SingletonId; \
4610 }
4611#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4612 ElBits, NF) \
4613 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4614 NumElts == (NumEls * NF) && NumFields == 1) { \
4615 return SingletonId; \
4616 }
4617#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4618 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4619 return SingletonId;
4620#include "clang/Basic/AArch64ACLETypes.def"
4621 } else if (Target->hasRISCVVTypes()) {
4622 uint64_t EltTySize = getTypeSize(EltTy);
4623#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4624 IsFP, IsBF) \
4625 if (!EltTy->isBooleanType() && \
4626 ((EltTy->hasIntegerRepresentation() && \
4627 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4628 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4629 IsFP && !IsBF) || \
4630 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4631 IsBF && !IsFP)) && \
4632 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4633 return SingletonId;
4634#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4635 if (EltTy->isBooleanType() && NumElts == NumEls) \
4636 return SingletonId;
4637#include "clang/Basic/RISCVVTypes.def"
4638 }
4639 return QualType();
4640}
4641
4642/// getVectorType - Return the unique reference to a vector type of
4643/// the specified element type and size. VectorType must be a built-in type.
4645 VectorKind VecKind) const {
4646 assert(vecType->isBuiltinType() ||
4647 (vecType->isBitIntType() &&
4648 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4649 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4650
4651 // Check if we've already instantiated a vector of this type.
4652 llvm::FoldingSetNodeID ID;
4653 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4654
4655 void *InsertPos = nullptr;
4656 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4657 return QualType(VTP, 0);
4658
4659 // If the element type isn't canonical, this won't be a canonical type either,
4660 // so fill in the canonical type field.
4661 QualType Canonical;
4662 if (!vecType.isCanonical()) {
4663 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4664
4665 // Get the new insert position for the node we care about.
4666 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4667 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4668 }
4669 auto *New = new (*this, alignof(VectorType))
4670 VectorType(vecType, NumElts, Canonical, VecKind);
4671 VectorTypes.InsertNode(New, InsertPos);
4672 Types.push_back(New);
4673 return QualType(New, 0);
4674}
4675
4677 SourceLocation AttrLoc,
4678 VectorKind VecKind) const {
4679 llvm::FoldingSetNodeID ID;
4680 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4681 VecKind);
4682 void *InsertPos = nullptr;
4683 DependentVectorType *Canon =
4684 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4686
4687 if (Canon) {
4688 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4689 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4690 } else {
4691 QualType CanonVecTy = getCanonicalType(VecType);
4692 if (CanonVecTy == VecType) {
4693 New = new (*this, alignof(DependentVectorType))
4694 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4695
4696 DependentVectorType *CanonCheck =
4697 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4698 assert(!CanonCheck &&
4699 "Dependent-sized vector_size canonical type broken");
4700 (void)CanonCheck;
4701 DependentVectorTypes.InsertNode(New, InsertPos);
4702 } else {
4703 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4704 SourceLocation(), VecKind);
4705 New = new (*this, alignof(DependentVectorType))
4706 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4707 }
4708 }
4709
4710 Types.push_back(New);
4711 return QualType(New, 0);
4712}
4713
4714/// getExtVectorType - Return the unique reference to an extended vector type of
4715/// the specified element type and size. VectorType must be a built-in type.
4717 unsigned NumElts) const {
4718 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4719 (vecType->isBitIntType() &&
4720 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4721 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4722
4723 // Check if we've already instantiated a vector of this type.
4724 llvm::FoldingSetNodeID ID;
4725 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4727 void *InsertPos = nullptr;
4728 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4729 return QualType(VTP, 0);
4730
4731 // If the element type isn't canonical, this won't be a canonical type either,
4732 // so fill in the canonical type field.
4733 QualType Canonical;
4734 if (!vecType.isCanonical()) {
4735 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4736
4737 // Get the new insert position for the node we care about.
4738 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4739 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4740 }
4741 auto *New = new (*this, alignof(ExtVectorType))
4742 ExtVectorType(vecType, NumElts, Canonical);
4743 VectorTypes.InsertNode(New, InsertPos);
4744 Types.push_back(New);
4745 return QualType(New, 0);
4746}
4747
4750 Expr *SizeExpr,
4751 SourceLocation AttrLoc) const {
4752 llvm::FoldingSetNodeID ID;
4754 SizeExpr);
4755
4756 void *InsertPos = nullptr;
4758 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4760 if (Canon) {
4761 // We already have a canonical version of this array type; use it as
4762 // the canonical type for a newly-built type.
4763 New = new (*this, alignof(DependentSizedExtVectorType))
4764 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4765 AttrLoc);
4766 } else {
4767 QualType CanonVecTy = getCanonicalType(vecType);
4768 if (CanonVecTy == vecType) {
4769 New = new (*this, alignof(DependentSizedExtVectorType))
4770 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4771
4772 DependentSizedExtVectorType *CanonCheck
4773 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4774 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4775 (void)CanonCheck;
4776 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4777 } else {
4778 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4779 SourceLocation());
4780 New = new (*this, alignof(DependentSizedExtVectorType))
4781 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4782 }
4783 }
4784
4785 Types.push_back(New);
4786 return QualType(New, 0);
4787}
4788
4790 unsigned NumColumns) const {
4791 llvm::FoldingSetNodeID ID;
4792 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4793 Type::ConstantMatrix);
4794
4795 assert(MatrixType::isValidElementType(ElementTy) &&
4796 "need a valid element type");
4797 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4799 "need valid matrix dimensions");
4800 void *InsertPos = nullptr;
4801 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4802 return QualType(MTP, 0);
4803
4804 QualType Canonical;
4805 if (!ElementTy.isCanonical()) {
4806 Canonical =
4807 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4808
4809 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4810 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4811 (void)NewIP;
4812 }
4813
4814 auto *New = new (*this, alignof(ConstantMatrixType))
4815 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4816 MatrixTypes.InsertNode(New, InsertPos);
4817 Types.push_back(New);
4818 return QualType(New, 0);
4819}
4820
4822 Expr *RowExpr,
4823 Expr *ColumnExpr,
4824 SourceLocation AttrLoc) const {
4825 QualType CanonElementTy = getCanonicalType(ElementTy);
4826 llvm::FoldingSetNodeID ID;
4827 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4828 ColumnExpr);
4829
4830 void *InsertPos = nullptr;
4832 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4833
4834 if (!Canon) {
4835 Canon = new (*this, alignof(DependentSizedMatrixType))
4836 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4837 ColumnExpr, AttrLoc);
4838#ifndef NDEBUG
4839 DependentSizedMatrixType *CanonCheck =
4840 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4841 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4842#endif
4843 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4844 Types.push_back(Canon);
4845 }
4846
4847 // Already have a canonical version of the matrix type
4848 //
4849 // If it exactly matches the requested type, use it directly.
4850 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4851 Canon->getRowExpr() == ColumnExpr)
4852 return QualType(Canon, 0);
4853
4854 // Use Canon as the canonical type for newly-built type.
4856 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4857 ColumnExpr, AttrLoc);
4858 Types.push_back(New);
4859 return QualType(New, 0);
4860}
4861
4863 Expr *AddrSpaceExpr,
4864 SourceLocation AttrLoc) const {
4865 assert(AddrSpaceExpr->isInstantiationDependent());
4866
4867 QualType canonPointeeType = getCanonicalType(PointeeType);
4868
4869 void *insertPos = nullptr;
4870 llvm::FoldingSetNodeID ID;
4871 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4872 AddrSpaceExpr);
4873
4874 DependentAddressSpaceType *canonTy =
4875 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4876
4877 if (!canonTy) {
4878 canonTy = new (*this, alignof(DependentAddressSpaceType))
4879 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4880 AttrLoc);
4881 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4882 Types.push_back(canonTy);
4883 }
4884
4885 if (canonPointeeType == PointeeType &&
4886 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4887 return QualType(canonTy, 0);
4888
4889 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4890 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4891 AddrSpaceExpr, AttrLoc);
4892 Types.push_back(sugaredType);
4893 return QualType(sugaredType, 0);
4894}
4895
4896/// Determine whether \p T is canonical as the result type of a function.
4898 return T.isCanonical() &&
4899 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4900 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4901}
4902
4903/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4904QualType
4906 const FunctionType::ExtInfo &Info) const {
4907 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4908 // functionality creates a function without a prototype regardless of
4909 // language mode (so it makes them even in C++). Once the rewriter has been
4910 // fixed, this assertion can be enabled again.
4911 //assert(!LangOpts.requiresStrictPrototypes() &&
4912 // "strict prototypes are disabled");
4913
4914 // Unique functions, to guarantee there is only one function of a particular
4915 // structure.
4916 llvm::FoldingSetNodeID ID;
4917 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4918
4919 void *InsertPos = nullptr;
4920 if (FunctionNoProtoType *FT =
4921 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4922 return QualType(FT, 0);
4923
4924 QualType Canonical;
4925 if (!isCanonicalResultType(ResultTy)) {
4926 Canonical =
4928
4929 // Get the new insert position for the node we care about.
4930 FunctionNoProtoType *NewIP =
4931 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4932 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4933 }
4934
4935 auto *New = new (*this, alignof(FunctionNoProtoType))
4936 FunctionNoProtoType(ResultTy, Canonical, Info);
4937 Types.push_back(New);
4938 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4939 return QualType(New, 0);
4940}
4941
4944 CanQualType CanResultType = getCanonicalType(ResultType);
4945
4946 // Canonical result types do not have ARC lifetime qualifiers.
4947 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4948 Qualifiers Qs = CanResultType.getQualifiers();
4949 Qs.removeObjCLifetime();
4951 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4952 }
4953
4954 return CanResultType;
4955}
4956
4958 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4959 if (ESI.Type == EST_None)
4960 return true;
4961 if (!NoexceptInType)
4962 return false;
4963
4964 // C++17 onwards: exception specification is part of the type, as a simple
4965 // boolean "can this function type throw".
4966 if (ESI.Type == EST_BasicNoexcept)
4967 return true;
4968
4969 // A noexcept(expr) specification is (possibly) canonical if expr is
4970 // value-dependent.
4971 if (ESI.Type == EST_DependentNoexcept)
4972 return true;
4973
4974 // A dynamic exception specification is canonical if it only contains pack
4975 // expansions (so we can't tell whether it's non-throwing) and all its
4976 // contained types are canonical.
4977 if (ESI.Type == EST_Dynamic) {
4978 bool AnyPackExpansions = false;
4979 for (QualType ET : ESI.Exceptions) {
4980 if (!ET.isCanonical())
4981 return false;
4982 if (ET->getAs<PackExpansionType>())
4983 AnyPackExpansions = true;
4984 }
4985 return AnyPackExpansions;
4986 }
4987
4988 return false;
4989}
4990
4991QualType ASTContext::getFunctionTypeInternal(
4992 QualType ResultTy, ArrayRef<QualType> ArgArray,
4993 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4994 size_t NumArgs = ArgArray.size();
4995
4996 // Unique functions, to guarantee there is only one function of a particular
4997 // structure.
4998 llvm::FoldingSetNodeID ID;
4999 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5000 *this, true);
5001
5002 QualType Canonical;
5003 bool Unique = false;
5004
5005 void *InsertPos = nullptr;
5006 if (FunctionProtoType *FPT =
5007 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5008 QualType Existing = QualType(FPT, 0);
5009
5010 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5011 // it so long as our exception specification doesn't contain a dependent
5012 // noexcept expression, or we're just looking for a canonical type.
5013 // Otherwise, we're going to need to create a type
5014 // sugar node to hold the concrete expression.
5015 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5016 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5017 return Existing;
5018
5019 // We need a new type sugar node for this one, to hold the new noexcept
5020 // expression. We do no canonicalization here, but that's OK since we don't
5021 // expect to see the same noexcept expression much more than once.
5022 Canonical = getCanonicalType(Existing);
5023 Unique = true;
5024 }
5025
5026 bool NoexceptInType = getLangOpts().CPlusPlus17;
5027 bool IsCanonicalExceptionSpec =
5029
5030 // Determine whether the type being created is already canonical or not.
5031 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5032 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5033 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5034 if (!ArgArray[i].isCanonicalAsParam())
5035 isCanonical = false;
5036
5037 if (OnlyWantCanonical)
5038 assert(isCanonical &&
5039 "given non-canonical parameters constructing canonical type");
5040
5041 // If this type isn't canonical, get the canonical version of it if we don't
5042 // already have it. The exception spec is only partially part of the
5043 // canonical type, and only in C++17 onwards.
5044 if (!isCanonical && Canonical.isNull()) {
5045 SmallVector<QualType, 16> CanonicalArgs;
5046 CanonicalArgs.reserve(NumArgs);
5047 for (unsigned i = 0; i != NumArgs; ++i)
5048 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5049
5050 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5051 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5052 CanonicalEPI.HasTrailingReturn = false;
5053
5054 if (IsCanonicalExceptionSpec) {
5055 // Exception spec is already OK.
5056 } else if (NoexceptInType) {
5057 switch (EPI.ExceptionSpec.Type) {
5059 // We don't know yet. It shouldn't matter what we pick here; no-one
5060 // should ever look at this.
5061 [[fallthrough]];
5062 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5063 CanonicalEPI.ExceptionSpec.Type = EST_None;
5064 break;
5065
5066 // A dynamic exception specification is almost always "not noexcept",
5067 // with the exception that a pack expansion might expand to no types.
5068 case EST_Dynamic: {
5069 bool AnyPacks = false;
5070 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5071 if (ET->getAs<PackExpansionType>())
5072 AnyPacks = true;
5073 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5074 }
5075 if (!AnyPacks)
5076 CanonicalEPI.ExceptionSpec.Type = EST_None;
5077 else {
5078 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5079 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5080 }
5081 break;
5082 }
5083
5084 case EST_DynamicNone:
5085 case EST_BasicNoexcept:
5086 case EST_NoexceptTrue:
5087 case EST_NoThrow:
5088 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5089 break;
5090
5092 llvm_unreachable("dependent noexcept is already canonical");
5093 }
5094 } else {
5095 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5096 }
5097
5098 // Adjust the canonical function result type.
5099 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5100 Canonical =
5101 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5102
5103 // Get the new insert position for the node we care about.
5104 FunctionProtoType *NewIP =
5105 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5106 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5107 }
5108
5109 // Compute the needed size to hold this FunctionProtoType and the
5110 // various trailing objects.
5111 auto ESH = FunctionProtoType::getExceptionSpecSize(
5112 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5113 size_t Size = FunctionProtoType::totalSizeToAlloc<
5114 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5115 FunctionType::FunctionTypeExtraAttributeInfo,
5116 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5117 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5118 FunctionEffect, EffectConditionExpr>(
5121 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5122 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5123 EPI.ExtParameterInfos ? NumArgs : 0,
5125 EPI.FunctionEffects.conditions().size());
5126
5127 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5128 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5129 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5130 Types.push_back(FTP);
5131 if (!Unique)
5132 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5133 if (!EPI.FunctionEffects.empty())
5134 AnyFunctionEffects = true;
5135 return QualType(FTP, 0);
5136}
5137
5138QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5139 llvm::FoldingSetNodeID ID;
5140 PipeType::Profile(ID, T, ReadOnly);
5141
5142 void *InsertPos = nullptr;
5143 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5144 return QualType(PT, 0);
5145
5146 // If the pipe element type isn't canonical, this won't be a canonical type
5147 // either, so fill in the canonical type field.
5148 QualType Canonical;
5149 if (!T.isCanonical()) {
5150 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5151
5152 // Get the new insert position for the node we care about.
5153 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5154 assert(!NewIP && "Shouldn't be in the map!");
5155 (void)NewIP;
5156 }
5157 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5158 Types.push_back(New);
5159 PipeTypes.InsertNode(New, InsertPos);
5160 return QualType(New, 0);
5161}
5162
5164 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5165 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5166 : Ty;
5167}
5168
5170 return getPipeType(T, true);
5171}
5172
5174 return getPipeType(T, false);
5175}
5176
5177QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5178 llvm::FoldingSetNodeID ID;
5179 BitIntType::Profile(ID, IsUnsigned, NumBits);
5180
5181 void *InsertPos = nullptr;
5182 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5183 return QualType(EIT, 0);
5184
5185 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5186 BitIntTypes.InsertNode(New, InsertPos);
5187 Types.push_back(New);
5188 return QualType(New, 0);
5189}
5190
5192 Expr *NumBitsExpr) const {
5193 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5194 llvm::FoldingSetNodeID ID;
5195 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5196
5197 void *InsertPos = nullptr;
5198 if (DependentBitIntType *Existing =
5199 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5200 return QualType(Existing, 0);
5201
5202 auto *New = new (*this, alignof(DependentBitIntType))
5203 DependentBitIntType(IsUnsigned, NumBitsExpr);
5204 DependentBitIntTypes.InsertNode(New, InsertPos);
5205
5206 Types.push_back(New);
5207 return QualType(New, 0);
5208}
5209
5212 using Kind = PredefinedSugarType::Kind;
5213
5214 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5215 Target != nullptr)
5216 return QualType(Target, 0);
5217
5218 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5219 switch (KDI) {
5220 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5221 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5222 // are part of the core language and are widely used. Using
5223 // PredefinedSugarType makes these types as named sugar types rather than
5224 // standard integer types, enabling better hints and diagnostics.
5225 case Kind::SizeT:
5226 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5227 case Kind::SignedSizeT:
5228 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5229 case Kind::PtrdiffT:
5230 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5231 }
5232 llvm_unreachable("unexpected kind");
5233 };
5234 auto *New = new (*this, alignof(PredefinedSugarType))
5235 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5236 getCanonicalType(*this, static_cast<Kind>(KD)));
5237 Types.push_back(New);
5238 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5239 return QualType(New, 0);
5240}
5241
5243 NestedNameSpecifier Qualifier,
5244 const TypeDecl *Decl) const {
5245 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5246 return getTagType(Keyword, Qualifier, Tag,
5247 /*OwnsTag=*/false);
5248 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5249 return getTypedefType(Keyword, Qualifier, Typedef);
5250 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5251 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5252
5254 assert(!Qualifier);
5255 return QualType(Decl->TypeForDecl, 0);
5256}
5257
5259 if (auto *Tag = dyn_cast<TagDecl>(TD))
5260 return getCanonicalTagType(Tag);
5261 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5262 return getCanonicalType(TN->getUnderlyingType());
5263 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5265 assert(TD->TypeForDecl);
5266 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5267}
5268
5270 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5271 return getCanonicalTagType(TD);
5272 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5273 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5275 /*Qualifier=*/std::nullopt, TD);
5276 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5277 return getCanonicalUnresolvedUsingType(Using);
5278
5279 assert(Decl->TypeForDecl);
5280 return QualType(Decl->TypeForDecl, 0);
5281}
5282
5283/// getTypedefType - Return the unique reference to the type for the
5284/// specified typedef name decl.
5287 NestedNameSpecifier Qualifier,
5288 const TypedefNameDecl *Decl, QualType UnderlyingType,
5289 std::optional<bool> TypeMatchesDeclOrNone) const {
5290 if (!TypeMatchesDeclOrNone) {
5291 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5292 assert(!DeclUnderlyingType.isNull());
5293 if (UnderlyingType.isNull())
5294 UnderlyingType = DeclUnderlyingType;
5295 else
5296 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5297 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5298 } else {
5299 // FIXME: This is a workaround for a serialization cycle: assume the decl
5300 // underlying type is not available; don't touch it.
5301 assert(!UnderlyingType.isNull());
5302 }
5303
5304 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5305 *TypeMatchesDeclOrNone) {
5306 if (Decl->TypeForDecl)
5307 return QualType(Decl->TypeForDecl, 0);
5308
5309 auto *NewType = new (*this, alignof(TypedefType))
5310 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5311 !*TypeMatchesDeclOrNone);
5312
5313 Types.push_back(NewType);
5314 Decl->TypeForDecl = NewType;
5315 return QualType(NewType, 0);
5316 }
5317
5318 llvm::FoldingSetNodeID ID;
5319 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5320 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5321
5322 void *InsertPos = nullptr;
5323 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5324 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5325 return QualType(Placeholder->getType(), 0);
5326
5327 void *Mem =
5328 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5330 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5331 alignof(TypedefType));
5332 auto *NewType =
5333 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5334 UnderlyingType, !*TypeMatchesDeclOrNone);
5335 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5337 TypedefTypes.InsertNode(Placeholder, InsertPos);
5338 Types.push_back(NewType);
5339 return QualType(NewType, 0);
5340}
5341
5343 NestedNameSpecifier Qualifier,
5344 const UsingShadowDecl *D,
5345 QualType UnderlyingType) const {
5346 // FIXME: This is expensive to compute every time!
5347 if (UnderlyingType.isNull()) {
5348 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5349 UnderlyingType =
5352 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5353 }
5354
5355 llvm::FoldingSetNodeID ID;
5356 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5357
5358 void *InsertPos = nullptr;
5359 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5360 return QualType(T, 0);
5361
5362 assert(!UnderlyingType.hasLocalQualifiers());
5363
5364 assert(
5366 UnderlyingType));
5367
5368 void *Mem =
5369 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5370 alignof(UsingType));
5371 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5372 Types.push_back(T);
5373 UsingTypes.InsertNode(T, InsertPos);
5374 return QualType(T, 0);
5375}
5376
5377TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5378 NestedNameSpecifier Qualifier,
5379 const TagDecl *TD, bool OwnsTag,
5380 bool IsInjected,
5381 const Type *CanonicalType,
5382 bool WithFoldingSetNode) const {
5383 auto [TC, Size] = [&] {
5384 switch (TD->getDeclKind()) {
5385 case Decl::Enum:
5386 static_assert(alignof(EnumType) == alignof(TagType));
5387 return std::make_tuple(Type::Enum, sizeof(EnumType));
5388 case Decl::ClassTemplatePartialSpecialization:
5389 case Decl::ClassTemplateSpecialization:
5390 case Decl::CXXRecord:
5391 static_assert(alignof(RecordType) == alignof(TagType));
5392 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5393 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5394 return std::make_tuple(Type::InjectedClassName,
5395 sizeof(InjectedClassNameType));
5396 [[fallthrough]];
5397 case Decl::Record:
5398 return std::make_tuple(Type::Record, sizeof(RecordType));
5399 default:
5400 llvm_unreachable("unexpected decl kind");
5401 }
5402 }();
5403
5404 if (Qualifier) {
5405 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5406 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5407 sizeof(NestedNameSpecifier);
5408 }
5409 void *Mem;
5410 if (WithFoldingSetNode) {
5411 // FIXME: It would be more profitable to tail allocate the folding set node
5412 // from the type, instead of the other way around, due to the greater
5413 // alignment requirements of the type. But this makes it harder to deal with
5414 // the different type node sizes. This would require either uniquing from
5415 // different folding sets, or having the folding setaccept a
5416 // contextual parameter which is not fixed at construction.
5417 Mem = Allocate(
5418 sizeof(TagTypeFoldingSetPlaceholder) +
5419 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5420 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5421 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5422 Mem = T->getTagType();
5423 } else {
5424 Mem = Allocate(Size, alignof(TagType));
5425 }
5426
5427 auto *T = [&, TC = TC]() -> TagType * {
5428 switch (TC) {
5429 case Type::Enum: {
5430 assert(isa<EnumDecl>(TD));
5431 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5432 IsInjected, CanonicalType);
5433 assert(reinterpret_cast<void *>(T) ==
5434 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5435 "TagType must be the first base of EnumType");
5436 return T;
5437 }
5438 case Type::Record: {
5439 assert(isa<RecordDecl>(TD));
5440 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5441 IsInjected, CanonicalType);
5442 assert(reinterpret_cast<void *>(T) ==
5443 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5444 "TagType must be the first base of RecordType");
5445 return T;
5446 }
5447 case Type::InjectedClassName: {
5448 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5449 IsInjected, CanonicalType);
5450 assert(reinterpret_cast<void *>(T) ==
5451 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5452 "TagType must be the first base of InjectedClassNameType");
5453 return T;
5454 }
5455 default:
5456 llvm_unreachable("unexpected type class");
5457 }
5458 }();
5459 assert(T->getKeyword() == Keyword);
5460 assert(T->getQualifier() == Qualifier);
5461 assert(T->getOriginalDecl() == TD);
5462 assert(T->isInjected() == IsInjected);
5463 assert(T->isTagOwned() == OwnsTag);
5464 assert((T->isCanonicalUnqualified()
5465 ? QualType()
5466 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5467 Types.push_back(T);
5468 return T;
5469}
5470
5471static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5472 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5473 RD && RD->isInjectedClassName())
5474 return cast<TagDecl>(RD->getDeclContext());
5475 return TD;
5476}
5477
5480 if (TD->TypeForDecl)
5481 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5482
5483 const Type *CanonicalType = getTagTypeInternal(
5485 /*Qualifier=*/std::nullopt, TD,
5486 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5487 /*WithFoldingSetNode=*/false);
5488 TD->TypeForDecl = CanonicalType;
5489 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5490}
5491
5493 NestedNameSpecifier Qualifier,
5494 const TagDecl *TD, bool OwnsTag) const {
5495
5496 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5497 bool IsInjected = TD != NonInjectedTD;
5498
5499 ElaboratedTypeKeyword PreferredKeyword =
5502 NonInjectedTD->getTagKind());
5503
5504 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5505 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5506 return QualType(T, 0);
5507
5508 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5509 const Type *T =
5510 getTagTypeInternal(Keyword,
5511 /*Qualifier=*/std::nullopt, NonInjectedTD,
5512 /*OwnsTag=*/false, IsInjected, CanonicalType,
5513 /*WithFoldingSetNode=*/false);
5514 TD->TypeForDecl = T;
5515 return QualType(T, 0);
5516 }
5517
5518 llvm::FoldingSetNodeID ID;
5519 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5520 OwnsTag, IsInjected);
5521
5522 void *InsertPos = nullptr;
5523 if (TagTypeFoldingSetPlaceholder *T =
5524 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5525 return QualType(T->getTagType(), 0);
5526
5527 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5528 TagType *T =
5529 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5530 CanonicalType, /*WithFoldingSetNode=*/true);
5531 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5532 return QualType(T, 0);
5533}
5534
5535bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5536 unsigned NumPositiveBits,
5537 QualType &BestType,
5538 QualType &BestPromotionType) {
5539 unsigned IntWidth = Target->getIntWidth();
5540 unsigned CharWidth = Target->getCharWidth();
5541 unsigned ShortWidth = Target->getShortWidth();
5542 bool EnumTooLarge = false;
5543 unsigned BestWidth;
5544 if (NumNegativeBits) {
5545 // If there is a negative value, figure out the smallest integer type (of
5546 // int/long/longlong) that fits.
5547 // If it's packed, check also if it fits a char or a short.
5548 if (IsPacked && NumNegativeBits <= CharWidth &&
5549 NumPositiveBits < CharWidth) {
5550 BestType = SignedCharTy;
5551 BestWidth = CharWidth;
5552 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5553 NumPositiveBits < ShortWidth) {
5554 BestType = ShortTy;
5555 BestWidth = ShortWidth;
5556 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5557 BestType = IntTy;
5558 BestWidth = IntWidth;
5559 } else {
5560 BestWidth = Target->getLongWidth();
5561
5562 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5563 BestType = LongTy;
5564 } else {
5565 BestWidth = Target->getLongLongWidth();
5566
5567 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5568 EnumTooLarge = true;
5569 BestType = LongLongTy;
5570 }
5571 }
5572 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5573 } else {
5574 // If there is no negative value, figure out the smallest type that fits
5575 // all of the enumerator values.
5576 // If it's packed, check also if it fits a char or a short.
5577 if (IsPacked && NumPositiveBits <= CharWidth) {
5578 BestType = UnsignedCharTy;
5579 BestPromotionType = IntTy;
5580 BestWidth = CharWidth;
5581 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5582 BestType = UnsignedShortTy;
5583 BestPromotionType = IntTy;
5584 BestWidth = ShortWidth;
5585 } else if (NumPositiveBits <= IntWidth) {
5586 BestType = UnsignedIntTy;
5587 BestWidth = IntWidth;
5588 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5590 : IntTy;
5591 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5592 BestType = UnsignedLongTy;
5593 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5595 : LongTy;
5596 } else {
5597 BestWidth = Target->getLongLongWidth();
5598 if (NumPositiveBits > BestWidth) {
5599 // This can happen with bit-precise integer types, but those are not
5600 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5601 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5602 // a 128-bit integer, we should consider doing the same.
5603 EnumTooLarge = true;
5604 }
5605 BestType = UnsignedLongLongTy;
5606 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5608 : LongLongTy;
5609 }
5610 }
5611 return EnumTooLarge;
5612}
5613
5615 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5616 "Integral type required!");
5617 unsigned BitWidth = getIntWidth(T);
5618
5619 if (Value.isUnsigned() || Value.isNonNegative()) {
5620 if (T->isSignedIntegerOrEnumerationType())
5621 --BitWidth;
5622 return Value.getActiveBits() <= BitWidth;
5623 }
5624 return Value.getSignificantBits() <= BitWidth;
5625}
5626
5627UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5629 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5630 const Type *CanonicalType) const {
5631 void *Mem = Allocate(
5632 UnresolvedUsingType::totalSizeToAlloc<
5634 !!InsertPos, !!Qualifier),
5635 alignof(UnresolvedUsingType));
5636 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5637 if (InsertPos) {
5638 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5640 TypedefTypes.InsertNode(Placeholder, InsertPos);
5641 }
5642 Types.push_back(T);
5643 return T;
5644}
5645
5647 const UnresolvedUsingTypenameDecl *D) const {
5648 D = D->getCanonicalDecl();
5649 if (D->TypeForDecl)
5650 return D->TypeForDecl->getCanonicalTypeUnqualified();
5651
5652 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5654 /*Qualifier=*/std::nullopt, D,
5655 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5656 D->TypeForDecl = CanonicalType;
5657 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5658}
5659
5662 NestedNameSpecifier Qualifier,
5663 const UnresolvedUsingTypenameDecl *D) const {
5664 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5665 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5666 return QualType(T, 0);
5667
5668 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5669 const Type *T =
5670 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5671 /*Qualifier=*/std::nullopt, D,
5672 /*InsertPos=*/nullptr, CanonicalType);
5673 D->TypeForDecl = T;
5674 return QualType(T, 0);
5675 }
5676
5677 llvm::FoldingSetNodeID ID;
5678 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5679
5680 void *InsertPos = nullptr;
5682 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5683 return QualType(Placeholder->getType(), 0);
5684 assert(InsertPos);
5685
5686 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5687 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5688 InsertPos, CanonicalType);
5689 return QualType(T, 0);
5690}
5691
5693 QualType modifiedType,
5694 QualType equivalentType,
5695 const Attr *attr) const {
5696 llvm::FoldingSetNodeID id;
5697 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5698
5699 void *insertPos = nullptr;
5700 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5701 if (type) return QualType(type, 0);
5702
5703 assert(!attr || attr->getKind() == attrKind);
5704
5705 QualType canon = getCanonicalType(equivalentType);
5706 type = new (*this, alignof(AttributedType))
5707 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5708
5709 Types.push_back(type);
5710 AttributedTypes.InsertNode(type, insertPos);
5711
5712 return QualType(type, 0);
5713}
5714
5716 QualType equivalentType) const {
5717 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5718}
5719
5721 QualType modifiedType,
5722 QualType equivalentType) {
5723 switch (nullability) {
5725 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5726
5728 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5729
5731 return getAttributedType(attr::TypeNullableResult, modifiedType,
5732 equivalentType);
5733
5735 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5736 equivalentType);
5737 }
5738
5739 llvm_unreachable("Unknown nullability kind");
5740}
5741
5742QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5743 QualType Wrapped) const {
5744 llvm::FoldingSetNodeID ID;
5745 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5746
5747 void *InsertPos = nullptr;
5748 BTFTagAttributedType *Ty =
5749 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5750 if (Ty)
5751 return QualType(Ty, 0);
5752
5753 QualType Canon = getCanonicalType(Wrapped);
5754 Ty = new (*this, alignof(BTFTagAttributedType))
5755 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5756
5757 Types.push_back(Ty);
5758 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5759
5760 return QualType(Ty, 0);
5761}
5762
5764 QualType Wrapped, QualType Contained,
5765 const HLSLAttributedResourceType::Attributes &Attrs) {
5766
5767 llvm::FoldingSetNodeID ID;
5768 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5769
5770 void *InsertPos = nullptr;
5771 HLSLAttributedResourceType *Ty =
5772 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5773 if (Ty)
5774 return QualType(Ty, 0);
5775
5776 Ty = new (*this, alignof(HLSLAttributedResourceType))
5777 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5778
5779 Types.push_back(Ty);
5780 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5781
5782 return QualType(Ty, 0);
5783}
5784
5785QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5786 uint32_t Alignment,
5787 ArrayRef<SpirvOperand> Operands) {
5788 llvm::FoldingSetNodeID ID;
5789 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5790
5791 void *InsertPos = nullptr;
5792 HLSLInlineSpirvType *Ty =
5793 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5794 if (Ty)
5795 return QualType(Ty, 0);
5796
5797 void *Mem = Allocate(
5798 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5799 alignof(HLSLInlineSpirvType));
5800
5801 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5802
5803 Types.push_back(Ty);
5804 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5805
5806 return QualType(Ty, 0);
5807}
5808
5809/// Retrieve a substitution-result type.
5811 Decl *AssociatedDecl,
5812 unsigned Index,
5813 UnsignedOrNone PackIndex,
5814 bool Final) const {
5815 llvm::FoldingSetNodeID ID;
5816 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5817 PackIndex, Final);
5818 void *InsertPos = nullptr;
5819 SubstTemplateTypeParmType *SubstParm =
5820 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5821
5822 if (!SubstParm) {
5823 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5824 !Replacement.isCanonical()),
5825 alignof(SubstTemplateTypeParmType));
5826 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5827 Index, PackIndex, Final);
5828 Types.push_back(SubstParm);
5829 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5830 }
5831
5832 return QualType(SubstParm, 0);
5833}
5834
5837 unsigned Index, bool Final,
5838 const TemplateArgument &ArgPack) {
5839#ifndef NDEBUG
5840 for (const auto &P : ArgPack.pack_elements())
5841 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5842#endif
5843
5844 llvm::FoldingSetNodeID ID;
5845 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5846 ArgPack);
5847 void *InsertPos = nullptr;
5848 if (SubstTemplateTypeParmPackType *SubstParm =
5849 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5850 return QualType(SubstParm, 0);
5851
5852 QualType Canon;
5853 {
5854 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5855 if (!AssociatedDecl->isCanonicalDecl() ||
5856 !CanonArgPack.structurallyEquals(ArgPack)) {
5858 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5859 [[maybe_unused]] const auto *Nothing =
5860 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5861 assert(!Nothing);
5862 }
5863 }
5864
5865 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5866 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5867 ArgPack);
5868 Types.push_back(SubstParm);
5869 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5870 return QualType(SubstParm, 0);
5871}
5872
5875 assert(llvm::all_of(ArgPack.pack_elements(),
5876 [](const auto &P) {
5877 return P.getKind() == TemplateArgument::Type;
5878 }) &&
5879 "Pack contains a non-type");
5880
5881 llvm::FoldingSetNodeID ID;
5882 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5883
5884 void *InsertPos = nullptr;
5885 if (auto *T =
5886 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5887 return QualType(T, 0);
5888
5889 QualType Canon;
5890 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5891 if (!CanonArgPack.structurallyEquals(ArgPack))
5892 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5893
5894 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5895 SubstBuiltinTemplatePackType(Canon, ArgPack);
5896 Types.push_back(PackType);
5897 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5898 return QualType(PackType, 0);
5899}
5900
5901/// Retrieve the template type parameter type for a template
5902/// parameter or parameter pack with the given depth, index, and (optionally)
5903/// name.
5904QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5905 bool ParameterPack,
5906 TemplateTypeParmDecl *TTPDecl) const {
5907 llvm::FoldingSetNodeID ID;
5908 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5909 void *InsertPos = nullptr;
5910 TemplateTypeParmType *TypeParm
5911 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5912
5913 if (TypeParm)
5914 return QualType(TypeParm, 0);
5915
5916 if (TTPDecl) {
5917 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5918 TypeParm = new (*this, alignof(TemplateTypeParmType))
5919 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5920
5921 TemplateTypeParmType *TypeCheck
5922 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5923 assert(!TypeCheck && "Template type parameter canonical type broken");
5924 (void)TypeCheck;
5925 } else
5926 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5927 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5928
5929 Types.push_back(TypeParm);
5930 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5931
5932 return QualType(TypeParm, 0);
5933}
5934
5936 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5937 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5938 TemplateName Name, SourceLocation NameLoc,
5939 const TemplateArgumentListInfo &SpecifiedArgs,
5940 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5942 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5943
5946 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5947 SpecifiedArgs);
5948 return DI;
5949}
5950
5953 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5954 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5955 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5956 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5957 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5958 SpecifiedArgVec.push_back(Arg.getArgument());
5959
5960 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5961 CanonicalArgs, Underlying);
5962}
5963
5964[[maybe_unused]] static bool
5966 for (const TemplateArgument &Arg : Args)
5967 if (Arg.isPackExpansion())
5968 return true;
5969 return false;
5970}
5971
5974 assert(Template ==
5975 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5976 assert(!Args.empty());
5977#ifndef NDEBUG
5978 for (const auto &Arg : Args)
5979 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5980#endif
5981
5982 llvm::FoldingSetNodeID ID;
5983 TemplateSpecializationType::Profile(ID, Template, Args, QualType(), *this);
5984 void *InsertPos = nullptr;
5985 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5986 return QualType(T, 0);
5987
5988 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5989 sizeof(TemplateArgument) * Args.size(),
5990 alignof(TemplateSpecializationType));
5991 auto *Spec = new (Mem)
5992 TemplateSpecializationType(ElaboratedTypeKeyword::None, Template,
5993 /*IsAlias=*/false, Args, QualType());
5994 assert(Spec->isDependentType() &&
5995 "canonical template specialization must be dependent");
5996 Types.push_back(Spec);
5997 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5998 return QualType(Spec, 0);
5999}
6000
6003 ArrayRef<TemplateArgument> SpecifiedArgs,
6004 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6005 assert(!Template.getUnderlying().getAsDependentTemplateName() &&
6006 "No dependent template names here!");
6007
6008 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6009 bool IsTypeAlias = TD && TD->isTypeAlias();
6010 if (Underlying.isNull()) {
6011 TemplateName CanonTemplate =
6012 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6013 bool NonCanonical =
6014 Template != CanonTemplate || Keyword != ElaboratedTypeKeyword::None;
6016 if (CanonicalArgs.empty()) {
6017 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6018 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6019 CanonicalArgs = CanonArgsVec;
6020 } else {
6021 NonCanonical |= !llvm::equal(
6022 SpecifiedArgs, CanonicalArgs,
6023 [](const TemplateArgument &A, const TemplateArgument &B) {
6024 return A.structurallyEquals(B);
6025 });
6026 }
6027
6028 // We can get here with an alias template when the specialization
6029 // contains a pack expansion that does not match up with a parameter
6030 // pack, or a builtin template which cannot be resolved due to dependency.
6031 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6032 hasAnyPackExpansions(CanonicalArgs)) &&
6033 "Caller must compute aliased type");
6034 IsTypeAlias = false;
6035
6036 Underlying =
6037 getCanonicalTemplateSpecializationType(CanonTemplate, CanonicalArgs);
6038 if (!NonCanonical)
6039 return Underlying;
6040 }
6041 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6042 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6043 (IsTypeAlias ? sizeof(QualType) : 0),
6044 alignof(TemplateSpecializationType));
6045 auto *Spec = new (Mem) TemplateSpecializationType(
6046 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6047 Types.push_back(Spec);
6048 return QualType(Spec, 0);
6049}
6050
6053 llvm::FoldingSetNodeID ID;
6054 ParenType::Profile(ID, InnerType);
6055
6056 void *InsertPos = nullptr;
6057 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6058 if (T)
6059 return QualType(T, 0);
6060
6061 QualType Canon = InnerType;
6062 if (!Canon.isCanonical()) {
6063 Canon = getCanonicalType(InnerType);
6064 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6065 assert(!CheckT && "Paren canonical type broken");
6066 (void)CheckT;
6067 }
6068
6069 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6070 Types.push_back(T);
6071 ParenTypes.InsertNode(T, InsertPos);
6072 return QualType(T, 0);
6073}
6074
6077 const IdentifierInfo *MacroII) const {
6078 QualType Canon = UnderlyingTy;
6079 if (!Canon.isCanonical())
6080 Canon = getCanonicalType(UnderlyingTy);
6081
6082 auto *newType = new (*this, alignof(MacroQualifiedType))
6083 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6084 Types.push_back(newType);
6085 return QualType(newType, 0);
6086}
6087
6090 switch (Keyword) {
6091 // These are just themselves.
6097 return Keyword;
6098
6099 // These are equivalent.
6102
6103 // These are functionally equivalent, so relying on their equivalence is
6104 // IFNDR. By making them equivalent, we disallow overloading, which at least
6105 // can produce a diagnostic.
6108 }
6109 llvm_unreachable("unexpected keyword kind");
6110}
6111
6114 const IdentifierInfo *Name) const {
6115 llvm::FoldingSetNodeID ID;
6116 DependentNameType::Profile(ID, Keyword, NNS, Name);
6117
6118 void *InsertPos = nullptr;
6119 if (DependentNameType *T =
6120 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6121 return QualType(T, 0);
6122
6123 ElaboratedTypeKeyword CanonKeyword =
6125 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6126
6127 QualType Canon;
6128 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6129 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6130 [[maybe_unused]] DependentNameType *T =
6131 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6132 assert(!T && "broken canonicalization");
6133 assert(Canon.isCanonical());
6134 }
6135
6136 DependentNameType *T = new (*this, alignof(DependentNameType))
6137 DependentNameType(Keyword, NNS, Name, Canon);
6138 Types.push_back(T);
6139 DependentNameTypes.InsertNode(T, InsertPos);
6140 return QualType(T, 0);
6141}
6142
6145 ArrayRef<TemplateArgumentLoc> Args) const {
6146 // TODO: avoid this copy
6148 for (unsigned I = 0, E = Args.size(); I != E; ++I)
6149 ArgCopy.push_back(Args[I].getArgument());
6150 return getDependentTemplateSpecializationType(Keyword, Name, ArgCopy);
6151}
6152
6155 ArrayRef<TemplateArgument> Args, bool IsCanonical) const {
6156 llvm::FoldingSetNodeID ID;
6157 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, Name, Args);
6158
6159 if (auto const T_iter = DependentTemplateSpecializationTypes.find(ID);
6160 T_iter != DependentTemplateSpecializationTypes.end())
6161 return QualType(T_iter->getSecond(), 0);
6162
6163 NestedNameSpecifier NNS = Name.getQualifier();
6164
6165 QualType Canon;
6166 if (!IsCanonical) {
6167 ElaboratedTypeKeyword CanonKeyword =
6169 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6170 bool AnyNonCanonArgs = false;
6171 auto CanonArgs =
6172 ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
6173
6174 if (CanonKeyword != Keyword || AnyNonCanonArgs || CanonNNS != NNS ||
6175 !Name.hasTemplateKeyword()) {
6177 CanonKeyword, {CanonNNS, Name.getName(), /*HasTemplateKeyword=*/true},
6178 CanonArgs,
6179 /*IsCanonical=*/true);
6180 }
6181 } else {
6183 assert(Name.hasTemplateKeyword());
6184 assert(NNS.isCanonical());
6185#ifndef NDEBUG
6186 for (const auto &Arg : Args)
6187 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6188#endif
6189 }
6190 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
6191 sizeof(TemplateArgument) * Args.size()),
6192 alignof(DependentTemplateSpecializationType));
6193 auto *T =
6194 new (Mem) DependentTemplateSpecializationType(Keyword, Name, Args, Canon);
6195#ifndef NDEBUG
6196 llvm::FoldingSetNodeID InsertedID;
6197 T->Profile(InsertedID, *this);
6198 assert(InsertedID == ID && "ID does not match");
6199#endif
6200 Types.push_back(T);
6201 DependentTemplateSpecializationTypes.try_emplace(ID, T);
6202 return QualType(T, 0);
6203}
6204
6206 TemplateArgument Arg;
6207 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6209 if (TTP->isParameterPack())
6210 ArgType = getPackExpansionType(ArgType, std::nullopt);
6211
6213 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6214 QualType T =
6215 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6216 // For class NTTPs, ensure we include the 'const' so the type matches that
6217 // of a real template argument.
6218 // FIXME: It would be more faithful to model this as something like an
6219 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6221 if (T->isRecordType()) {
6222 // C++ [temp.param]p8: An id-expression naming a non-type
6223 // template-parameter of class type T denotes a static storage duration
6224 // object of type const T.
6225 T.addConst();
6226 VK = VK_LValue;
6227 } else {
6228 VK = Expr::getValueKindForType(NTTP->getType());
6229 }
6230 Expr *E = new (*this)
6231 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6232 T, VK, NTTP->getLocation());
6233
6234 if (NTTP->isParameterPack())
6235 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6236 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6237 } else {
6238 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6240 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6241 TemplateName(TTP));
6242 if (TTP->isParameterPack())
6243 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6244 else
6245 Arg = TemplateArgument(Name);
6246 }
6247
6248 if (Param->isTemplateParameterPack())
6249 Arg =
6250 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6251
6252 return Arg;
6253}
6254
6256 UnsignedOrNone NumExpansions,
6257 bool ExpectPackInType) const {
6258 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6259 "Pack expansions must expand one or more parameter packs");
6260
6261 llvm::FoldingSetNodeID ID;
6262 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6263
6264 void *InsertPos = nullptr;
6265 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6266 if (T)
6267 return QualType(T, 0);
6268
6269 QualType Canon;
6270 if (!Pattern.isCanonical()) {
6271 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6272 /*ExpectPackInType=*/false);
6273
6274 // Find the insert position again, in case we inserted an element into
6275 // PackExpansionTypes and invalidated our insert position.
6276 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6277 }
6278
6279 T = new (*this, alignof(PackExpansionType))
6280 PackExpansionType(Pattern, Canon, NumExpansions);
6281 Types.push_back(T);
6282 PackExpansionTypes.InsertNode(T, InsertPos);
6283 return QualType(T, 0);
6284}
6285
6286/// CmpProtocolNames - Comparison predicate for sorting protocols
6287/// alphabetically.
6288static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6289 ObjCProtocolDecl *const *RHS) {
6290 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6291}
6292
6294 if (Protocols.empty()) return true;
6295
6296 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6297 return false;
6298
6299 for (unsigned i = 1; i != Protocols.size(); ++i)
6300 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6301 Protocols[i]->getCanonicalDecl() != Protocols[i])
6302 return false;
6303 return true;
6304}
6305
6306static void
6308 // Sort protocols, keyed by name.
6309 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6310
6311 // Canonicalize.
6312 for (ObjCProtocolDecl *&P : Protocols)
6313 P = P->getCanonicalDecl();
6314
6315 // Remove duplicates.
6316 auto ProtocolsEnd = llvm::unique(Protocols);
6317 Protocols.erase(ProtocolsEnd, Protocols.end());
6318}
6319
6321 ObjCProtocolDecl * const *Protocols,
6322 unsigned NumProtocols) const {
6323 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6324 /*isKindOf=*/false);
6325}
6326
6328 QualType baseType,
6329 ArrayRef<QualType> typeArgs,
6331 bool isKindOf) const {
6332 // If the base type is an interface and there aren't any protocols or
6333 // type arguments to add, then the interface type will do just fine.
6334 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6335 isa<ObjCInterfaceType>(baseType))
6336 return baseType;
6337
6338 // Look in the folding set for an existing type.
6339 llvm::FoldingSetNodeID ID;
6340 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6341 void *InsertPos = nullptr;
6342 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6343 return QualType(QT, 0);
6344
6345 // Determine the type arguments to be used for canonicalization,
6346 // which may be explicitly specified here or written on the base
6347 // type.
6348 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6349 if (effectiveTypeArgs.empty()) {
6350 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6351 effectiveTypeArgs = baseObject->getTypeArgs();
6352 }
6353
6354 // Build the canonical type, which has the canonical base type and a
6355 // sorted-and-uniqued list of protocols and the type arguments
6356 // canonicalized.
6357 QualType canonical;
6358 bool typeArgsAreCanonical = llvm::all_of(
6359 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6360 bool protocolsSorted = areSortedAndUniqued(protocols);
6361 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6362 // Determine the canonical type arguments.
6363 ArrayRef<QualType> canonTypeArgs;
6364 SmallVector<QualType, 4> canonTypeArgsVec;
6365 if (!typeArgsAreCanonical) {
6366 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6367 for (auto typeArg : effectiveTypeArgs)
6368 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6369 canonTypeArgs = canonTypeArgsVec;
6370 } else {
6371 canonTypeArgs = effectiveTypeArgs;
6372 }
6373
6374 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6375 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6376 if (!protocolsSorted) {
6377 canonProtocolsVec.append(protocols.begin(), protocols.end());
6378 SortAndUniqueProtocols(canonProtocolsVec);
6379 canonProtocols = canonProtocolsVec;
6380 } else {
6381 canonProtocols = protocols;
6382 }
6383
6384 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6385 canonProtocols, isKindOf);
6386
6387 // Regenerate InsertPos.
6388 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6389 }
6390
6391 unsigned size = sizeof(ObjCObjectTypeImpl);
6392 size += typeArgs.size() * sizeof(QualType);
6393 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6394 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6395 auto *T =
6396 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6397 isKindOf);
6398
6399 Types.push_back(T);
6400 ObjCObjectTypes.InsertNode(T, InsertPos);
6401 return QualType(T, 0);
6402}
6403
6404/// Apply Objective-C protocol qualifiers to the given type.
6405/// If this is for the canonical type of a type parameter, we can apply
6406/// protocol qualifiers on the ObjCObjectPointerType.
6409 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6410 bool allowOnPointerType) const {
6411 hasError = false;
6412
6413 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6414 return getObjCTypeParamType(objT->getDecl(), protocols);
6415 }
6416
6417 // Apply protocol qualifiers to ObjCObjectPointerType.
6418 if (allowOnPointerType) {
6419 if (const auto *objPtr =
6420 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6421 const ObjCObjectType *objT = objPtr->getObjectType();
6422 // Merge protocol lists and construct ObjCObjectType.
6424 protocolsVec.append(objT->qual_begin(),
6425 objT->qual_end());
6426 protocolsVec.append(protocols.begin(), protocols.end());
6427 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6429 objT->getBaseType(),
6430 objT->getTypeArgsAsWritten(),
6431 protocols,
6432 objT->isKindOfTypeAsWritten());
6434 }
6435 }
6436
6437 // Apply protocol qualifiers to ObjCObjectType.
6438 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6439 // FIXME: Check for protocols to which the class type is already
6440 // known to conform.
6441
6442 return getObjCObjectType(objT->getBaseType(),
6443 objT->getTypeArgsAsWritten(),
6444 protocols,
6445 objT->isKindOfTypeAsWritten());
6446 }
6447
6448 // If the canonical type is ObjCObjectType, ...
6449 if (type->isObjCObjectType()) {
6450 // Silently overwrite any existing protocol qualifiers.
6451 // TODO: determine whether that's the right thing to do.
6452
6453 // FIXME: Check for protocols to which the class type is already
6454 // known to conform.
6455 return getObjCObjectType(type, {}, protocols, false);
6456 }
6457
6458 // id<protocol-list>
6459 if (type->isObjCIdType()) {
6460 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6461 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6462 objPtr->isKindOfType());
6464 }
6465
6466 // Class<protocol-list>
6467 if (type->isObjCClassType()) {
6468 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6469 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6470 objPtr->isKindOfType());
6472 }
6473
6474 hasError = true;
6475 return type;
6476}
6477
6480 ArrayRef<ObjCProtocolDecl *> protocols) const {
6481 // Look in the folding set for an existing type.
6482 llvm::FoldingSetNodeID ID;
6483 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6484 void *InsertPos = nullptr;
6485 if (ObjCTypeParamType *TypeParam =
6486 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6487 return QualType(TypeParam, 0);
6488
6489 // We canonicalize to the underlying type.
6490 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6491 if (!protocols.empty()) {
6492 // Apply the protocol qualifers.
6493 bool hasError;
6495 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6496 assert(!hasError && "Error when apply protocol qualifier to bound type");
6497 }
6498
6499 unsigned size = sizeof(ObjCTypeParamType);
6500 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6501 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6502 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6503
6504 Types.push_back(newType);
6505 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6506 return QualType(newType, 0);
6507}
6508
6510 ObjCTypeParamDecl *New) const {
6511 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6512 // Update TypeForDecl after updating TypeSourceInfo.
6513 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6515 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6516 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6517 New->TypeForDecl = UpdatedTy.getTypePtr();
6518}
6519
6520/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6521/// protocol list adopt all protocols in QT's qualified-id protocol
6522/// list.
6524 ObjCInterfaceDecl *IC) {
6525 if (!QT->isObjCQualifiedIdType())
6526 return false;
6527
6528 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6529 // If both the right and left sides have qualifiers.
6530 for (auto *Proto : OPT->quals()) {
6531 if (!IC->ClassImplementsProtocol(Proto, false))
6532 return false;
6533 }
6534 return true;
6535 }
6536 return false;
6537}
6538
6539/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6540/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6541/// of protocols.
6543 ObjCInterfaceDecl *IDecl) {
6544 if (!QT->isObjCQualifiedIdType())
6545 return false;
6546 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6547 if (!OPT)
6548 return false;
6549 if (!IDecl->hasDefinition())
6550 return false;
6552 CollectInheritedProtocols(IDecl, InheritedProtocols);
6553 if (InheritedProtocols.empty())
6554 return false;
6555 // Check that if every protocol in list of id<plist> conforms to a protocol
6556 // of IDecl's, then bridge casting is ok.
6557 bool Conforms = false;
6558 for (auto *Proto : OPT->quals()) {
6559 Conforms = false;
6560 for (auto *PI : InheritedProtocols) {
6561 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6562 Conforms = true;
6563 break;
6564 }
6565 }
6566 if (!Conforms)
6567 break;
6568 }
6569 if (Conforms)
6570 return true;
6571
6572 for (auto *PI : InheritedProtocols) {
6573 // If both the right and left sides have qualifiers.
6574 bool Adopts = false;
6575 for (auto *Proto : OPT->quals()) {
6576 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6577 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6578 break;
6579 }
6580 if (!Adopts)
6581 return false;
6582 }
6583 return true;
6584}
6585
6586/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6587/// the given object type.
6589 llvm::FoldingSetNodeID ID;
6590 ObjCObjectPointerType::Profile(ID, ObjectT);
6591
6592 void *InsertPos = nullptr;
6593 if (ObjCObjectPointerType *QT =
6594 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6595 return QualType(QT, 0);
6596
6597 // Find the canonical object type.
6598 QualType Canonical;
6599 if (!ObjectT.isCanonical()) {
6600 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6601
6602 // Regenerate InsertPos.
6603 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6604 }
6605
6606 // No match.
6607 void *Mem =
6609 auto *QType =
6610 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6611
6612 Types.push_back(QType);
6613 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6614 return QualType(QType, 0);
6615}
6616
6617/// getObjCInterfaceType - Return the unique reference to the type for the
6618/// specified ObjC interface decl. The list of protocols is optional.
6620 ObjCInterfaceDecl *PrevDecl) const {
6621 if (Decl->TypeForDecl)
6622 return QualType(Decl->TypeForDecl, 0);
6623
6624 if (PrevDecl) {
6625 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6626 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6627 return QualType(PrevDecl->TypeForDecl, 0);
6628 }
6629
6630 // Prefer the definition, if there is one.
6631 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6632 Decl = Def;
6633
6634 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6635 auto *T = new (Mem) ObjCInterfaceType(Decl);
6636 Decl->TypeForDecl = T;
6637 Types.push_back(T);
6638 return QualType(T, 0);
6639}
6640
6641/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6642/// TypeOfExprType AST's (since expression's are never shared). For example,
6643/// multiple declarations that refer to "typeof(x)" all contain different
6644/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6645/// on canonical type's (which are always unique).
6647 TypeOfExprType *toe;
6648 if (tofExpr->isTypeDependent()) {
6649 llvm::FoldingSetNodeID ID;
6650 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6651 Kind == TypeOfKind::Unqualified);
6652
6653 void *InsertPos = nullptr;
6655 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6656 if (Canon) {
6657 // We already have a "canonical" version of an identical, dependent
6658 // typeof(expr) type. Use that as our canonical type.
6659 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6660 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6661 } else {
6662 // Build a new, canonical typeof(expr) type.
6663 Canon = new (*this, alignof(DependentTypeOfExprType))
6664 DependentTypeOfExprType(*this, tofExpr, Kind);
6665 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6666 toe = Canon;
6667 }
6668 } else {
6669 QualType Canonical = getCanonicalType(tofExpr->getType());
6670 toe = new (*this, alignof(TypeOfExprType))
6671 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6672 }
6673 Types.push_back(toe);
6674 return QualType(toe, 0);
6675}
6676
6677/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6678/// TypeOfType nodes. The only motivation to unique these nodes would be
6679/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6680/// an issue. This doesn't affect the type checker, since it operates
6681/// on canonical types (which are always unique).
6683 QualType Canonical = getCanonicalType(tofType);
6684 auto *tot = new (*this, alignof(TypeOfType))
6685 TypeOfType(*this, tofType, Canonical, Kind);
6686 Types.push_back(tot);
6687 return QualType(tot, 0);
6688}
6689
6690/// getReferenceQualifiedType - Given an expr, will return the type for
6691/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6692/// and class member access into account.
6694 // C++11 [dcl.type.simple]p4:
6695 // [...]
6696 QualType T = E->getType();
6697 switch (E->getValueKind()) {
6698 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6699 // type of e;
6700 case VK_XValue:
6701 return getRValueReferenceType(T);
6702 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6703 // type of e;
6704 case VK_LValue:
6705 return getLValueReferenceType(T);
6706 // - otherwise, decltype(e) is the type of e.
6707 case VK_PRValue:
6708 return T;
6709 }
6710 llvm_unreachable("Unknown value kind");
6711}
6712
6713/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6714/// nodes. This would never be helpful, since each such type has its own
6715/// expression, and would not give a significant memory saving, since there
6716/// is an Expr tree under each such type.
6718 // C++11 [temp.type]p2:
6719 // If an expression e involves a template parameter, decltype(e) denotes a
6720 // unique dependent type. Two such decltype-specifiers refer to the same
6721 // type only if their expressions are equivalent (14.5.6.1).
6722 QualType CanonType;
6723 if (!E->isInstantiationDependent()) {
6724 CanonType = getCanonicalType(UnderlyingType);
6725 } else if (!UnderlyingType.isNull()) {
6726 CanonType = getDecltypeType(E, QualType());
6727 } else {
6728 llvm::FoldingSetNodeID ID;
6729 DependentDecltypeType::Profile(ID, *this, E);
6730
6731 void *InsertPos = nullptr;
6732 if (DependentDecltypeType *Canon =
6733 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6734 return QualType(Canon, 0);
6735
6736 // Build a new, canonical decltype(expr) type.
6737 auto *DT =
6738 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6739 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6740 Types.push_back(DT);
6741 return QualType(DT, 0);
6742 }
6743 auto *DT = new (*this, alignof(DecltypeType))
6744 DecltypeType(E, UnderlyingType, CanonType);
6745 Types.push_back(DT);
6746 return QualType(DT, 0);
6747}
6748
6750 bool FullySubstituted,
6751 ArrayRef<QualType> Expansions,
6752 UnsignedOrNone Index) const {
6753 QualType Canonical;
6754 if (FullySubstituted && Index) {
6755 Canonical = getCanonicalType(Expansions[*Index]);
6756 } else {
6757 llvm::FoldingSetNodeID ID;
6758 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6759 FullySubstituted, Expansions);
6760 void *InsertPos = nullptr;
6761 PackIndexingType *Canon =
6762 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6763 if (!Canon) {
6764 void *Mem = Allocate(
6765 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6767 Canon =
6768 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6769 IndexExpr, FullySubstituted, Expansions);
6770 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6771 }
6772 Canonical = QualType(Canon, 0);
6773 }
6774
6775 void *Mem =
6776 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6778 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6779 FullySubstituted, Expansions);
6780 Types.push_back(T);
6781 return QualType(T, 0);
6782}
6783
6784/// getUnaryTransformationType - We don't unique these, since the memory
6785/// savings are minimal and these are rare.
6788 UnaryTransformType::UTTKind Kind) const {
6789
6790 llvm::FoldingSetNodeID ID;
6791 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6792
6793 void *InsertPos = nullptr;
6794 if (UnaryTransformType *UT =
6795 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6796 return QualType(UT, 0);
6797
6798 QualType CanonType;
6799 if (!BaseType->isDependentType()) {
6800 CanonType = UnderlyingType.getCanonicalType();
6801 } else {
6802 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6803 UnderlyingType = QualType();
6804 if (QualType CanonBase = BaseType.getCanonicalType();
6805 BaseType != CanonBase) {
6806 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6807 assert(CanonType.isCanonical());
6808
6809 // Find the insertion position again.
6810 [[maybe_unused]] UnaryTransformType *UT =
6811 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6812 assert(!UT && "broken canonicalization");
6813 }
6814 }
6815
6816 auto *UT = new (*this, alignof(UnaryTransformType))
6817 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6818 UnaryTransformTypes.InsertNode(UT, InsertPos);
6819 Types.push_back(UT);
6820 return QualType(UT, 0);
6821}
6822
6823QualType ASTContext::getAutoTypeInternal(
6824 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6825 bool IsPack, TemplateDecl *TypeConstraintConcept,
6826 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6827 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6828 !TypeConstraintConcept && !IsDependent)
6829 return getAutoDeductType();
6830
6831 // Look in the folding set for an existing type.
6832 llvm::FoldingSetNodeID ID;
6833 bool IsDeducedDependent =
6834 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6835 (!DeducedType.isNull() && DeducedType->isDependentType());
6836 AutoType::Profile(ID, *this, DeducedType, Keyword,
6837 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6838 TypeConstraintArgs);
6839 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6840 return QualType(AT_iter->getSecond(), 0);
6841
6842 QualType Canon;
6843 if (!IsCanon) {
6844 if (!DeducedType.isNull()) {
6845 Canon = DeducedType.getCanonicalType();
6846 } else if (TypeConstraintConcept) {
6847 bool AnyNonCanonArgs = false;
6848 auto *CanonicalConcept =
6849 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6850 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6851 *this, TypeConstraintArgs, AnyNonCanonArgs);
6852 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6853 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6854 CanonicalConcept, CanonicalConceptArgs,
6855 /*IsCanon=*/true);
6856 }
6857 }
6858 }
6859
6860 void *Mem = Allocate(sizeof(AutoType) +
6861 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6862 alignof(AutoType));
6863 auto *AT = new (Mem) AutoType(
6864 DeducedType, Keyword,
6865 (IsDependent ? TypeDependence::DependentInstantiation
6866 : TypeDependence::None) |
6867 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6868 Canon, TypeConstraintConcept, TypeConstraintArgs);
6869#ifndef NDEBUG
6870 llvm::FoldingSetNodeID InsertedID;
6871 AT->Profile(InsertedID, *this);
6872 assert(InsertedID == ID && "ID does not match");
6873#endif
6874 Types.push_back(AT);
6875 AutoTypes.try_emplace(ID, AT);
6876 return QualType(AT, 0);
6877}
6878
6879/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6880/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6881/// canonical deduced-but-dependent 'auto' type.
6882QualType
6884 bool IsDependent, bool IsPack,
6885 TemplateDecl *TypeConstraintConcept,
6886 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6887 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6888 assert((!IsDependent || DeducedType.isNull()) &&
6889 "A dependent auto should be undeduced");
6890 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6891 TypeConstraintConcept, TypeConstraintArgs);
6892}
6893
6895 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6896
6897 // Remove a type-constraint from a top-level auto or decltype(auto).
6898 if (auto *AT = CanonT->getAs<AutoType>()) {
6899 if (!AT->isConstrained())
6900 return T;
6901 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6902 AT->isDependentType(),
6903 AT->containsUnexpandedParameterPack()),
6904 T.getQualifiers());
6905 }
6906
6907 // FIXME: We only support constrained auto at the top level in the type of a
6908 // non-type template parameter at the moment. Once we lift that restriction,
6909 // we'll need to recursively build types containing auto here.
6910 assert(!CanonT->getContainedAutoType() ||
6911 !CanonT->getContainedAutoType()->isConstrained());
6912 return T;
6913}
6914
6915QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6917 bool IsDependent, QualType Canon) const {
6918 // Look in the folding set for an existing type.
6919 void *InsertPos = nullptr;
6920 llvm::FoldingSetNodeID ID;
6921 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6922 IsDependent);
6923 if (DeducedTemplateSpecializationType *DTST =
6924 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6925 return QualType(DTST, 0);
6926
6927 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6928 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6929 IsDependent, Canon);
6930
6931#ifndef NDEBUG
6932 llvm::FoldingSetNodeID TempID;
6933 DTST->Profile(TempID);
6934 assert(ID == TempID && "ID does not match");
6935#endif
6936 Types.push_back(DTST);
6937 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6938 return QualType(DTST, 0);
6939}
6940
6941/// Return the uniqued reference to the deduced template specialization type
6942/// which has been deduced to the given type, or to the canonical undeduced
6943/// such type, or the canonical deduced-but-dependent such type.
6946 bool IsDependent) const {
6947 // FIXME: This could save an extra hash table lookup if it handled all the
6948 // parameters already being canonical.
6949 // FIXME: Can this be formed from a DependentTemplateName, such that the
6950 // keyword should be part of the canonical type?
6951 QualType Canon =
6952 DeducedType.isNull()
6953 ? getDeducedTemplateSpecializationTypeInternal(
6955 QualType(), IsDependent, QualType())
6956 : DeducedType.getCanonicalType();
6957 return getDeducedTemplateSpecializationTypeInternal(
6958 Keyword, Template, DeducedType, IsDependent, Canon);
6959}
6960
6961/// getAtomicType - Return the uniqued reference to the atomic type for
6962/// the given value type.
6964 // Unique pointers, to guarantee there is only one pointer of a particular
6965 // structure.
6966 llvm::FoldingSetNodeID ID;
6968
6969 void *InsertPos = nullptr;
6970 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6971 return QualType(AT, 0);
6972
6973 // If the atomic value type isn't canonical, this won't be a canonical type
6974 // either, so fill in the canonical type field.
6975 QualType Canonical;
6976 if (!T.isCanonical()) {
6977 Canonical = getAtomicType(getCanonicalType(T));
6978
6979 // Get the new insert position for the node we care about.
6980 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6981 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6982 }
6983 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6984 Types.push_back(New);
6985 AtomicTypes.InsertNode(New, InsertPos);
6986 return QualType(New, 0);
6987}
6988
6989/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6991 if (AutoDeductTy.isNull())
6992 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6993 AutoType(QualType(), AutoTypeKeyword::Auto,
6994 TypeDependence::None, QualType(),
6995 /*concept*/ nullptr, /*args*/ {}),
6996 0);
6997 return AutoDeductTy;
6998}
6999
7000/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7002 if (AutoRRefDeductTy.isNull())
7004 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7005 return AutoRRefDeductTy;
7006}
7007
7008/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7009/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7010/// needs to agree with the definition in <stddef.h>.
7014
7016 return getFromTargetType(Target->getSizeType());
7017}
7018
7019/// Return the unique signed counterpart of the integer type
7020/// corresponding to size_t.
7024
7025/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7026/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7030
7031/// Return the unique unsigned counterpart of "ptrdiff_t"
7032/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7033/// in the definition of %tu format specifier.
7035 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7036}
7037
7038/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7040 return getFromTargetType(Target->getIntMaxType());
7041}
7042
7043/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7045 return getFromTargetType(Target->getUIntMaxType());
7046}
7047
7048/// getSignedWCharType - Return the type of "signed wchar_t".
7049/// Used when in C++, as a GCC extension.
7051 // FIXME: derive from "Target" ?
7052 return WCharTy;
7053}
7054
7055/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7056/// Used when in C++, as a GCC extension.
7058 // FIXME: derive from "Target" ?
7059 return UnsignedIntTy;
7060}
7061
7063 return getFromTargetType(Target->getIntPtrType());
7064}
7065
7069
7070/// Return the unique type for "pid_t" defined in
7071/// <sys/types.h>. We need this to compute the correct type for vfork().
7073 return getFromTargetType(Target->getProcessIDType());
7074}
7075
7076//===----------------------------------------------------------------------===//
7077// Type Operators
7078//===----------------------------------------------------------------------===//
7079
7081 // Push qualifiers into arrays, and then discard any remaining
7082 // qualifiers.
7083 T = getCanonicalType(T);
7085 const Type *Ty = T.getTypePtr();
7089 } else if (isa<ArrayType>(Ty)) {
7091 } else if (isa<FunctionType>(Ty)) {
7092 Result = getPointerType(QualType(Ty, 0));
7093 } else {
7094 Result = QualType(Ty, 0);
7095 }
7096
7098}
7099
7101 Qualifiers &quals) const {
7102 SplitQualType splitType = type.getSplitUnqualifiedType();
7103
7104 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7105 // the unqualified desugared type and then drops it on the floor.
7106 // We then have to strip that sugar back off with
7107 // getUnqualifiedDesugaredType(), which is silly.
7108 const auto *AT =
7109 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7110
7111 // If we don't have an array, just use the results in splitType.
7112 if (!AT) {
7113 quals = splitType.Quals;
7114 return QualType(splitType.Ty, 0);
7115 }
7116
7117 // Otherwise, recurse on the array's element type.
7118 QualType elementType = AT->getElementType();
7119 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7120
7121 // If that didn't change the element type, AT has no qualifiers, so we
7122 // can just use the results in splitType.
7123 if (elementType == unqualElementType) {
7124 assert(quals.empty()); // from the recursive call
7125 quals = splitType.Quals;
7126 return QualType(splitType.Ty, 0);
7127 }
7128
7129 // Otherwise, add in the qualifiers from the outermost type, then
7130 // build the type back up.
7131 quals.addConsistentQualifiers(splitType.Quals);
7132
7133 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7134 return getConstantArrayType(unqualElementType, CAT->getSize(),
7135 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7136 }
7137
7138 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7139 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7140 }
7141
7142 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7143 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7144 VAT->getSizeModifier(),
7145 VAT->getIndexTypeCVRQualifiers());
7146 }
7147
7148 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7149 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7150 DSAT->getSizeModifier(), 0);
7151}
7152
7153/// Attempt to unwrap two types that may both be array types with the same bound
7154/// (or both be array types of unknown bound) for the purpose of comparing the
7155/// cv-decomposition of two types per C++ [conv.qual].
7156///
7157/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7158/// C++20 [conv.qual], if permitted by the current language mode.
7160 bool AllowPiMismatch) const {
7161 while (true) {
7162 auto *AT1 = getAsArrayType(T1);
7163 if (!AT1)
7164 return;
7165
7166 auto *AT2 = getAsArrayType(T2);
7167 if (!AT2)
7168 return;
7169
7170 // If we don't have two array types with the same constant bound nor two
7171 // incomplete array types, we've unwrapped everything we can.
7172 // C++20 also permits one type to be a constant array type and the other
7173 // to be an incomplete array type.
7174 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7175 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7176 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7177 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7178 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7180 return;
7181 } else if (isa<IncompleteArrayType>(AT1)) {
7182 if (!(isa<IncompleteArrayType>(AT2) ||
7183 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7185 return;
7186 } else {
7187 return;
7188 }
7189
7190 T1 = AT1->getElementType();
7191 T2 = AT2->getElementType();
7192 }
7193}
7194
7195/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7196///
7197/// If T1 and T2 are both pointer types of the same kind, or both array types
7198/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7199/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7200///
7201/// This function will typically be called in a loop that successively
7202/// "unwraps" pointer and pointer-to-member types to compare them at each
7203/// level.
7204///
7205/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7206/// C++20 [conv.qual], if permitted by the current language mode.
7207///
7208/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7209/// pair of types that can't be unwrapped further.
7211 bool AllowPiMismatch) const {
7212 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7213
7214 const auto *T1PtrType = T1->getAs<PointerType>();
7215 const auto *T2PtrType = T2->getAs<PointerType>();
7216 if (T1PtrType && T2PtrType) {
7217 T1 = T1PtrType->getPointeeType();
7218 T2 = T2PtrType->getPointeeType();
7219 return true;
7220 }
7221
7222 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7223 *T2MPType = T2->getAs<MemberPointerType>();
7224 T1MPType && T2MPType) {
7225 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7226 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7227 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7228 return false;
7229 if (T1MPType->getQualifier().getCanonical() !=
7230 T2MPType->getQualifier().getCanonical())
7231 return false;
7232 T1 = T1MPType->getPointeeType();
7233 T2 = T2MPType->getPointeeType();
7234 return true;
7235 }
7236
7237 if (getLangOpts().ObjC) {
7238 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7239 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7240 if (T1OPType && T2OPType) {
7241 T1 = T1OPType->getPointeeType();
7242 T2 = T2OPType->getPointeeType();
7243 return true;
7244 }
7245 }
7246
7247 // FIXME: Block pointers, too?
7248
7249 return false;
7250}
7251
7253 while (true) {
7254 Qualifiers Quals;
7255 T1 = getUnqualifiedArrayType(T1, Quals);
7256 T2 = getUnqualifiedArrayType(T2, Quals);
7257 if (hasSameType(T1, T2))
7258 return true;
7259 if (!UnwrapSimilarTypes(T1, T2))
7260 return false;
7261 }
7262}
7263
7265 while (true) {
7266 Qualifiers Quals1, Quals2;
7267 T1 = getUnqualifiedArrayType(T1, Quals1);
7268 T2 = getUnqualifiedArrayType(T2, Quals2);
7269
7270 Quals1.removeCVRQualifiers();
7271 Quals2.removeCVRQualifiers();
7272 if (Quals1 != Quals2)
7273 return false;
7274
7275 if (hasSameType(T1, T2))
7276 return true;
7277
7278 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7279 return false;
7280 }
7281}
7282
7285 SourceLocation NameLoc) const {
7286 switch (Name.getKind()) {
7289 // DNInfo work in progress: CHECKME: what about DNLoc?
7291 NameLoc);
7292
7295 // DNInfo work in progress: CHECKME: what about DNLoc?
7296 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7297 }
7298
7301 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7302 }
7303
7307 DeclarationName DName;
7308 if (const IdentifierInfo *II = TN.getIdentifier()) {
7309 DName = DeclarationNames.getIdentifier(II);
7310 return DeclarationNameInfo(DName, NameLoc);
7311 } else {
7312 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7313 // DNInfo work in progress: FIXME: source locations?
7314 DeclarationNameLoc DNLoc =
7316 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7317 }
7318 }
7319
7323 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7324 NameLoc);
7325 }
7326
7331 NameLoc);
7332 }
7335 NameLoc);
7338 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7339 }
7340 }
7341
7342 llvm_unreachable("bad template name kind!");
7343}
7344
7345static const TemplateArgument *
7347 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7348 if (!TP->hasDefaultArgument())
7349 return nullptr;
7350 return &TP->getDefaultArgument().getArgument();
7351 };
7352 switch (P->getKind()) {
7353 case NamedDecl::TemplateTypeParm:
7354 return handleParam(cast<TemplateTypeParmDecl>(P));
7355 case NamedDecl::NonTypeTemplateParm:
7356 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7357 case NamedDecl::TemplateTemplateParm:
7358 return handleParam(cast<TemplateTemplateParmDecl>(P));
7359 default:
7360 llvm_unreachable("Unexpected template parameter kind");
7361 }
7362}
7363
7365 bool IgnoreDeduced) const {
7366 while (std::optional<TemplateName> UnderlyingOrNone =
7367 Name.desugar(IgnoreDeduced))
7368 Name = *UnderlyingOrNone;
7369
7370 switch (Name.getKind()) {
7373 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7375
7376 // The canonical template name is the canonical template declaration.
7377 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7378 }
7379
7382 llvm_unreachable("cannot canonicalize unresolved template");
7383
7386 assert(DTN && "Non-dependent template names must refer to template decls.");
7387 NestedNameSpecifier Qualifier = DTN->getQualifier();
7388 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7389 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7390 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7391 /*HasTemplateKeyword=*/true});
7392 return Name;
7393 }
7394
7398 TemplateArgument canonArgPack =
7401 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7402 subst->getIndex(), subst->getFinal());
7403 }
7405 assert(IgnoreDeduced == false);
7407 DefaultArguments DefArgs = DTS->getDefaultArguments();
7408 TemplateName Underlying = DTS->getUnderlying();
7409
7410 TemplateName CanonUnderlying =
7411 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7412 bool NonCanonical = CanonUnderlying != Underlying;
7413 auto CanonArgs =
7414 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7415
7416 ArrayRef<NamedDecl *> Params =
7417 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7418 assert(CanonArgs.size() <= Params.size());
7419 // A deduced template name which deduces the same default arguments already
7420 // declared in the underlying template is the same template as the
7421 // underlying template. We need need to note any arguments which differ from
7422 // the corresponding declaration. If any argument differs, we must build a
7423 // deduced template name.
7424 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7426 if (!A)
7427 break;
7428 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7429 TemplateArgument &CanonDefArg = CanonArgs[I];
7430 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7431 continue;
7432 // Keep popping from the back any deault arguments which are the same.
7433 if (I == int(CanonArgs.size() - 1))
7434 CanonArgs.pop_back();
7435 NonCanonical = true;
7436 }
7437 return NonCanonical ? getDeducedTemplateName(
7438 CanonUnderlying,
7439 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7440 : Name;
7441 }
7445 llvm_unreachable("always sugar node");
7446 }
7447
7448 llvm_unreachable("bad template name!");
7449}
7450
7452 const TemplateName &Y,
7453 bool IgnoreDeduced) const {
7454 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7455 getCanonicalTemplateName(Y, IgnoreDeduced);
7456}
7457
7459 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7460 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7461 return false;
7463 return false;
7464 return true;
7465}
7466
7467bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7468 if (!XCE != !YCE)
7469 return false;
7470
7471 if (!XCE)
7472 return true;
7473
7474 llvm::FoldingSetNodeID XCEID, YCEID;
7475 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7476 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7477 return XCEID == YCEID;
7478}
7479
7481 const TypeConstraint *YTC) const {
7482 if (!XTC != !YTC)
7483 return false;
7484
7485 if (!XTC)
7486 return true;
7487
7488 auto *NCX = XTC->getNamedConcept();
7489 auto *NCY = YTC->getNamedConcept();
7490 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7491 return false;
7494 return false;
7496 if (XTC->getConceptReference()
7498 ->NumTemplateArgs !=
7500 return false;
7501
7502 // Compare slowly by profiling.
7503 //
7504 // We couldn't compare the profiling result for the template
7505 // args here. Consider the following example in different modules:
7506 //
7507 // template <__integer_like _Tp, C<_Tp> Sentinel>
7508 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7509 // return __t;
7510 // }
7511 //
7512 // When we compare the profiling result for `C<_Tp>` in different
7513 // modules, it will compare the type of `_Tp` in different modules.
7514 // However, the type of `_Tp` in different modules refer to different
7515 // types here naturally. So we couldn't compare the profiling result
7516 // for the template args directly.
7519}
7520
7522 const NamedDecl *Y) const {
7523 if (X->getKind() != Y->getKind())
7524 return false;
7525
7526 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7527 auto *TY = cast<TemplateTypeParmDecl>(Y);
7528 if (TX->isParameterPack() != TY->isParameterPack())
7529 return false;
7530 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7531 return false;
7532 return isSameTypeConstraint(TX->getTypeConstraint(),
7533 TY->getTypeConstraint());
7534 }
7535
7536 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7537 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7538 return TX->isParameterPack() == TY->isParameterPack() &&
7539 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7540 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7541 TY->getPlaceholderTypeConstraint());
7542 }
7543
7545 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7546 return TX->isParameterPack() == TY->isParameterPack() &&
7547 isSameTemplateParameterList(TX->getTemplateParameters(),
7548 TY->getTemplateParameters());
7549}
7550
7552 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7553 if (X->size() != Y->size())
7554 return false;
7555
7556 for (unsigned I = 0, N = X->size(); I != N; ++I)
7557 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7558 return false;
7559
7560 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7561}
7562
7564 const NamedDecl *Y) const {
7565 // If the type parameter isn't the same already, we don't need to check the
7566 // default argument further.
7567 if (!isSameTemplateParameter(X, Y))
7568 return false;
7569
7570 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7571 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7572 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7573 return false;
7574
7575 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7576 TTPY->getDefaultArgument().getArgument().getAsType());
7577 }
7578
7579 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7580 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7581 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7582 return false;
7583
7584 Expr *DefaultArgumentX =
7585 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7586 Expr *DefaultArgumentY =
7587 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7588 llvm::FoldingSetNodeID XID, YID;
7589 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7590 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7591 return XID == YID;
7592 }
7593
7594 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7595 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7596
7597 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7598 return false;
7599
7600 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7601 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7602 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7603}
7604
7606 const NestedNameSpecifier Y) {
7607 if (X == Y)
7608 return true;
7609 if (!X || !Y)
7610 return false;
7611
7612 auto Kind = X.getKind();
7613 if (Kind != Y.getKind())
7614 return false;
7615
7616 // FIXME: For namespaces and types, we're permitted to check that the entity
7617 // is named via the same tokens. We should probably do so.
7618 switch (Kind) {
7620 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7621 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7622 if (!declaresSameEntity(NamespaceX->getNamespace(),
7623 NamespaceY->getNamespace()))
7624 return false;
7625 return isSameQualifier(PrefixX, PrefixY);
7626 }
7628 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7629 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7630 return false;
7631 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7632 }
7636 return true;
7637 }
7638 llvm_unreachable("unhandled qualifier kind");
7639}
7640
7641static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7642 if (!A->getASTContext().getLangOpts().CUDA)
7643 return true; // Target attributes are overloadable in CUDA compilation only.
7644 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7645 return false;
7646 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7647 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7648 return true; // unattributed and __host__ functions are the same.
7649}
7650
7651/// Determine whether the attributes we can overload on are identical for A and
7652/// B. Will ignore any overloadable attrs represented in the type of A and B.
7654 const FunctionDecl *B) {
7655 // Note that pass_object_size attributes are represented in the function's
7656 // ExtParameterInfo, so we don't need to check them here.
7657
7658 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7659 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7660 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7661
7662 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7663 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7664 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7665
7666 // Return false if the number of enable_if attributes is different.
7667 if (!Cand1A || !Cand2A)
7668 return false;
7669
7670 Cand1ID.clear();
7671 Cand2ID.clear();
7672
7673 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7674 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7675
7676 // Return false if any of the enable_if expressions of A and B are
7677 // different.
7678 if (Cand1ID != Cand2ID)
7679 return false;
7680 }
7681 return hasSameCudaAttrs(A, B);
7682}
7683
7684bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7685 // Caution: this function is called by the AST reader during deserialization,
7686 // so it cannot rely on AST invariants being met. Non-trivial accessors
7687 // should be avoided, along with any traversal of redeclaration chains.
7688
7689 if (X == Y)
7690 return true;
7691
7692 if (X->getDeclName() != Y->getDeclName())
7693 return false;
7694
7695 // Must be in the same context.
7696 //
7697 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7698 // could be two different declarations of the same function. (We will fix the
7699 // semantic DC to refer to the primary definition after merging.)
7700 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7702 return false;
7703
7704 // If either X or Y are local to the owning module, they are only possible to
7705 // be the same entity if they are in the same module.
7706 if (X->isModuleLocal() || Y->isModuleLocal())
7707 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7708 return false;
7709
7710 // Two typedefs refer to the same entity if they have the same underlying
7711 // type.
7712 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7713 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7714 return hasSameType(TypedefX->getUnderlyingType(),
7715 TypedefY->getUnderlyingType());
7716
7717 // Must have the same kind.
7718 if (X->getKind() != Y->getKind())
7719 return false;
7720
7721 // Objective-C classes and protocols with the same name always match.
7723 return true;
7724
7726 // No need to handle these here: we merge them when adding them to the
7727 // template.
7728 return false;
7729 }
7730
7731 // Compatible tags match.
7732 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7733 const auto *TagY = cast<TagDecl>(Y);
7734 return (TagX->getTagKind() == TagY->getTagKind()) ||
7735 ((TagX->getTagKind() == TagTypeKind::Struct ||
7736 TagX->getTagKind() == TagTypeKind::Class ||
7737 TagX->getTagKind() == TagTypeKind::Interface) &&
7738 (TagY->getTagKind() == TagTypeKind::Struct ||
7739 TagY->getTagKind() == TagTypeKind::Class ||
7740 TagY->getTagKind() == TagTypeKind::Interface));
7741 }
7742
7743 // Functions with the same type and linkage match.
7744 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7745 // functions, etc.
7746 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7747 const auto *FuncY = cast<FunctionDecl>(Y);
7748 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7749 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7750 if (CtorX->getInheritedConstructor() &&
7751 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7752 CtorY->getInheritedConstructor().getConstructor()))
7753 return false;
7754 }
7755
7756 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7757 return false;
7758
7759 // Multiversioned functions with different feature strings are represented
7760 // as separate declarations.
7761 if (FuncX->isMultiVersion()) {
7762 const auto *TAX = FuncX->getAttr<TargetAttr>();
7763 const auto *TAY = FuncY->getAttr<TargetAttr>();
7764 assert(TAX && TAY && "Multiversion Function without target attribute");
7765
7766 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7767 return false;
7768 }
7769
7770 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7771 // not the same entity if they are constrained.
7772 if ((FuncX->isMemberLikeConstrainedFriend() ||
7773 FuncY->isMemberLikeConstrainedFriend()) &&
7774 !FuncX->getLexicalDeclContext()->Equals(
7775 FuncY->getLexicalDeclContext())) {
7776 return false;
7777 }
7778
7779 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7780 FuncY->getTrailingRequiresClause()))
7781 return false;
7782
7783 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7784 // Map to the first declaration that we've already merged into this one.
7785 // The TSI of redeclarations might not match (due to calling conventions
7786 // being inherited onto the type but not the TSI), but the TSI type of
7787 // the first declaration of the function should match across modules.
7788 FD = FD->getCanonicalDecl();
7789 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7790 : FD->getType();
7791 };
7792 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7793 if (!hasSameType(XT, YT)) {
7794 // We can get functions with different types on the redecl chain in C++17
7795 // if they have differing exception specifications and at least one of
7796 // the excpetion specs is unresolved.
7797 auto *XFPT = XT->getAs<FunctionProtoType>();
7798 auto *YFPT = YT->getAs<FunctionProtoType>();
7799 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7800 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7803 return true;
7804 return false;
7805 }
7806
7807 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7808 hasSameOverloadableAttrs(FuncX, FuncY);
7809 }
7810
7811 // Variables with the same type and linkage match.
7812 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7813 const auto *VarY = cast<VarDecl>(Y);
7814 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7815 // During deserialization, we might compare variables before we load
7816 // their types. Assume the types will end up being the same.
7817 if (VarX->getType().isNull() || VarY->getType().isNull())
7818 return true;
7819
7820 if (hasSameType(VarX->getType(), VarY->getType()))
7821 return true;
7822
7823 // We can get decls with different types on the redecl chain. Eg.
7824 // template <typename T> struct S { static T Var[]; }; // #1
7825 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7826 // Only? happens when completing an incomplete array type. In this case
7827 // when comparing #1 and #2 we should go through their element type.
7828 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7829 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7830 if (!VarXTy || !VarYTy)
7831 return false;
7832 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7833 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7834 }
7835 return false;
7836 }
7837
7838 // Namespaces with the same name and inlinedness match.
7839 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7840 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7841 return NamespaceX->isInline() == NamespaceY->isInline();
7842 }
7843
7844 // Identical template names and kinds match if their template parameter lists
7845 // and patterns match.
7846 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7847 const auto *TemplateY = cast<TemplateDecl>(Y);
7848
7849 // ConceptDecl wouldn't be the same if their constraint expression differs.
7850 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7851 const auto *ConceptY = cast<ConceptDecl>(Y);
7852 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7853 ConceptY->getConstraintExpr()))
7854 return false;
7855 }
7856
7857 return isSameEntity(TemplateX->getTemplatedDecl(),
7858 TemplateY->getTemplatedDecl()) &&
7859 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7860 TemplateY->getTemplateParameters());
7861 }
7862
7863 // Fields with the same name and the same type match.
7864 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7865 const auto *FDY = cast<FieldDecl>(Y);
7866 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7867 return hasSameType(FDX->getType(), FDY->getType());
7868 }
7869
7870 // Indirect fields with the same target field match.
7871 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7872 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7873 return IFDX->getAnonField()->getCanonicalDecl() ==
7874 IFDY->getAnonField()->getCanonicalDecl();
7875 }
7876
7877 // Enumerators with the same name match.
7879 // FIXME: Also check the value is odr-equivalent.
7880 return true;
7881
7882 // Using shadow declarations with the same target match.
7883 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7884 const auto *USY = cast<UsingShadowDecl>(Y);
7885 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7886 }
7887
7888 // Using declarations with the same qualifier match. (We already know that
7889 // the name matches.)
7890 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7891 const auto *UY = cast<UsingDecl>(Y);
7892 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7893 UX->hasTypename() == UY->hasTypename() &&
7894 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7895 }
7896 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7897 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7898 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7899 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7900 }
7901 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7902 return isSameQualifier(
7903 UX->getQualifier(),
7904 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7905 }
7906
7907 // Using-pack declarations are only created by instantiation, and match if
7908 // they're instantiated from matching UnresolvedUsing...Decls.
7909 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7910 return declaresSameEntity(
7911 UX->getInstantiatedFromUsingDecl(),
7912 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7913 }
7914
7915 // Namespace alias definitions with the same target match.
7916 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7917 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7918 return NAX->getNamespace()->Equals(NAY->getNamespace());
7919 }
7920
7921 return false;
7922}
7923
7926 switch (Arg.getKind()) {
7928 return Arg;
7929
7931 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7932 Arg.getIsDefaulted());
7933
7935 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7937 Arg.getIsDefaulted());
7938 }
7939
7942 /*isNullPtr*/ true, Arg.getIsDefaulted());
7943
7946 Arg.getIsDefaulted());
7947
7949 return TemplateArgument(
7952
7955
7957 return TemplateArgument(*this,
7960
7963 /*isNullPtr*/ false, Arg.getIsDefaulted());
7964
7966 bool AnyNonCanonArgs = false;
7967 auto CanonArgs = ::getCanonicalTemplateArguments(
7968 *this, Arg.pack_elements(), AnyNonCanonArgs);
7969 if (!AnyNonCanonArgs)
7970 return Arg;
7972 const_cast<ASTContext &>(*this), CanonArgs);
7973 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7974 return NewArg;
7975 }
7976 }
7977
7978 // Silence GCC warning
7979 llvm_unreachable("Unhandled template argument kind");
7980}
7981
7983 const TemplateArgument &Arg2) const {
7984 if (Arg1.getKind() != Arg2.getKind())
7985 return false;
7986
7987 switch (Arg1.getKind()) {
7989 llvm_unreachable("Comparing NULL template argument");
7990
7992 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7993
7995 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7997
7999 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8000
8005
8007 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8008 Arg2.getAsIntegral());
8009
8011 return Arg1.structurallyEquals(Arg2);
8012
8014 llvm::FoldingSetNodeID ID1, ID2;
8015 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8016 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8017 return ID1 == ID2;
8018 }
8019
8021 return llvm::equal(
8022 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8023 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8024 return isSameTemplateArgument(Arg1, Arg2);
8025 });
8026 }
8027
8028 llvm_unreachable("Unhandled template argument kind");
8029}
8030
8032 // Handle the non-qualified case efficiently.
8033 if (!T.hasLocalQualifiers()) {
8034 // Handle the common positive case fast.
8035 if (const auto *AT = dyn_cast<ArrayType>(T))
8036 return AT;
8037 }
8038
8039 // Handle the common negative case fast.
8040 if (!isa<ArrayType>(T.getCanonicalType()))
8041 return nullptr;
8042
8043 // Apply any qualifiers from the array type to the element type. This
8044 // implements C99 6.7.3p8: "If the specification of an array type includes
8045 // any type qualifiers, the element type is so qualified, not the array type."
8046
8047 // If we get here, we either have type qualifiers on the type, or we have
8048 // sugar such as a typedef in the way. If we have type qualifiers on the type
8049 // we must propagate them down into the element type.
8050
8051 SplitQualType split = T.getSplitDesugaredType();
8052 Qualifiers qs = split.Quals;
8053
8054 // If we have a simple case, just return now.
8055 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8056 if (!ATy || qs.empty())
8057 return ATy;
8058
8059 // Otherwise, we have an array and we have qualifiers on it. Push the
8060 // qualifiers into the array element type and return a new array type.
8061 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8062
8063 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8064 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8065 CAT->getSizeExpr(),
8066 CAT->getSizeModifier(),
8067 CAT->getIndexTypeCVRQualifiers()));
8068 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8070 IAT->getSizeModifier(),
8071 IAT->getIndexTypeCVRQualifiers()));
8072
8073 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8075 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8076 DSAT->getIndexTypeCVRQualifiers()));
8077
8078 const auto *VAT = cast<VariableArrayType>(ATy);
8079 return cast<ArrayType>(
8080 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8081 VAT->getIndexTypeCVRQualifiers()));
8082}
8083
8085 if (getLangOpts().HLSL && T->isConstantArrayType())
8086 return getArrayParameterType(T);
8087 if (T->isArrayType() || T->isFunctionType())
8088 return getDecayedType(T);
8089 return T;
8090}
8091
8095 return T.getUnqualifiedType();
8096}
8097
8099 // C++ [except.throw]p3:
8100 // A throw-expression initializes a temporary object, called the exception
8101 // object, the type of which is determined by removing any top-level
8102 // cv-qualifiers from the static type of the operand of throw and adjusting
8103 // the type from "array of T" or "function returning T" to "pointer to T"
8104 // or "pointer to function returning T", [...]
8106 if (T->isArrayType() || T->isFunctionType())
8107 T = getDecayedType(T);
8108 return T.getUnqualifiedType();
8109}
8110
8111/// getArrayDecayedType - Return the properly qualified result of decaying the
8112/// specified array type to a pointer. This operation is non-trivial when
8113/// handling typedefs etc. The canonical type of "T" must be an array type,
8114/// this returns a pointer to a properly qualified element of the array.
8115///
8116/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8118 // Get the element type with 'getAsArrayType' so that we don't lose any
8119 // typedefs in the element type of the array. This also handles propagation
8120 // of type qualifiers from the array type into the element type if present
8121 // (C99 6.7.3p8).
8122 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8123 assert(PrettyArrayType && "Not an array type!");
8124
8125 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8126
8127 // int x[restrict 4] -> int *restrict
8129 PrettyArrayType->getIndexTypeQualifiers());
8130
8131 // int x[_Nullable] -> int * _Nullable
8132 if (auto Nullability = Ty->getNullability()) {
8133 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8134 Result, Result);
8135 }
8136 return Result;
8137}
8138
8140 return getBaseElementType(array->getElementType());
8141}
8142
8144 Qualifiers qs;
8145 while (true) {
8146 SplitQualType split = type.getSplitDesugaredType();
8147 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8148 if (!array) break;
8149
8150 type = array->getElementType();
8152 }
8153
8154 return getQualifiedType(type, qs);
8155}
8156
8157/// getConstantArrayElementCount - Returns number of constant array elements.
8158uint64_t
8160 uint64_t ElementCount = 1;
8161 do {
8162 ElementCount *= CA->getZExtSize();
8163 CA = dyn_cast_or_null<ConstantArrayType>(
8165 } while (CA);
8166 return ElementCount;
8167}
8168
8170 const ArrayInitLoopExpr *AILE) const {
8171 if (!AILE)
8172 return 0;
8173
8174 uint64_t ElementCount = 1;
8175
8176 do {
8177 ElementCount *= AILE->getArraySize().getZExtValue();
8178 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8179 } while (AILE);
8180
8181 return ElementCount;
8182}
8183
8184/// getFloatingRank - Return a relative rank for floating point types.
8185/// This routine will assert if passed a built-in type that isn't a float.
8187 if (const auto *CT = T->getAs<ComplexType>())
8188 return getFloatingRank(CT->getElementType());
8189
8190 switch (T->castAs<BuiltinType>()->getKind()) {
8191 default: llvm_unreachable("getFloatingRank(): not a floating type");
8192 case BuiltinType::Float16: return Float16Rank;
8193 case BuiltinType::Half: return HalfRank;
8194 case BuiltinType::Float: return FloatRank;
8195 case BuiltinType::Double: return DoubleRank;
8196 case BuiltinType::LongDouble: return LongDoubleRank;
8197 case BuiltinType::Float128: return Float128Rank;
8198 case BuiltinType::BFloat16: return BFloat16Rank;
8199 case BuiltinType::Ibm128: return Ibm128Rank;
8200 }
8201}
8202
8203/// getFloatingTypeOrder - Compare the rank of the two specified floating
8204/// point types, ignoring the domain of the type (i.e. 'double' ==
8205/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8206/// LHS < RHS, return -1.
8208 FloatingRank LHSR = getFloatingRank(LHS);
8209 FloatingRank RHSR = getFloatingRank(RHS);
8210
8211 if (LHSR == RHSR)
8212 return 0;
8213 if (LHSR > RHSR)
8214 return 1;
8215 return -1;
8216}
8217
8220 return 0;
8221 return getFloatingTypeOrder(LHS, RHS);
8222}
8223
8224/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8225/// routine will assert if passed a built-in type that isn't an integer or enum,
8226/// or if it is not canonicalized.
8227unsigned ASTContext::getIntegerRank(const Type *T) const {
8228 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8229
8230 // Results in this 'losing' to any type of the same size, but winning if
8231 // larger.
8232 if (const auto *EIT = dyn_cast<BitIntType>(T))
8233 return 0 + (EIT->getNumBits() << 3);
8234
8235 switch (cast<BuiltinType>(T)->getKind()) {
8236 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8237 case BuiltinType::Bool:
8238 return 1 + (getIntWidth(BoolTy) << 3);
8239 case BuiltinType::Char_S:
8240 case BuiltinType::Char_U:
8241 case BuiltinType::SChar:
8242 case BuiltinType::UChar:
8243 return 2 + (getIntWidth(CharTy) << 3);
8244 case BuiltinType::Short:
8245 case BuiltinType::UShort:
8246 return 3 + (getIntWidth(ShortTy) << 3);
8247 case BuiltinType::Int:
8248 case BuiltinType::UInt:
8249 return 4 + (getIntWidth(IntTy) << 3);
8250 case BuiltinType::Long:
8251 case BuiltinType::ULong:
8252 return 5 + (getIntWidth(LongTy) << 3);
8253 case BuiltinType::LongLong:
8254 case BuiltinType::ULongLong:
8255 return 6 + (getIntWidth(LongLongTy) << 3);
8256 case BuiltinType::Int128:
8257 case BuiltinType::UInt128:
8258 return 7 + (getIntWidth(Int128Ty) << 3);
8259
8260 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8261 // their underlying types" [c++20 conv.rank]
8262 case BuiltinType::Char8:
8263 return getIntegerRank(UnsignedCharTy.getTypePtr());
8264 case BuiltinType::Char16:
8265 return getIntegerRank(
8266 getFromTargetType(Target->getChar16Type()).getTypePtr());
8267 case BuiltinType::Char32:
8268 return getIntegerRank(
8269 getFromTargetType(Target->getChar32Type()).getTypePtr());
8270 case BuiltinType::WChar_S:
8271 case BuiltinType::WChar_U:
8272 return getIntegerRank(
8273 getFromTargetType(Target->getWCharType()).getTypePtr());
8274 }
8275}
8276
8277/// Whether this is a promotable bitfield reference according
8278/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8279///
8280/// \returns the type this bit-field will promote to, or NULL if no
8281/// promotion occurs.
8283 if (E->isTypeDependent() || E->isValueDependent())
8284 return {};
8285
8286 // C++ [conv.prom]p5:
8287 // If the bit-field has an enumerated type, it is treated as any other
8288 // value of that type for promotion purposes.
8290 return {};
8291
8292 // FIXME: We should not do this unless E->refersToBitField() is true. This
8293 // matters in C where getSourceBitField() will find bit-fields for various
8294 // cases where the source expression is not a bit-field designator.
8295
8296 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8297 if (!Field)
8298 return {};
8299
8300 QualType FT = Field->getType();
8301
8302 uint64_t BitWidth = Field->getBitWidthValue();
8303 uint64_t IntSize = getTypeSize(IntTy);
8304 // C++ [conv.prom]p5:
8305 // A prvalue for an integral bit-field can be converted to a prvalue of type
8306 // int if int can represent all the values of the bit-field; otherwise, it
8307 // can be converted to unsigned int if unsigned int can represent all the
8308 // values of the bit-field. If the bit-field is larger yet, no integral
8309 // promotion applies to it.
8310 // C11 6.3.1.1/2:
8311 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8312 // If an int can represent all values of the original type (as restricted by
8313 // the width, for a bit-field), the value is converted to an int; otherwise,
8314 // it is converted to an unsigned int.
8315 //
8316 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8317 // We perform that promotion here to match GCC and C++.
8318 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8319 // greater than that of 'int'. We perform that promotion to match GCC.
8320 //
8321 // C23 6.3.1.1p2:
8322 // The value from a bit-field of a bit-precise integer type is converted to
8323 // the corresponding bit-precise integer type. (The rest is the same as in
8324 // C11.)
8325 if (QualType QT = Field->getType(); QT->isBitIntType())
8326 return QT;
8327
8328 if (BitWidth < IntSize)
8329 return IntTy;
8330
8331 if (BitWidth == IntSize)
8332 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8333
8334 // Bit-fields wider than int are not subject to promotions, and therefore act
8335 // like the base type. GCC has some weird bugs in this area that we
8336 // deliberately do not follow (GCC follows a pre-standard resolution to
8337 // C's DR315 which treats bit-width as being part of the type, and this leaks
8338 // into their semantics in some cases).
8339 return {};
8340}
8341
8342/// getPromotedIntegerType - Returns the type that Promotable will
8343/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8344/// integer type.
8346 assert(!Promotable.isNull());
8347 assert(isPromotableIntegerType(Promotable));
8348 if (const auto *ED = Promotable->getAsEnumDecl())
8349 return ED->getPromotionType();
8350
8351 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8352 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8353 // (3.9.1) can be converted to a prvalue of the first of the following
8354 // types that can represent all the values of its underlying type:
8355 // int, unsigned int, long int, unsigned long int, long long int, or
8356 // unsigned long long int [...]
8357 // FIXME: Is there some better way to compute this?
8358 if (BT->getKind() == BuiltinType::WChar_S ||
8359 BT->getKind() == BuiltinType::WChar_U ||
8360 BT->getKind() == BuiltinType::Char8 ||
8361 BT->getKind() == BuiltinType::Char16 ||
8362 BT->getKind() == BuiltinType::Char32) {
8363 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8364 uint64_t FromSize = getTypeSize(BT);
8365 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8367 for (const auto &PT : PromoteTypes) {
8368 uint64_t ToSize = getTypeSize(PT);
8369 if (FromSize < ToSize ||
8370 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8371 return PT;
8372 }
8373 llvm_unreachable("char type should fit into long long");
8374 }
8375 }
8376
8377 // At this point, we should have a signed or unsigned integer type.
8378 if (Promotable->isSignedIntegerType())
8379 return IntTy;
8380 uint64_t PromotableSize = getIntWidth(Promotable);
8381 uint64_t IntSize = getIntWidth(IntTy);
8382 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8383 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8384}
8385
8386/// Recurses in pointer/array types until it finds an objc retainable
8387/// type and returns its ownership.
8389 while (!T.isNull()) {
8390 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8391 return T.getObjCLifetime();
8392 if (T->isArrayType())
8394 else if (const auto *PT = T->getAs<PointerType>())
8395 T = PT->getPointeeType();
8396 else if (const auto *RT = T->getAs<ReferenceType>())
8397 T = RT->getPointeeType();
8398 else
8399 break;
8400 }
8401
8402 return Qualifiers::OCL_None;
8403}
8404
8405static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8406 // Incomplete enum types are not treated as integer types.
8407 // FIXME: In C++, enum types are never integer types.
8408 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8409 if (ED->isComplete() && !ED->isScoped())
8410 return ED->getIntegerType().getTypePtr();
8411 return nullptr;
8412}
8413
8414/// getIntegerTypeOrder - Returns the highest ranked integer type:
8415/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8416/// LHS < RHS, return -1.
8418 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8419 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8420
8421 // Unwrap enums to their underlying type.
8422 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8423 LHSC = getIntegerTypeForEnum(ET);
8424 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8425 RHSC = getIntegerTypeForEnum(ET);
8426
8427 if (LHSC == RHSC) return 0;
8428
8429 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8430 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8431
8432 unsigned LHSRank = getIntegerRank(LHSC);
8433 unsigned RHSRank = getIntegerRank(RHSC);
8434
8435 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8436 if (LHSRank == RHSRank) return 0;
8437 return LHSRank > RHSRank ? 1 : -1;
8438 }
8439
8440 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8441 if (LHSUnsigned) {
8442 // If the unsigned [LHS] type is larger, return it.
8443 if (LHSRank >= RHSRank)
8444 return 1;
8445
8446 // If the signed type can represent all values of the unsigned type, it
8447 // wins. Because we are dealing with 2's complement and types that are
8448 // powers of two larger than each other, this is always safe.
8449 return -1;
8450 }
8451
8452 // If the unsigned [RHS] type is larger, return it.
8453 if (RHSRank >= LHSRank)
8454 return -1;
8455
8456 // If the signed type can represent all values of the unsigned type, it
8457 // wins. Because we are dealing with 2's complement and types that are
8458 // powers of two larger than each other, this is always safe.
8459 return 1;
8460}
8461
8463 if (CFConstantStringTypeDecl)
8464 return CFConstantStringTypeDecl;
8465
8466 assert(!CFConstantStringTagDecl &&
8467 "tag and typedef should be initialized together");
8468 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8469 CFConstantStringTagDecl->startDefinition();
8470
8471 struct {
8472 QualType Type;
8473 const char *Name;
8474 } Fields[5];
8475 unsigned Count = 0;
8476
8477 /// Objective-C ABI
8478 ///
8479 /// typedef struct __NSConstantString_tag {
8480 /// const int *isa;
8481 /// int flags;
8482 /// const char *str;
8483 /// long length;
8484 /// } __NSConstantString;
8485 ///
8486 /// Swift ABI (4.1, 4.2)
8487 ///
8488 /// typedef struct __NSConstantString_tag {
8489 /// uintptr_t _cfisa;
8490 /// uintptr_t _swift_rc;
8491 /// _Atomic(uint64_t) _cfinfoa;
8492 /// const char *_ptr;
8493 /// uint32_t _length;
8494 /// } __NSConstantString;
8495 ///
8496 /// Swift ABI (5.0)
8497 ///
8498 /// typedef struct __NSConstantString_tag {
8499 /// uintptr_t _cfisa;
8500 /// uintptr_t _swift_rc;
8501 /// _Atomic(uint64_t) _cfinfoa;
8502 /// const char *_ptr;
8503 /// uintptr_t _length;
8504 /// } __NSConstantString;
8505
8506 const auto CFRuntime = getLangOpts().CFRuntime;
8507 if (static_cast<unsigned>(CFRuntime) <
8508 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8509 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8510 Fields[Count++] = { IntTy, "flags" };
8511 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8512 Fields[Count++] = { LongTy, "length" };
8513 } else {
8514 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8515 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8516 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8517 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8520 Fields[Count++] = { IntTy, "_ptr" };
8521 else
8522 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8523 }
8524
8525 // Create fields
8526 for (unsigned i = 0; i < Count; ++i) {
8527 FieldDecl *Field =
8528 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8529 SourceLocation(), &Idents.get(Fields[i].Name),
8530 Fields[i].Type, /*TInfo=*/nullptr,
8531 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8532 Field->setAccess(AS_public);
8533 CFConstantStringTagDecl->addDecl(Field);
8534 }
8535
8536 CFConstantStringTagDecl->completeDefinition();
8537 // This type is designed to be compatible with NSConstantString, but cannot
8538 // use the same name, since NSConstantString is an interface.
8539 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8540 CFConstantStringTypeDecl =
8541 buildImplicitTypedef(tagType, "__NSConstantString");
8542
8543 return CFConstantStringTypeDecl;
8544}
8545
8547 if (!CFConstantStringTagDecl)
8548 getCFConstantStringDecl(); // Build the tag and the typedef.
8549 return CFConstantStringTagDecl;
8550}
8551
8552// getCFConstantStringType - Return the type used for constant CFStrings.
8557
8559 if (ObjCSuperType.isNull()) {
8560 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8561 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8562 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8563 }
8564 return ObjCSuperType;
8565}
8566
8568 const auto *TT = T->castAs<TypedefType>();
8569 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8570 CFConstantStringTagDecl = TT->castAsRecordDecl();
8571}
8572
8574 if (BlockDescriptorType)
8575 return getCanonicalTagType(BlockDescriptorType);
8576
8577 RecordDecl *RD;
8578 // FIXME: Needs the FlagAppleBlock bit.
8579 RD = buildImplicitRecord("__block_descriptor");
8580 RD->startDefinition();
8581
8582 QualType FieldTypes[] = {
8585 };
8586
8587 static const char *const FieldNames[] = {
8588 "reserved",
8589 "Size"
8590 };
8591
8592 for (size_t i = 0; i < 2; ++i) {
8594 *this, RD, SourceLocation(), SourceLocation(),
8595 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8596 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8597 Field->setAccess(AS_public);
8598 RD->addDecl(Field);
8599 }
8600
8601 RD->completeDefinition();
8602
8603 BlockDescriptorType = RD;
8604
8605 return getCanonicalTagType(BlockDescriptorType);
8606}
8607
8609 if (BlockDescriptorExtendedType)
8610 return getCanonicalTagType(BlockDescriptorExtendedType);
8611
8612 RecordDecl *RD;
8613 // FIXME: Needs the FlagAppleBlock bit.
8614 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8615 RD->startDefinition();
8616
8617 QualType FieldTypes[] = {
8622 };
8623
8624 static const char *const FieldNames[] = {
8625 "reserved",
8626 "Size",
8627 "CopyFuncPtr",
8628 "DestroyFuncPtr"
8629 };
8630
8631 for (size_t i = 0; i < 4; ++i) {
8633 *this, RD, SourceLocation(), SourceLocation(),
8634 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8635 /*BitWidth=*/nullptr,
8636 /*Mutable=*/false, ICIS_NoInit);
8637 Field->setAccess(AS_public);
8638 RD->addDecl(Field);
8639 }
8640
8641 RD->completeDefinition();
8642
8643 BlockDescriptorExtendedType = RD;
8644 return getCanonicalTagType(BlockDescriptorExtendedType);
8645}
8646
8648 const auto *BT = dyn_cast<BuiltinType>(T);
8649
8650 if (!BT) {
8651 if (isa<PipeType>(T))
8652 return OCLTK_Pipe;
8653
8654 return OCLTK_Default;
8655 }
8656
8657 switch (BT->getKind()) {
8658#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8659 case BuiltinType::Id: \
8660 return OCLTK_Image;
8661#include "clang/Basic/OpenCLImageTypes.def"
8662
8663 case BuiltinType::OCLClkEvent:
8664 return OCLTK_ClkEvent;
8665
8666 case BuiltinType::OCLEvent:
8667 return OCLTK_Event;
8668
8669 case BuiltinType::OCLQueue:
8670 return OCLTK_Queue;
8671
8672 case BuiltinType::OCLReserveID:
8673 return OCLTK_ReserveID;
8674
8675 case BuiltinType::OCLSampler:
8676 return OCLTK_Sampler;
8677
8678 default:
8679 return OCLTK_Default;
8680 }
8681}
8682
8684 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8685}
8686
8687/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8688/// requires copy/dispose. Note that this must match the logic
8689/// in buildByrefHelpers.
8691 const VarDecl *D) {
8692 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8693 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8694 if (!copyExpr && record->hasTrivialDestructor()) return false;
8695
8696 return true;
8697 }
8698
8700 return true;
8701
8702 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8703 // move or destroy.
8705 return true;
8706
8707 if (!Ty->isObjCRetainableType()) return false;
8708
8709 Qualifiers qs = Ty.getQualifiers();
8710
8711 // If we have lifetime, that dominates.
8712 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8713 switch (lifetime) {
8714 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8715
8716 // These are just bits as far as the runtime is concerned.
8719 return false;
8720
8721 // These cases should have been taken care of when checking the type's
8722 // non-triviality.
8725 llvm_unreachable("impossible");
8726 }
8727 llvm_unreachable("fell out of lifetime switch!");
8728 }
8729 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8731}
8732
8734 Qualifiers::ObjCLifetime &LifeTime,
8735 bool &HasByrefExtendedLayout) const {
8736 if (!getLangOpts().ObjC ||
8737 getLangOpts().getGC() != LangOptions::NonGC)
8738 return false;
8739
8740 HasByrefExtendedLayout = false;
8741 if (Ty->isRecordType()) {
8742 HasByrefExtendedLayout = true;
8743 LifeTime = Qualifiers::OCL_None;
8744 } else if ((LifeTime = Ty.getObjCLifetime())) {
8745 // Honor the ARC qualifiers.
8746 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8747 // The MRR rule.
8749 } else {
8750 LifeTime = Qualifiers::OCL_None;
8751 }
8752 return true;
8753}
8754
8756 assert(Target && "Expected target to be initialized");
8757 const llvm::Triple &T = Target->getTriple();
8758 // Windows is LLP64 rather than LP64
8759 if (T.isOSWindows() && T.isArch64Bit())
8760 return UnsignedLongLongTy;
8761 return UnsignedLongTy;
8762}
8763
8765 assert(Target && "Expected target to be initialized");
8766 const llvm::Triple &T = Target->getTriple();
8767 // Windows is LLP64 rather than LP64
8768 if (T.isOSWindows() && T.isArch64Bit())
8769 return LongLongTy;
8770 return LongTy;
8771}
8772
8774 if (!ObjCInstanceTypeDecl)
8775 ObjCInstanceTypeDecl =
8776 buildImplicitTypedef(getObjCIdType(), "instancetype");
8777 return ObjCInstanceTypeDecl;
8778}
8779
8780// This returns true if a type has been typedefed to BOOL:
8781// typedef <type> BOOL;
8783 if (const auto *TT = dyn_cast<TypedefType>(T))
8784 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8785 return II->isStr("BOOL");
8786
8787 return false;
8788}
8789
8790/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8791/// purpose.
8793 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8794 return CharUnits::Zero();
8795
8797
8798 // Make all integer and enum types at least as large as an int
8799 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8800 sz = std::max(sz, getTypeSizeInChars(IntTy));
8801 // Treat arrays as pointers, since that's how they're passed in.
8802 else if (type->isArrayType())
8804 return sz;
8805}
8806
8813
8816 if (!VD->isInline())
8818
8819 // In almost all cases, it's a weak definition.
8820 auto *First = VD->getFirstDecl();
8821 if (First->isInlineSpecified() || !First->isStaticDataMember())
8823
8824 // If there's a file-context declaration in this translation unit, it's a
8825 // non-discardable definition.
8826 for (auto *D : VD->redecls())
8828 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8830
8831 // If we've not seen one yet, we don't know.
8833}
8834
8835static std::string charUnitsToString(const CharUnits &CU) {
8836 return llvm::itostr(CU.getQuantity());
8837}
8838
8839/// getObjCEncodingForBlock - Return the encoded type for this block
8840/// declaration.
8842 std::string S;
8843
8844 const BlockDecl *Decl = Expr->getBlockDecl();
8845 QualType BlockTy =
8847 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8848 // Encode result type.
8849 if (getLangOpts().EncodeExtendedBlockSig)
8851 true /*Extended*/);
8852 else
8853 getObjCEncodingForType(BlockReturnTy, S);
8854 // Compute size of all parameters.
8855 // Start with computing size of a pointer in number of bytes.
8856 // FIXME: There might(should) be a better way of doing this computation!
8858 CharUnits ParmOffset = PtrSize;
8859 for (auto *PI : Decl->parameters()) {
8860 QualType PType = PI->getType();
8862 if (sz.isZero())
8863 continue;
8864 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8865 ParmOffset += sz;
8866 }
8867 // Size of the argument frame
8868 S += charUnitsToString(ParmOffset);
8869 // Block pointer and offset.
8870 S += "@?0";
8871
8872 // Argument types.
8873 ParmOffset = PtrSize;
8874 for (auto *PVDecl : Decl->parameters()) {
8875 QualType PType = PVDecl->getOriginalType();
8876 if (const auto *AT =
8877 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8878 // Use array's original type only if it has known number of
8879 // elements.
8880 if (!isa<ConstantArrayType>(AT))
8881 PType = PVDecl->getType();
8882 } else if (PType->isFunctionType())
8883 PType = PVDecl->getType();
8884 if (getLangOpts().EncodeExtendedBlockSig)
8886 S, true /*Extended*/);
8887 else
8888 getObjCEncodingForType(PType, S);
8889 S += charUnitsToString(ParmOffset);
8890 ParmOffset += getObjCEncodingTypeSize(PType);
8891 }
8892
8893 return S;
8894}
8895
8896std::string
8898 std::string S;
8899 // Encode result type.
8900 getObjCEncodingForType(Decl->getReturnType(), S);
8901 CharUnits ParmOffset;
8902 // Compute size of all parameters.
8903 for (auto *PI : Decl->parameters()) {
8904 QualType PType = PI->getType();
8906 if (sz.isZero())
8907 continue;
8908
8909 assert(sz.isPositive() &&
8910 "getObjCEncodingForFunctionDecl - Incomplete param type");
8911 ParmOffset += sz;
8912 }
8913 S += charUnitsToString(ParmOffset);
8914 ParmOffset = CharUnits::Zero();
8915
8916 // Argument types.
8917 for (auto *PVDecl : Decl->parameters()) {
8918 QualType PType = PVDecl->getOriginalType();
8919 if (const auto *AT =
8920 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8921 // Use array's original type only if it has known number of
8922 // elements.
8923 if (!isa<ConstantArrayType>(AT))
8924 PType = PVDecl->getType();
8925 } else if (PType->isFunctionType())
8926 PType = PVDecl->getType();
8927 getObjCEncodingForType(PType, S);
8928 S += charUnitsToString(ParmOffset);
8929 ParmOffset += getObjCEncodingTypeSize(PType);
8930 }
8931
8932 return S;
8933}
8934
8935/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8936/// method parameter or return type. If Extended, include class names and
8937/// block object types.
8939 QualType T, std::string& S,
8940 bool Extended) const {
8941 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8943 // Encode parameter type.
8944 ObjCEncOptions Options = ObjCEncOptions()
8945 .setExpandPointedToStructures()
8946 .setExpandStructures()
8947 .setIsOutermostType();
8948 if (Extended)
8949 Options.setEncodeBlockParameters().setEncodeClassNames();
8950 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8951}
8952
8953/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8954/// declaration.
8956 bool Extended) const {
8957 // FIXME: This is not very efficient.
8958 // Encode return type.
8959 std::string S;
8960 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8961 Decl->getReturnType(), S, Extended);
8962 // Compute size of all parameters.
8963 // Start with computing size of a pointer in number of bytes.
8964 // FIXME: There might(should) be a better way of doing this computation!
8966 // The first two arguments (self and _cmd) are pointers; account for
8967 // their size.
8968 CharUnits ParmOffset = 2 * PtrSize;
8969 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8970 E = Decl->sel_param_end(); PI != E; ++PI) {
8971 QualType PType = (*PI)->getType();
8973 if (sz.isZero())
8974 continue;
8975
8976 assert(sz.isPositive() &&
8977 "getObjCEncodingForMethodDecl - Incomplete param type");
8978 ParmOffset += sz;
8979 }
8980 S += charUnitsToString(ParmOffset);
8981 S += "@0:";
8982 S += charUnitsToString(PtrSize);
8983
8984 // Argument types.
8985 ParmOffset = 2 * PtrSize;
8986 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8987 E = Decl->sel_param_end(); PI != E; ++PI) {
8988 const ParmVarDecl *PVDecl = *PI;
8989 QualType PType = PVDecl->getOriginalType();
8990 if (const auto *AT =
8991 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8992 // Use array's original type only if it has known number of
8993 // elements.
8994 if (!isa<ConstantArrayType>(AT))
8995 PType = PVDecl->getType();
8996 } else if (PType->isFunctionType())
8997 PType = PVDecl->getType();
8999 PType, S, Extended);
9000 S += charUnitsToString(ParmOffset);
9001 ParmOffset += getObjCEncodingTypeSize(PType);
9002 }
9003
9004 return S;
9005}
9006
9009 const ObjCPropertyDecl *PD,
9010 const Decl *Container) const {
9011 if (!Container)
9012 return nullptr;
9013 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9014 for (auto *PID : CID->property_impls())
9015 if (PID->getPropertyDecl() == PD)
9016 return PID;
9017 } else {
9018 const auto *OID = cast<ObjCImplementationDecl>(Container);
9019 for (auto *PID : OID->property_impls())
9020 if (PID->getPropertyDecl() == PD)
9021 return PID;
9022 }
9023 return nullptr;
9024}
9025
9026/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9027/// property declaration. If non-NULL, Container must be either an
9028/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9029/// NULL when getting encodings for protocol properties.
9030/// Property attributes are stored as a comma-delimited C string. The simple
9031/// attributes readonly and bycopy are encoded as single characters. The
9032/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9033/// encoded as single characters, followed by an identifier. Property types
9034/// are also encoded as a parametrized attribute. The characters used to encode
9035/// these attributes are defined by the following enumeration:
9036/// @code
9037/// enum PropertyAttributes {
9038/// kPropertyReadOnly = 'R', // property is read-only.
9039/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9040/// kPropertyByref = '&', // property is a reference to the value last assigned
9041/// kPropertyDynamic = 'D', // property is dynamic
9042/// kPropertyGetter = 'G', // followed by getter selector name
9043/// kPropertySetter = 'S', // followed by setter selector name
9044/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9045/// kPropertyType = 'T' // followed by old-style type encoding.
9046/// kPropertyWeak = 'W' // 'weak' property
9047/// kPropertyStrong = 'P' // property GC'able
9048/// kPropertyNonAtomic = 'N' // property non-atomic
9049/// kPropertyOptional = '?' // property optional
9050/// };
9051/// @endcode
9052std::string
9054 const Decl *Container) const {
9055 // Collect information from the property implementation decl(s).
9056 bool Dynamic = false;
9057 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9058
9059 if (ObjCPropertyImplDecl *PropertyImpDecl =
9061 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9062 Dynamic = true;
9063 else
9064 SynthesizePID = PropertyImpDecl;
9065 }
9066
9067 // FIXME: This is not very efficient.
9068 std::string S = "T";
9069
9070 // Encode result type.
9071 // GCC has some special rules regarding encoding of properties which
9072 // closely resembles encoding of ivars.
9074
9075 if (PD->isOptional())
9076 S += ",?";
9077
9078 if (PD->isReadOnly()) {
9079 S += ",R";
9081 S += ",C";
9083 S += ",&";
9085 S += ",W";
9086 } else {
9087 switch (PD->getSetterKind()) {
9088 case ObjCPropertyDecl::Assign: break;
9089 case ObjCPropertyDecl::Copy: S += ",C"; break;
9090 case ObjCPropertyDecl::Retain: S += ",&"; break;
9091 case ObjCPropertyDecl::Weak: S += ",W"; break;
9092 }
9093 }
9094
9095 // It really isn't clear at all what this means, since properties
9096 // are "dynamic by default".
9097 if (Dynamic)
9098 S += ",D";
9099
9101 S += ",N";
9102
9104 S += ",G";
9105 S += PD->getGetterName().getAsString();
9106 }
9107
9109 S += ",S";
9110 S += PD->getSetterName().getAsString();
9111 }
9112
9113 if (SynthesizePID) {
9114 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9115 S += ",V";
9116 S += OID->getNameAsString();
9117 }
9118
9119 // FIXME: OBJCGC: weak & strong
9120 return S;
9121}
9122
9123/// getLegacyIntegralTypeEncoding -
9124/// Another legacy compatibility encoding: 32-bit longs are encoded as
9125/// 'l' or 'L' , but not always. For typedefs, we need to use
9126/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9128 if (PointeeTy->getAs<TypedefType>()) {
9129 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9130 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9131 PointeeTy = UnsignedIntTy;
9132 else
9133 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9134 PointeeTy = IntTy;
9135 }
9136 }
9137}
9138
9140 const FieldDecl *Field,
9141 QualType *NotEncodedT) const {
9142 // We follow the behavior of gcc, expanding structures which are
9143 // directly pointed to, and expanding embedded structures. Note that
9144 // these rules are sufficient to prevent recursive encoding of the
9145 // same type.
9146 getObjCEncodingForTypeImpl(T, S,
9147 ObjCEncOptions()
9148 .setExpandPointedToStructures()
9149 .setExpandStructures()
9150 .setIsOutermostType(),
9151 Field, NotEncodedT);
9152}
9153
9155 std::string& S) const {
9156 // Encode result type.
9157 // GCC has some special rules regarding encoding of properties which
9158 // closely resembles encoding of ivars.
9159 getObjCEncodingForTypeImpl(T, S,
9160 ObjCEncOptions()
9161 .setExpandPointedToStructures()
9162 .setExpandStructures()
9163 .setIsOutermostType()
9164 .setEncodingProperty(),
9165 /*Field=*/nullptr);
9166}
9167
9169 const BuiltinType *BT) {
9170 BuiltinType::Kind kind = BT->getKind();
9171 switch (kind) {
9172 case BuiltinType::Void: return 'v';
9173 case BuiltinType::Bool: return 'B';
9174 case BuiltinType::Char8:
9175 case BuiltinType::Char_U:
9176 case BuiltinType::UChar: return 'C';
9177 case BuiltinType::Char16:
9178 case BuiltinType::UShort: return 'S';
9179 case BuiltinType::Char32:
9180 case BuiltinType::UInt: return 'I';
9181 case BuiltinType::ULong:
9182 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9183 case BuiltinType::UInt128: return 'T';
9184 case BuiltinType::ULongLong: return 'Q';
9185 case BuiltinType::Char_S:
9186 case BuiltinType::SChar: return 'c';
9187 case BuiltinType::Short: return 's';
9188 case BuiltinType::WChar_S:
9189 case BuiltinType::WChar_U:
9190 case BuiltinType::Int: return 'i';
9191 case BuiltinType::Long:
9192 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9193 case BuiltinType::LongLong: return 'q';
9194 case BuiltinType::Int128: return 't';
9195 case BuiltinType::Float: return 'f';
9196 case BuiltinType::Double: return 'd';
9197 case BuiltinType::LongDouble: return 'D';
9198 case BuiltinType::NullPtr: return '*'; // like char*
9199
9200 case BuiltinType::BFloat16:
9201 case BuiltinType::Float16:
9202 case BuiltinType::Float128:
9203 case BuiltinType::Ibm128:
9204 case BuiltinType::Half:
9205 case BuiltinType::ShortAccum:
9206 case BuiltinType::Accum:
9207 case BuiltinType::LongAccum:
9208 case BuiltinType::UShortAccum:
9209 case BuiltinType::UAccum:
9210 case BuiltinType::ULongAccum:
9211 case BuiltinType::ShortFract:
9212 case BuiltinType::Fract:
9213 case BuiltinType::LongFract:
9214 case BuiltinType::UShortFract:
9215 case BuiltinType::UFract:
9216 case BuiltinType::ULongFract:
9217 case BuiltinType::SatShortAccum:
9218 case BuiltinType::SatAccum:
9219 case BuiltinType::SatLongAccum:
9220 case BuiltinType::SatUShortAccum:
9221 case BuiltinType::SatUAccum:
9222 case BuiltinType::SatULongAccum:
9223 case BuiltinType::SatShortFract:
9224 case BuiltinType::SatFract:
9225 case BuiltinType::SatLongFract:
9226 case BuiltinType::SatUShortFract:
9227 case BuiltinType::SatUFract:
9228 case BuiltinType::SatULongFract:
9229 // FIXME: potentially need @encodes for these!
9230 return ' ';
9231
9232#define SVE_TYPE(Name, Id, SingletonId) \
9233 case BuiltinType::Id:
9234#include "clang/Basic/AArch64ACLETypes.def"
9235#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9236#include "clang/Basic/RISCVVTypes.def"
9237#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9238#include "clang/Basic/WebAssemblyReferenceTypes.def"
9239#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9240#include "clang/Basic/AMDGPUTypes.def"
9241 {
9242 DiagnosticsEngine &Diags = C->getDiagnostics();
9243 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9244 "cannot yet @encode type %0");
9245 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9246 return ' ';
9247 }
9248
9249 case BuiltinType::ObjCId:
9250 case BuiltinType::ObjCClass:
9251 case BuiltinType::ObjCSel:
9252 llvm_unreachable("@encoding ObjC primitive type");
9253
9254 // OpenCL and placeholder types don't need @encodings.
9255#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9256 case BuiltinType::Id:
9257#include "clang/Basic/OpenCLImageTypes.def"
9258#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9259 case BuiltinType::Id:
9260#include "clang/Basic/OpenCLExtensionTypes.def"
9261 case BuiltinType::OCLEvent:
9262 case BuiltinType::OCLClkEvent:
9263 case BuiltinType::OCLQueue:
9264 case BuiltinType::OCLReserveID:
9265 case BuiltinType::OCLSampler:
9266 case BuiltinType::Dependent:
9267#define PPC_VECTOR_TYPE(Name, Id, Size) \
9268 case BuiltinType::Id:
9269#include "clang/Basic/PPCTypes.def"
9270#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9271#include "clang/Basic/HLSLIntangibleTypes.def"
9272#define BUILTIN_TYPE(KIND, ID)
9273#define PLACEHOLDER_TYPE(KIND, ID) \
9274 case BuiltinType::KIND:
9275#include "clang/AST/BuiltinTypes.def"
9276 llvm_unreachable("invalid builtin type for @encode");
9277 }
9278 llvm_unreachable("invalid BuiltinType::Kind value");
9279}
9280
9281static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9283
9284 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9285 if (!Enum->isFixed())
9286 return 'i';
9287
9288 // The encoding of a fixed enum type matches its fixed underlying type.
9289 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9291}
9292
9293static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9294 QualType T, const FieldDecl *FD) {
9295 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9296 S += 'b';
9297 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9298 // The GNU runtime requires more information; bitfields are encoded as b,
9299 // then the offset (in bits) of the first element, then the type of the
9300 // bitfield, then the size in bits. For example, in this structure:
9301 //
9302 // struct
9303 // {
9304 // int integer;
9305 // int flags:2;
9306 // };
9307 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9308 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9309 // information is not especially sensible, but we're stuck with it for
9310 // compatibility with GCC, although providing it breaks anything that
9311 // actually uses runtime introspection and wants to work on both runtimes...
9312 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9313 uint64_t Offset;
9314
9315 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9316 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9317 } else {
9318 const RecordDecl *RD = FD->getParent();
9319 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9320 Offset = RL.getFieldOffset(FD->getFieldIndex());
9321 }
9322
9323 S += llvm::utostr(Offset);
9324
9325 if (const auto *ET = T->getAsCanonical<EnumType>())
9326 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9327 else {
9328 const auto *BT = T->castAs<BuiltinType>();
9329 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9330 }
9331 }
9332 S += llvm::utostr(FD->getBitWidthValue());
9333}
9334
9335// Helper function for determining whether the encoded type string would include
9336// a template specialization type.
9338 bool VisitBasesAndFields) {
9339 T = T->getBaseElementTypeUnsafe();
9340
9341 if (auto *PT = T->getAs<PointerType>())
9343 PT->getPointeeType().getTypePtr(), false);
9344
9345 auto *CXXRD = T->getAsCXXRecordDecl();
9346
9347 if (!CXXRD)
9348 return false;
9349
9351 return true;
9352
9353 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9354 return false;
9355
9356 for (const auto &B : CXXRD->bases())
9357 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9358 true))
9359 return true;
9360
9361 for (auto *FD : CXXRD->fields())
9362 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9363 true))
9364 return true;
9365
9366 return false;
9367}
9368
9369// FIXME: Use SmallString for accumulating string.
9370void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9371 const ObjCEncOptions Options,
9372 const FieldDecl *FD,
9373 QualType *NotEncodedT) const {
9375 switch (CT->getTypeClass()) {
9376 case Type::Builtin:
9377 case Type::Enum:
9378 if (FD && FD->isBitField())
9379 return EncodeBitField(this, S, T, FD);
9380 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9381 S += getObjCEncodingForPrimitiveType(this, BT);
9382 else
9383 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9384 return;
9385
9386 case Type::Complex:
9387 S += 'j';
9388 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9389 ObjCEncOptions(),
9390 /*Field=*/nullptr);
9391 return;
9392
9393 case Type::Atomic:
9394 S += 'A';
9395 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9396 ObjCEncOptions(),
9397 /*Field=*/nullptr);
9398 return;
9399
9400 // encoding for pointer or reference types.
9401 case Type::Pointer:
9402 case Type::LValueReference:
9403 case Type::RValueReference: {
9404 QualType PointeeTy;
9405 if (isa<PointerType>(CT)) {
9406 const auto *PT = T->castAs<PointerType>();
9407 if (PT->isObjCSelType()) {
9408 S += ':';
9409 return;
9410 }
9411 PointeeTy = PT->getPointeeType();
9412 } else {
9413 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9414 }
9415
9416 bool isReadOnly = false;
9417 // For historical/compatibility reasons, the read-only qualifier of the
9418 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9419 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9420 // Also, do not emit the 'r' for anything but the outermost type!
9421 if (T->getAs<TypedefType>()) {
9422 if (Options.IsOutermostType() && T.isConstQualified()) {
9423 isReadOnly = true;
9424 S += 'r';
9425 }
9426 } else if (Options.IsOutermostType()) {
9427 QualType P = PointeeTy;
9428 while (auto PT = P->getAs<PointerType>())
9429 P = PT->getPointeeType();
9430 if (P.isConstQualified()) {
9431 isReadOnly = true;
9432 S += 'r';
9433 }
9434 }
9435 if (isReadOnly) {
9436 // Another legacy compatibility encoding. Some ObjC qualifier and type
9437 // combinations need to be rearranged.
9438 // Rewrite "in const" from "nr" to "rn"
9439 if (StringRef(S).ends_with("nr"))
9440 S.replace(S.end()-2, S.end(), "rn");
9441 }
9442
9443 if (PointeeTy->isCharType()) {
9444 // char pointer types should be encoded as '*' unless it is a
9445 // type that has been typedef'd to 'BOOL'.
9446 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9447 S += '*';
9448 return;
9449 }
9450 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9451 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9452 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9453 if (II == &Idents.get("objc_class")) {
9454 S += '#';
9455 return;
9456 }
9457 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9458 if (II == &Idents.get("objc_object")) {
9459 S += '@';
9460 return;
9461 }
9462 // If the encoded string for the class includes template names, just emit
9463 // "^v" for pointers to the class.
9464 if (getLangOpts().CPlusPlus &&
9465 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9467 RTy, Options.ExpandPointedToStructures()))) {
9468 S += "^v";
9469 return;
9470 }
9471 // fall through...
9472 }
9473 S += '^';
9475
9476 ObjCEncOptions NewOptions;
9477 if (Options.ExpandPointedToStructures())
9478 NewOptions.setExpandStructures();
9479 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9480 /*Field=*/nullptr, NotEncodedT);
9481 return;
9482 }
9483
9484 case Type::ConstantArray:
9485 case Type::IncompleteArray:
9486 case Type::VariableArray: {
9487 const auto *AT = cast<ArrayType>(CT);
9488
9489 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9490 // Incomplete arrays are encoded as a pointer to the array element.
9491 S += '^';
9492
9493 getObjCEncodingForTypeImpl(
9494 AT->getElementType(), S,
9495 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9496 } else {
9497 S += '[';
9498
9499 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9500 S += llvm::utostr(CAT->getZExtSize());
9501 else {
9502 //Variable length arrays are encoded as a regular array with 0 elements.
9504 "Unknown array type!");
9505 S += '0';
9506 }
9507
9508 getObjCEncodingForTypeImpl(
9509 AT->getElementType(), S,
9510 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9511 NotEncodedT);
9512 S += ']';
9513 }
9514 return;
9515 }
9516
9517 case Type::FunctionNoProto:
9518 case Type::FunctionProto:
9519 S += '?';
9520 return;
9521
9522 case Type::Record: {
9523 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9524 S += RDecl->isUnion() ? '(' : '{';
9525 // Anonymous structures print as '?'
9526 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9527 S += II->getName();
9528 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9529 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9530 llvm::raw_string_ostream OS(S);
9531 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9533 }
9534 } else {
9535 S += '?';
9536 }
9537 if (Options.ExpandStructures()) {
9538 S += '=';
9539 if (!RDecl->isUnion()) {
9540 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9541 } else {
9542 for (const auto *Field : RDecl->fields()) {
9543 if (FD) {
9544 S += '"';
9545 S += Field->getNameAsString();
9546 S += '"';
9547 }
9548
9549 // Special case bit-fields.
9550 if (Field->isBitField()) {
9551 getObjCEncodingForTypeImpl(Field->getType(), S,
9552 ObjCEncOptions().setExpandStructures(),
9553 Field);
9554 } else {
9555 QualType qt = Field->getType();
9557 getObjCEncodingForTypeImpl(
9558 qt, S,
9559 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9560 NotEncodedT);
9561 }
9562 }
9563 }
9564 }
9565 S += RDecl->isUnion() ? ')' : '}';
9566 return;
9567 }
9568
9569 case Type::BlockPointer: {
9570 const auto *BT = T->castAs<BlockPointerType>();
9571 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9572 if (Options.EncodeBlockParameters()) {
9573 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9574
9575 S += '<';
9576 // Block return type
9577 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9578 Options.forComponentType(), FD, NotEncodedT);
9579 // Block self
9580 S += "@?";
9581 // Block parameters
9582 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9583 for (const auto &I : FPT->param_types())
9584 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9585 NotEncodedT);
9586 }
9587 S += '>';
9588 }
9589 return;
9590 }
9591
9592 case Type::ObjCObject: {
9593 // hack to match legacy encoding of *id and *Class
9594 QualType Ty = getObjCObjectPointerType(CT);
9595 if (Ty->isObjCIdType()) {
9596 S += "{objc_object=}";
9597 return;
9598 }
9599 else if (Ty->isObjCClassType()) {
9600 S += "{objc_class=}";
9601 return;
9602 }
9603 // TODO: Double check to make sure this intentionally falls through.
9604 [[fallthrough]];
9605 }
9606
9607 case Type::ObjCInterface: {
9608 // Ignore protocol qualifiers when mangling at this level.
9609 // @encode(class_name)
9610 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9611 S += '{';
9612 S += OI->getObjCRuntimeNameAsString();
9613 if (Options.ExpandStructures()) {
9614 S += '=';
9615 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9616 DeepCollectObjCIvars(OI, true, Ivars);
9617 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9618 const FieldDecl *Field = Ivars[i];
9619 if (Field->isBitField())
9620 getObjCEncodingForTypeImpl(Field->getType(), S,
9621 ObjCEncOptions().setExpandStructures(),
9622 Field);
9623 else
9624 getObjCEncodingForTypeImpl(Field->getType(), S,
9625 ObjCEncOptions().setExpandStructures(), FD,
9626 NotEncodedT);
9627 }
9628 }
9629 S += '}';
9630 return;
9631 }
9632
9633 case Type::ObjCObjectPointer: {
9634 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9635 if (OPT->isObjCIdType()) {
9636 S += '@';
9637 return;
9638 }
9639
9640 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9641 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9642 // Since this is a binary compatibility issue, need to consult with
9643 // runtime folks. Fortunately, this is a *very* obscure construct.
9644 S += '#';
9645 return;
9646 }
9647
9648 if (OPT->isObjCQualifiedIdType()) {
9649 getObjCEncodingForTypeImpl(
9650 getObjCIdType(), S,
9651 Options.keepingOnly(ObjCEncOptions()
9652 .setExpandPointedToStructures()
9653 .setExpandStructures()),
9654 FD);
9655 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9656 // Note that we do extended encoding of protocol qualifier list
9657 // Only when doing ivar or property encoding.
9658 S += '"';
9659 for (const auto *I : OPT->quals()) {
9660 S += '<';
9661 S += I->getObjCRuntimeNameAsString();
9662 S += '>';
9663 }
9664 S += '"';
9665 }
9666 return;
9667 }
9668
9669 S += '@';
9670 if (OPT->getInterfaceDecl() &&
9671 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9672 S += '"';
9673 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9674 for (const auto *I : OPT->quals()) {
9675 S += '<';
9676 S += I->getObjCRuntimeNameAsString();
9677 S += '>';
9678 }
9679 S += '"';
9680 }
9681 return;
9682 }
9683
9684 // gcc just blithely ignores member pointers.
9685 // FIXME: we should do better than that. 'M' is available.
9686 case Type::MemberPointer:
9687 // This matches gcc's encoding, even though technically it is insufficient.
9688 //FIXME. We should do a better job than gcc.
9689 case Type::Vector:
9690 case Type::ExtVector:
9691 // Until we have a coherent encoding of these three types, issue warning.
9692 if (NotEncodedT)
9693 *NotEncodedT = T;
9694 return;
9695
9696 case Type::ConstantMatrix:
9697 if (NotEncodedT)
9698 *NotEncodedT = T;
9699 return;
9700
9701 case Type::BitInt:
9702 if (NotEncodedT)
9703 *NotEncodedT = T;
9704 return;
9705
9706 // We could see an undeduced auto type here during error recovery.
9707 // Just ignore it.
9708 case Type::Auto:
9709 case Type::DeducedTemplateSpecialization:
9710 return;
9711
9712 case Type::HLSLAttributedResource:
9713 case Type::HLSLInlineSpirv:
9714 llvm_unreachable("unexpected type");
9715
9716 case Type::ArrayParameter:
9717 case Type::Pipe:
9718#define ABSTRACT_TYPE(KIND, BASE)
9719#define TYPE(KIND, BASE)
9720#define DEPENDENT_TYPE(KIND, BASE) \
9721 case Type::KIND:
9722#define NON_CANONICAL_TYPE(KIND, BASE) \
9723 case Type::KIND:
9724#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9725 case Type::KIND:
9726#include "clang/AST/TypeNodes.inc"
9727 llvm_unreachable("@encode for dependent type!");
9728 }
9729 llvm_unreachable("bad type kind!");
9730}
9731
9732void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9733 std::string &S,
9734 const FieldDecl *FD,
9735 bool includeVBases,
9736 QualType *NotEncodedT) const {
9737 assert(RDecl && "Expected non-null RecordDecl");
9738 assert(!RDecl->isUnion() && "Should not be called for unions");
9739 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9740 return;
9741
9742 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9743 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9744 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9745
9746 if (CXXRec) {
9747 for (const auto &BI : CXXRec->bases()) {
9748 if (!BI.isVirtual()) {
9749 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9750 if (base->isEmpty())
9751 continue;
9752 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9753 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9754 std::make_pair(offs, base));
9755 }
9756 }
9757 }
9758
9759 for (FieldDecl *Field : RDecl->fields()) {
9760 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9761 continue;
9762 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9763 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9764 std::make_pair(offs, Field));
9765 }
9766
9767 if (CXXRec && includeVBases) {
9768 for (const auto &BI : CXXRec->vbases()) {
9769 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9770 if (base->isEmpty())
9771 continue;
9772 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9773 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9774 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9775 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9776 std::make_pair(offs, base));
9777 }
9778 }
9779
9780 CharUnits size;
9781 if (CXXRec) {
9782 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9783 } else {
9784 size = layout.getSize();
9785 }
9786
9787#ifndef NDEBUG
9788 uint64_t CurOffs = 0;
9789#endif
9790 std::multimap<uint64_t, NamedDecl *>::iterator
9791 CurLayObj = FieldOrBaseOffsets.begin();
9792
9793 if (CXXRec && CXXRec->isDynamicClass() &&
9794 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9795 if (FD) {
9796 S += "\"_vptr$";
9797 std::string recname = CXXRec->getNameAsString();
9798 if (recname.empty()) recname = "?";
9799 S += recname;
9800 S += '"';
9801 }
9802 S += "^^?";
9803#ifndef NDEBUG
9804 CurOffs += getTypeSize(VoidPtrTy);
9805#endif
9806 }
9807
9808 if (!RDecl->hasFlexibleArrayMember()) {
9809 // Mark the end of the structure.
9810 uint64_t offs = toBits(size);
9811 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9812 std::make_pair(offs, nullptr));
9813 }
9814
9815 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9816#ifndef NDEBUG
9817 assert(CurOffs <= CurLayObj->first);
9818 if (CurOffs < CurLayObj->first) {
9819 uint64_t padding = CurLayObj->first - CurOffs;
9820 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9821 // packing/alignment of members is different that normal, in which case
9822 // the encoding will be out-of-sync with the real layout.
9823 // If the runtime switches to just consider the size of types without
9824 // taking into account alignment, we could make padding explicit in the
9825 // encoding (e.g. using arrays of chars). The encoding strings would be
9826 // longer then though.
9827 CurOffs += padding;
9828 }
9829#endif
9830
9831 NamedDecl *dcl = CurLayObj->second;
9832 if (!dcl)
9833 break; // reached end of structure.
9834
9835 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9836 // We expand the bases without their virtual bases since those are going
9837 // in the initial structure. Note that this differs from gcc which
9838 // expands virtual bases each time one is encountered in the hierarchy,
9839 // making the encoding type bigger than it really is.
9840 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9841 NotEncodedT);
9842 assert(!base->isEmpty());
9843#ifndef NDEBUG
9844 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9845#endif
9846 } else {
9847 const auto *field = cast<FieldDecl>(dcl);
9848 if (FD) {
9849 S += '"';
9850 S += field->getNameAsString();
9851 S += '"';
9852 }
9853
9854 if (field->isBitField()) {
9855 EncodeBitField(this, S, field->getType(), field);
9856#ifndef NDEBUG
9857 CurOffs += field->getBitWidthValue();
9858#endif
9859 } else {
9860 QualType qt = field->getType();
9862 getObjCEncodingForTypeImpl(
9863 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9864 FD, NotEncodedT);
9865#ifndef NDEBUG
9866 CurOffs += getTypeSize(field->getType());
9867#endif
9868 }
9869 }
9870 }
9871}
9872
9874 std::string& S) const {
9875 if (QT & Decl::OBJC_TQ_In)
9876 S += 'n';
9877 if (QT & Decl::OBJC_TQ_Inout)
9878 S += 'N';
9879 if (QT & Decl::OBJC_TQ_Out)
9880 S += 'o';
9881 if (QT & Decl::OBJC_TQ_Bycopy)
9882 S += 'O';
9883 if (QT & Decl::OBJC_TQ_Byref)
9884 S += 'R';
9885 if (QT & Decl::OBJC_TQ_Oneway)
9886 S += 'V';
9887}
9888
9890 if (!ObjCIdDecl) {
9893 ObjCIdDecl = buildImplicitTypedef(T, "id");
9894 }
9895 return ObjCIdDecl;
9896}
9897
9899 if (!ObjCSelDecl) {
9901 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9902 }
9903 return ObjCSelDecl;
9904}
9905
9907 if (!ObjCClassDecl) {
9910 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9911 }
9912 return ObjCClassDecl;
9913}
9914
9916 if (!ObjCProtocolClassDecl) {
9917 ObjCProtocolClassDecl
9920 &Idents.get("Protocol"),
9921 /*typeParamList=*/nullptr,
9922 /*PrevDecl=*/nullptr,
9923 SourceLocation(), true);
9924 }
9925
9926 return ObjCProtocolClassDecl;
9927}
9928
9930 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9931 return PointerAuthQualifier();
9933 getLangOpts().PointerAuthObjcInterfaceSelKey,
9934 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9936 /*isIsaPointer=*/false,
9937 /*authenticatesNullValues=*/false);
9938}
9939
9940//===----------------------------------------------------------------------===//
9941// __builtin_va_list Construction Functions
9942//===----------------------------------------------------------------------===//
9943
9945 StringRef Name) {
9946 // typedef char* __builtin[_ms]_va_list;
9947 QualType T = Context->getPointerType(Context->CharTy);
9948 return Context->buildImplicitTypedef(T, Name);
9949}
9950
9952 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9953}
9954
9956 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9957}
9958
9960 // typedef void* __builtin_va_list;
9961 QualType T = Context->getPointerType(Context->VoidTy);
9962 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9963}
9964
9965static TypedefDecl *
9967 // struct __va_list
9968 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9969 if (Context->getLangOpts().CPlusPlus) {
9970 // namespace std { struct __va_list {
9971 auto *NS = NamespaceDecl::Create(
9972 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9973 /*Inline=*/false, SourceLocation(), SourceLocation(),
9974 &Context->Idents.get("std"),
9975 /*PrevDecl=*/nullptr, /*Nested=*/false);
9976 NS->setImplicit();
9978 }
9979
9980 VaListTagDecl->startDefinition();
9981
9982 const size_t NumFields = 5;
9983 QualType FieldTypes[NumFields];
9984 const char *FieldNames[NumFields];
9985
9986 // void *__stack;
9987 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9988 FieldNames[0] = "__stack";
9989
9990 // void *__gr_top;
9991 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9992 FieldNames[1] = "__gr_top";
9993
9994 // void *__vr_top;
9995 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9996 FieldNames[2] = "__vr_top";
9997
9998 // int __gr_offs;
9999 FieldTypes[3] = Context->IntTy;
10000 FieldNames[3] = "__gr_offs";
10001
10002 // int __vr_offs;
10003 FieldTypes[4] = Context->IntTy;
10004 FieldNames[4] = "__vr_offs";
10005
10006 // Create fields
10007 for (unsigned i = 0; i < NumFields; ++i) {
10008 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10012 &Context->Idents.get(FieldNames[i]),
10013 FieldTypes[i], /*TInfo=*/nullptr,
10014 /*BitWidth=*/nullptr,
10015 /*Mutable=*/false,
10016 ICIS_NoInit);
10017 Field->setAccess(AS_public);
10018 VaListTagDecl->addDecl(Field);
10019 }
10020 VaListTagDecl->completeDefinition();
10021 Context->VaListTagDecl = VaListTagDecl;
10022 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10023
10024 // } __builtin_va_list;
10025 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10026}
10027
10029 // typedef struct __va_list_tag {
10031
10032 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10033 VaListTagDecl->startDefinition();
10034
10035 const size_t NumFields = 5;
10036 QualType FieldTypes[NumFields];
10037 const char *FieldNames[NumFields];
10038
10039 // unsigned char gpr;
10040 FieldTypes[0] = Context->UnsignedCharTy;
10041 FieldNames[0] = "gpr";
10042
10043 // unsigned char fpr;
10044 FieldTypes[1] = Context->UnsignedCharTy;
10045 FieldNames[1] = "fpr";
10046
10047 // unsigned short reserved;
10048 FieldTypes[2] = Context->UnsignedShortTy;
10049 FieldNames[2] = "reserved";
10050
10051 // void* overflow_arg_area;
10052 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10053 FieldNames[3] = "overflow_arg_area";
10054
10055 // void* reg_save_area;
10056 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10057 FieldNames[4] = "reg_save_area";
10058
10059 // Create fields
10060 for (unsigned i = 0; i < NumFields; ++i) {
10061 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10064 &Context->Idents.get(FieldNames[i]),
10065 FieldTypes[i], /*TInfo=*/nullptr,
10066 /*BitWidth=*/nullptr,
10067 /*Mutable=*/false,
10068 ICIS_NoInit);
10069 Field->setAccess(AS_public);
10070 VaListTagDecl->addDecl(Field);
10071 }
10072 VaListTagDecl->completeDefinition();
10073 Context->VaListTagDecl = VaListTagDecl;
10074 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10075
10076 // } __va_list_tag;
10077 TypedefDecl *VaListTagTypedefDecl =
10078 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10079
10080 QualType VaListTagTypedefType =
10081 Context->getTypedefType(ElaboratedTypeKeyword::None,
10082 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10083
10084 // typedef __va_list_tag __builtin_va_list[1];
10085 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10086 QualType VaListTagArrayType = Context->getConstantArrayType(
10087 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10088 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10089}
10090
10091static TypedefDecl *
10093 // struct __va_list_tag {
10095 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10096 VaListTagDecl->startDefinition();
10097
10098 const size_t NumFields = 4;
10099 QualType FieldTypes[NumFields];
10100 const char *FieldNames[NumFields];
10101
10102 // unsigned gp_offset;
10103 FieldTypes[0] = Context->UnsignedIntTy;
10104 FieldNames[0] = "gp_offset";
10105
10106 // unsigned fp_offset;
10107 FieldTypes[1] = Context->UnsignedIntTy;
10108 FieldNames[1] = "fp_offset";
10109
10110 // void* overflow_arg_area;
10111 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10112 FieldNames[2] = "overflow_arg_area";
10113
10114 // void* reg_save_area;
10115 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10116 FieldNames[3] = "reg_save_area";
10117
10118 // Create fields
10119 for (unsigned i = 0; i < NumFields; ++i) {
10120 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10124 &Context->Idents.get(FieldNames[i]),
10125 FieldTypes[i], /*TInfo=*/nullptr,
10126 /*BitWidth=*/nullptr,
10127 /*Mutable=*/false,
10128 ICIS_NoInit);
10129 Field->setAccess(AS_public);
10130 VaListTagDecl->addDecl(Field);
10131 }
10132 VaListTagDecl->completeDefinition();
10133 Context->VaListTagDecl = VaListTagDecl;
10134 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10135
10136 // };
10137
10138 // typedef struct __va_list_tag __builtin_va_list[1];
10139 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10140 QualType VaListTagArrayType = Context->getConstantArrayType(
10141 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10142 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10143}
10144
10145static TypedefDecl *
10147 // struct __va_list
10148 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10149 if (Context->getLangOpts().CPlusPlus) {
10150 // namespace std { struct __va_list {
10151 NamespaceDecl *NS;
10152 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10153 Context->getTranslationUnitDecl(),
10154 /*Inline=*/false, SourceLocation(),
10155 SourceLocation(), &Context->Idents.get("std"),
10156 /*PrevDecl=*/nullptr, /*Nested=*/false);
10157 NS->setImplicit();
10158 VaListDecl->setDeclContext(NS);
10159 }
10160
10161 VaListDecl->startDefinition();
10162
10163 // void * __ap;
10164 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10165 VaListDecl,
10168 &Context->Idents.get("__ap"),
10169 Context->getPointerType(Context->VoidTy),
10170 /*TInfo=*/nullptr,
10171 /*BitWidth=*/nullptr,
10172 /*Mutable=*/false,
10173 ICIS_NoInit);
10174 Field->setAccess(AS_public);
10175 VaListDecl->addDecl(Field);
10176
10177 // };
10178 VaListDecl->completeDefinition();
10179 Context->VaListTagDecl = VaListDecl;
10180
10181 // typedef struct __va_list __builtin_va_list;
10182 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10183 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10184}
10185
10186static TypedefDecl *
10188 // struct __va_list_tag {
10190 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10191 VaListTagDecl->startDefinition();
10192
10193 const size_t NumFields = 4;
10194 QualType FieldTypes[NumFields];
10195 const char *FieldNames[NumFields];
10196
10197 // long __gpr;
10198 FieldTypes[0] = Context->LongTy;
10199 FieldNames[0] = "__gpr";
10200
10201 // long __fpr;
10202 FieldTypes[1] = Context->LongTy;
10203 FieldNames[1] = "__fpr";
10204
10205 // void *__overflow_arg_area;
10206 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10207 FieldNames[2] = "__overflow_arg_area";
10208
10209 // void *__reg_save_area;
10210 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10211 FieldNames[3] = "__reg_save_area";
10212
10213 // Create fields
10214 for (unsigned i = 0; i < NumFields; ++i) {
10215 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10219 &Context->Idents.get(FieldNames[i]),
10220 FieldTypes[i], /*TInfo=*/nullptr,
10221 /*BitWidth=*/nullptr,
10222 /*Mutable=*/false,
10223 ICIS_NoInit);
10224 Field->setAccess(AS_public);
10225 VaListTagDecl->addDecl(Field);
10226 }
10227 VaListTagDecl->completeDefinition();
10228 Context->VaListTagDecl = VaListTagDecl;
10229 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10230
10231 // };
10232
10233 // typedef __va_list_tag __builtin_va_list[1];
10234 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10235 QualType VaListTagArrayType = Context->getConstantArrayType(
10236 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10237
10238 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10239}
10240
10242 // typedef struct __va_list_tag {
10244 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10245 VaListTagDecl->startDefinition();
10246
10247 const size_t NumFields = 3;
10248 QualType FieldTypes[NumFields];
10249 const char *FieldNames[NumFields];
10250
10251 // void *CurrentSavedRegisterArea;
10252 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10253 FieldNames[0] = "__current_saved_reg_area_pointer";
10254
10255 // void *SavedRegAreaEnd;
10256 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10257 FieldNames[1] = "__saved_reg_area_end_pointer";
10258
10259 // void *OverflowArea;
10260 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10261 FieldNames[2] = "__overflow_area_pointer";
10262
10263 // Create fields
10264 for (unsigned i = 0; i < NumFields; ++i) {
10266 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10267 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10268 /*TInfo=*/nullptr,
10269 /*BitWidth=*/nullptr,
10270 /*Mutable=*/false, ICIS_NoInit);
10271 Field->setAccess(AS_public);
10272 VaListTagDecl->addDecl(Field);
10273 }
10274 VaListTagDecl->completeDefinition();
10275 Context->VaListTagDecl = VaListTagDecl;
10276 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10277
10278 // } __va_list_tag;
10279 TypedefDecl *VaListTagTypedefDecl =
10280 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10281
10282 QualType VaListTagTypedefType =
10283 Context->getTypedefType(ElaboratedTypeKeyword::None,
10284 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10285
10286 // typedef __va_list_tag __builtin_va_list[1];
10287 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10288 QualType VaListTagArrayType = Context->getConstantArrayType(
10289 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10290
10291 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10292}
10293
10294static TypedefDecl *
10296 // typedef struct __va_list_tag {
10297 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10298
10299 VaListTagDecl->startDefinition();
10300
10301 // int* __va_stk;
10302 // int* __va_reg;
10303 // int __va_ndx;
10304 constexpr size_t NumFields = 3;
10305 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10306 Context->getPointerType(Context->IntTy),
10307 Context->IntTy};
10308 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10309
10310 // Create fields
10311 for (unsigned i = 0; i < NumFields; ++i) {
10314 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10315 /*BitWidth=*/nullptr,
10316 /*Mutable=*/false, ICIS_NoInit);
10317 Field->setAccess(AS_public);
10318 VaListTagDecl->addDecl(Field);
10319 }
10320 VaListTagDecl->completeDefinition();
10321 Context->VaListTagDecl = VaListTagDecl;
10322 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10323
10324 // } __va_list_tag;
10325 TypedefDecl *VaListTagTypedefDecl =
10326 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10327
10328 return VaListTagTypedefDecl;
10329}
10330
10333 switch (Kind) {
10335 return CreateCharPtrBuiltinVaListDecl(Context);
10337 return CreateVoidPtrBuiltinVaListDecl(Context);
10339 return CreateAArch64ABIBuiltinVaListDecl(Context);
10341 return CreatePowerABIBuiltinVaListDecl(Context);
10343 return CreateX86_64ABIBuiltinVaListDecl(Context);
10345 return CreateAAPCSABIBuiltinVaListDecl(Context);
10347 return CreateSystemZBuiltinVaListDecl(Context);
10349 return CreateHexagonBuiltinVaListDecl(Context);
10351 return CreateXtensaABIBuiltinVaListDecl(Context);
10352 }
10353
10354 llvm_unreachable("Unhandled __builtin_va_list type kind");
10355}
10356
10358 if (!BuiltinVaListDecl) {
10359 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10360 assert(BuiltinVaListDecl->isImplicit());
10361 }
10362
10363 return BuiltinVaListDecl;
10364}
10365
10367 // Force the creation of VaListTagDecl by building the __builtin_va_list
10368 // declaration.
10369 if (!VaListTagDecl)
10370 (void)getBuiltinVaListDecl();
10371
10372 return VaListTagDecl;
10373}
10374
10376 if (!BuiltinMSVaListDecl)
10377 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10378
10379 return BuiltinMSVaListDecl;
10380}
10381
10383 // Allow redecl custom type checking builtin for HLSL.
10384 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10385 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10386 return true;
10387 // Allow redecl custom type checking builtin for SPIR-V.
10388 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10389 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10390 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10391 return true;
10392 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10393}
10394
10396 assert(ObjCConstantStringType.isNull() &&
10397 "'NSConstantString' type already set!");
10398
10399 ObjCConstantStringType = getObjCInterfaceType(Decl);
10400}
10401
10402/// Retrieve the template name that corresponds to a non-empty
10403/// lookup.
10406 UnresolvedSetIterator End) const {
10407 unsigned size = End - Begin;
10408 assert(size > 1 && "set is not overloaded!");
10409
10410 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10411 size * sizeof(FunctionTemplateDecl*));
10412 auto *OT = new (memory) OverloadedTemplateStorage(size);
10413
10414 NamedDecl **Storage = OT->getStorage();
10415 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10416 NamedDecl *D = *I;
10417 assert(isa<FunctionTemplateDecl>(D) ||
10421 *Storage++ = D;
10422 }
10423
10424 return TemplateName(OT);
10425}
10426
10427/// Retrieve a template name representing an unqualified-id that has been
10428/// assumed to name a template for ADL purposes.
10430 auto *OT = new (*this) AssumedTemplateStorage(Name);
10431 return TemplateName(OT);
10432}
10433
10434/// Retrieve the template name that represents a qualified
10435/// template name such as \c std::vector.
10437 bool TemplateKeyword,
10438 TemplateName Template) const {
10439 assert(Template.getKind() == TemplateName::Template ||
10441
10442 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10443 assert(!Qualifier && "unexpected qualified template template parameter");
10444 assert(TemplateKeyword == false);
10445 return Template;
10446 }
10447
10448 // FIXME: Canonicalization?
10449 llvm::FoldingSetNodeID ID;
10450 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10451
10452 void *InsertPos = nullptr;
10454 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10455 if (!QTN) {
10456 QTN = new (*this, alignof(QualifiedTemplateName))
10457 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10458 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10459 }
10460
10461 return TemplateName(QTN);
10462}
10463
10464/// Retrieve the template name that represents a dependent
10465/// template name such as \c MetaFun::template operator+.
10468 llvm::FoldingSetNodeID ID;
10469 S.Profile(ID);
10470
10471 void *InsertPos = nullptr;
10472 if (DependentTemplateName *QTN =
10473 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10474 return TemplateName(QTN);
10475
10477 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10478 DependentTemplateNames.InsertNode(QTN, InsertPos);
10479 return TemplateName(QTN);
10480}
10481
10483 Decl *AssociatedDecl,
10484 unsigned Index,
10485 UnsignedOrNone PackIndex,
10486 bool Final) const {
10487 llvm::FoldingSetNodeID ID;
10488 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10489 Index, PackIndex, Final);
10490
10491 void *insertPos = nullptr;
10493 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10494
10495 if (!subst) {
10496 subst = new (*this) SubstTemplateTemplateParmStorage(
10497 Replacement, AssociatedDecl, Index, PackIndex, Final);
10498 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10499 }
10500
10501 return TemplateName(subst);
10502}
10503
10506 Decl *AssociatedDecl,
10507 unsigned Index, bool Final) const {
10508 auto &Self = const_cast<ASTContext &>(*this);
10509 llvm::FoldingSetNodeID ID;
10511 AssociatedDecl, Index, Final);
10512
10513 void *InsertPos = nullptr;
10515 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10516
10517 if (!Subst) {
10518 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10519 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10520 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10521 }
10522
10523 return TemplateName(Subst);
10524}
10525
10526/// Retrieve the template name that represents a template name
10527/// deduced from a specialization.
10530 DefaultArguments DefaultArgs) const {
10531 if (!DefaultArgs)
10532 return Underlying;
10533
10534 llvm::FoldingSetNodeID ID;
10535 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10536
10537 void *InsertPos = nullptr;
10539 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10540 if (!DTS) {
10541 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10542 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10543 alignof(DeducedTemplateStorage));
10544 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10545 DeducedTemplates.InsertNode(DTS, InsertPos);
10546 }
10547 return TemplateName(DTS);
10548}
10549
10550/// getFromTargetType - Given one of the integer types provided by
10551/// TargetInfo, produce the corresponding type. The unsigned @p Type
10552/// is actually a value of type @c TargetInfo::IntType.
10553CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10554 switch (Type) {
10555 case TargetInfo::NoInt: return {};
10558 case TargetInfo::SignedShort: return ShortTy;
10560 case TargetInfo::SignedInt: return IntTy;
10562 case TargetInfo::SignedLong: return LongTy;
10566 }
10567
10568 llvm_unreachable("Unhandled TargetInfo::IntType value");
10569}
10570
10571//===----------------------------------------------------------------------===//
10572// Type Predicates.
10573//===----------------------------------------------------------------------===//
10574
10575/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10576/// garbage collection attribute.
10577///
10579 if (getLangOpts().getGC() == LangOptions::NonGC)
10580 return Qualifiers::GCNone;
10581
10582 assert(getLangOpts().ObjC);
10583 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10584
10585 // Default behaviour under objective-C's gc is for ObjC pointers
10586 // (or pointers to them) be treated as though they were declared
10587 // as __strong.
10588 if (GCAttrs == Qualifiers::GCNone) {
10590 return Qualifiers::Strong;
10591 else if (Ty->isPointerType())
10593 } else {
10594 // It's not valid to set GC attributes on anything that isn't a
10595 // pointer.
10596#ifndef NDEBUG
10598 while (const auto *AT = dyn_cast<ArrayType>(CT))
10599 CT = AT->getElementType();
10600 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10601#endif
10602 }
10603 return GCAttrs;
10604}
10605
10606//===----------------------------------------------------------------------===//
10607// Type Compatibility Testing
10608//===----------------------------------------------------------------------===//
10609
10610/// areCompatVectorTypes - Return true if the two specified vector types are
10611/// compatible.
10612static bool areCompatVectorTypes(const VectorType *LHS,
10613 const VectorType *RHS) {
10614 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10615 return LHS->getElementType() == RHS->getElementType() &&
10616 LHS->getNumElements() == RHS->getNumElements();
10617}
10618
10619/// areCompatMatrixTypes - Return true if the two specified matrix types are
10620/// compatible.
10622 const ConstantMatrixType *RHS) {
10623 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10624 return LHS->getElementType() == RHS->getElementType() &&
10625 LHS->getNumRows() == RHS->getNumRows() &&
10626 LHS->getNumColumns() == RHS->getNumColumns();
10627}
10628
10630 QualType SecondVec) {
10631 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10632 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10633
10634 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10635 return true;
10636
10637 // Treat Neon vector types and most AltiVec vector types as if they are the
10638 // equivalent GCC vector types.
10639 const auto *First = FirstVec->castAs<VectorType>();
10640 const auto *Second = SecondVec->castAs<VectorType>();
10641 if (First->getNumElements() == Second->getNumElements() &&
10642 hasSameType(First->getElementType(), Second->getElementType()) &&
10643 First->getVectorKind() != VectorKind::AltiVecPixel &&
10644 First->getVectorKind() != VectorKind::AltiVecBool &&
10647 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10648 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10651 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10653 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10655 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10657 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10659 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10661 return true;
10662
10663 return false;
10664}
10665
10666/// getRVVTypeSize - Return RVV vector register size.
10667static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10668 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10669 auto VScale = Context.getTargetInfo().getVScaleRange(
10670 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10671 if (!VScale)
10672 return 0;
10673
10674 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10675
10676 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10677 if (Info.ElementType == Context.BoolTy)
10678 EltSize = 1;
10679
10680 uint64_t MinElts = Info.EC.getKnownMinValue();
10681 return VScale->first * MinElts * EltSize;
10682}
10683
10685 QualType SecondType) {
10686 assert(
10687 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10688 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10689 "Expected RVV builtin type and vector type!");
10690
10691 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10692 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10693 if (const auto *VT = SecondType->getAs<VectorType>()) {
10694 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10696 return FirstType->isRVVVLSBuiltinType() &&
10697 Info.ElementType == BoolTy &&
10698 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10699 }
10700 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10702 return FirstType->isRVVVLSBuiltinType() &&
10703 Info.ElementType == BoolTy &&
10704 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10705 }
10706 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10708 return FirstType->isRVVVLSBuiltinType() &&
10709 Info.ElementType == BoolTy &&
10710 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10711 }
10712 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10714 return FirstType->isRVVVLSBuiltinType() &&
10715 Info.ElementType == BoolTy &&
10716 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10717 }
10718 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10719 VT->getVectorKind() == VectorKind::Generic)
10720 return FirstType->isRVVVLSBuiltinType() &&
10721 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10722 hasSameType(VT->getElementType(),
10723 getBuiltinVectorTypeInfo(BT).ElementType);
10724 }
10725 }
10726 return false;
10727 };
10728
10729 return IsValidCast(FirstType, SecondType) ||
10730 IsValidCast(SecondType, FirstType);
10731}
10732
10734 QualType SecondType) {
10735 assert(
10736 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10737 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10738 "Expected RVV builtin type and vector type!");
10739
10740 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10741 const auto *BT = FirstType->getAs<BuiltinType>();
10742 if (!BT)
10743 return false;
10744
10745 if (!BT->isRVVVLSBuiltinType())
10746 return false;
10747
10748 const auto *VecTy = SecondType->getAs<VectorType>();
10749 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10751 getLangOpts().getLaxVectorConversions();
10752
10753 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10754 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10755 return false;
10756
10757 // If -flax-vector-conversions=all is specified, the types are
10758 // certainly compatible.
10760 return true;
10761
10762 // If -flax-vector-conversions=integer is specified, the types are
10763 // compatible if the elements are integer types.
10765 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10766 FirstType->getRVVEltType(*this)->isIntegerType();
10767 }
10768
10769 return false;
10770 };
10771
10772 return IsLaxCompatible(FirstType, SecondType) ||
10773 IsLaxCompatible(SecondType, FirstType);
10774}
10775
10777 while (true) {
10778 // __strong id
10779 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10780 if (Attr->getAttrKind() == attr::ObjCOwnership)
10781 return true;
10782
10783 Ty = Attr->getModifiedType();
10784
10785 // X *__strong (...)
10786 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10787 Ty = Paren->getInnerType();
10788
10789 // We do not want to look through typedefs, typeof(expr),
10790 // typeof(type), or any other way that the type is somehow
10791 // abstracted.
10792 } else {
10793 return false;
10794 }
10795 }
10796}
10797
10798//===----------------------------------------------------------------------===//
10799// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10800//===----------------------------------------------------------------------===//
10801
10802/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10803/// inheritance hierarchy of 'rProto'.
10804bool
10806 ObjCProtocolDecl *rProto) const {
10807 if (declaresSameEntity(lProto, rProto))
10808 return true;
10809 for (auto *PI : rProto->protocols())
10810 if (ProtocolCompatibleWithProtocol(lProto, PI))
10811 return true;
10812 return false;
10813}
10814
10815/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10816/// Class<pr1, ...>.
10818 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10819 for (auto *lhsProto : lhs->quals()) {
10820 bool match = false;
10821 for (auto *rhsProto : rhs->quals()) {
10822 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10823 match = true;
10824 break;
10825 }
10826 }
10827 if (!match)
10828 return false;
10829 }
10830 return true;
10831}
10832
10833/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10834/// ObjCQualifiedIDType.
10836 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10837 bool compare) {
10838 // Allow id<P..> and an 'id' in all cases.
10839 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10840 return true;
10841
10842 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10843 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10845 return false;
10846
10847 if (lhs->isObjCQualifiedIdType()) {
10848 if (rhs->qual_empty()) {
10849 // If the RHS is a unqualified interface pointer "NSString*",
10850 // make sure we check the class hierarchy.
10851 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10852 for (auto *I : lhs->quals()) {
10853 // when comparing an id<P> on lhs with a static type on rhs,
10854 // see if static class implements all of id's protocols, directly or
10855 // through its super class and categories.
10856 if (!rhsID->ClassImplementsProtocol(I, true))
10857 return false;
10858 }
10859 }
10860 // If there are no qualifiers and no interface, we have an 'id'.
10861 return true;
10862 }
10863 // Both the right and left sides have qualifiers.
10864 for (auto *lhsProto : lhs->quals()) {
10865 bool match = false;
10866
10867 // when comparing an id<P> on lhs with a static type on rhs,
10868 // see if static class implements all of id's protocols, directly or
10869 // through its super class and categories.
10870 for (auto *rhsProto : rhs->quals()) {
10871 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10872 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10873 match = true;
10874 break;
10875 }
10876 }
10877 // If the RHS is a qualified interface pointer "NSString<P>*",
10878 // make sure we check the class hierarchy.
10879 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10880 for (auto *I : lhs->quals()) {
10881 // when comparing an id<P> on lhs with a static type on rhs,
10882 // see if static class implements all of id's protocols, directly or
10883 // through its super class and categories.
10884 if (rhsID->ClassImplementsProtocol(I, true)) {
10885 match = true;
10886 break;
10887 }
10888 }
10889 }
10890 if (!match)
10891 return false;
10892 }
10893
10894 return true;
10895 }
10896
10897 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10898
10899 if (lhs->getInterfaceType()) {
10900 // If both the right and left sides have qualifiers.
10901 for (auto *lhsProto : lhs->quals()) {
10902 bool match = false;
10903
10904 // when comparing an id<P> on rhs with a static type on lhs,
10905 // see if static class implements all of id's protocols, directly or
10906 // through its super class and categories.
10907 // First, lhs protocols in the qualifier list must be found, direct
10908 // or indirect in rhs's qualifier list or it is a mismatch.
10909 for (auto *rhsProto : rhs->quals()) {
10910 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10911 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10912 match = true;
10913 break;
10914 }
10915 }
10916 if (!match)
10917 return false;
10918 }
10919
10920 // Static class's protocols, or its super class or category protocols
10921 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10922 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10923 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10924 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10925 // This is rather dubious but matches gcc's behavior. If lhs has
10926 // no type qualifier and its class has no static protocol(s)
10927 // assume that it is mismatch.
10928 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10929 return false;
10930 for (auto *lhsProto : LHSInheritedProtocols) {
10931 bool match = false;
10932 for (auto *rhsProto : rhs->quals()) {
10933 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10934 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10935 match = true;
10936 break;
10937 }
10938 }
10939 if (!match)
10940 return false;
10941 }
10942 }
10943 return true;
10944 }
10945 return false;
10946}
10947
10948/// canAssignObjCInterfaces - Return true if the two interface types are
10949/// compatible for assignment from RHS to LHS. This handles validation of any
10950/// protocol qualifiers on the LHS or RHS.
10952 const ObjCObjectPointerType *RHSOPT) {
10953 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10954 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10955
10956 // If either type represents the built-in 'id' type, return true.
10957 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10958 return true;
10959
10960 // Function object that propagates a successful result or handles
10961 // __kindof types.
10962 auto finish = [&](bool succeeded) -> bool {
10963 if (succeeded)
10964 return true;
10965
10966 if (!RHS->isKindOfType())
10967 return false;
10968
10969 // Strip off __kindof and protocol qualifiers, then check whether
10970 // we can assign the other way.
10972 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10973 };
10974
10975 // Casts from or to id<P> are allowed when the other side has compatible
10976 // protocols.
10977 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10978 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10979 }
10980
10981 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10982 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10983 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10984 }
10985
10986 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10987 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10988 return true;
10989 }
10990
10991 // If we have 2 user-defined types, fall into that path.
10992 if (LHS->getInterface() && RHS->getInterface()) {
10993 return finish(canAssignObjCInterfaces(LHS, RHS));
10994 }
10995
10996 return false;
10997}
10998
10999/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11000/// for providing type-safety for objective-c pointers used to pass/return
11001/// arguments in block literals. When passed as arguments, passing 'A*' where
11002/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11003/// not OK. For the return type, the opposite is not OK.
11005 const ObjCObjectPointerType *LHSOPT,
11006 const ObjCObjectPointerType *RHSOPT,
11007 bool BlockReturnType) {
11008
11009 // Function object that propagates a successful result or handles
11010 // __kindof types.
11011 auto finish = [&](bool succeeded) -> bool {
11012 if (succeeded)
11013 return true;
11014
11015 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11016 if (!Expected->isKindOfType())
11017 return false;
11018
11019 // Strip off __kindof and protocol qualifiers, then check whether
11020 // we can assign the other way.
11022 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11023 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11024 BlockReturnType);
11025 };
11026
11027 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11028 return true;
11029
11030 if (LHSOPT->isObjCBuiltinType()) {
11031 return finish(RHSOPT->isObjCBuiltinType() ||
11032 RHSOPT->isObjCQualifiedIdType());
11033 }
11034
11035 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11036 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11037 // Use for block parameters previous type checking for compatibility.
11038 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11039 // Or corrected type checking as in non-compat mode.
11040 (!BlockReturnType &&
11041 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11042 else
11044 (BlockReturnType ? LHSOPT : RHSOPT),
11045 (BlockReturnType ? RHSOPT : LHSOPT), false));
11046 }
11047
11048 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11049 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11050 if (LHS && RHS) { // We have 2 user-defined types.
11051 if (LHS != RHS) {
11052 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11053 return finish(BlockReturnType);
11054 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11055 return finish(!BlockReturnType);
11056 }
11057 else
11058 return true;
11059 }
11060 return false;
11061}
11062
11063/// Comparison routine for Objective-C protocols to be used with
11064/// llvm::array_pod_sort.
11066 ObjCProtocolDecl * const *rhs) {
11067 return (*lhs)->getName().compare((*rhs)->getName());
11068}
11069
11070/// getIntersectionOfProtocols - This routine finds the intersection of set
11071/// of protocols inherited from two distinct objective-c pointer objects with
11072/// the given common base.
11073/// It is used to build composite qualifier list of the composite type of
11074/// the conditional expression involving two objective-c pointer objects.
11075static
11077 const ObjCInterfaceDecl *CommonBase,
11078 const ObjCObjectPointerType *LHSOPT,
11079 const ObjCObjectPointerType *RHSOPT,
11080 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11081
11082 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11083 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11084 assert(LHS->getInterface() && "LHS must have an interface base");
11085 assert(RHS->getInterface() && "RHS must have an interface base");
11086
11087 // Add all of the protocols for the LHS.
11089
11090 // Start with the protocol qualifiers.
11091 for (auto *proto : LHS->quals()) {
11092 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11093 }
11094
11095 // Also add the protocols associated with the LHS interface.
11096 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11097
11098 // Add all of the protocols for the RHS.
11100
11101 // Start with the protocol qualifiers.
11102 for (auto *proto : RHS->quals()) {
11103 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11104 }
11105
11106 // Also add the protocols associated with the RHS interface.
11107 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11108
11109 // Compute the intersection of the collected protocol sets.
11110 for (auto *proto : LHSProtocolSet) {
11111 if (RHSProtocolSet.count(proto))
11112 IntersectionSet.push_back(proto);
11113 }
11114
11115 // Compute the set of protocols that is implied by either the common type or
11116 // the protocols within the intersection.
11118 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11119
11120 // Remove any implied protocols from the list of inherited protocols.
11121 if (!ImpliedProtocols.empty()) {
11122 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11123 return ImpliedProtocols.contains(proto);
11124 });
11125 }
11126
11127 // Sort the remaining protocols by name.
11128 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11130}
11131
11132/// Determine whether the first type is a subtype of the second.
11134 QualType rhs) {
11135 // Common case: two object pointers.
11136 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11137 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11138 if (lhsOPT && rhsOPT)
11139 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11140
11141 // Two block pointers.
11142 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11143 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11144 if (lhsBlock && rhsBlock)
11145 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11146
11147 // If either is an unqualified 'id' and the other is a block, it's
11148 // acceptable.
11149 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11150 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11151 return true;
11152
11153 return false;
11154}
11155
11156// Check that the given Objective-C type argument lists are equivalent.
11158 const ObjCInterfaceDecl *iface,
11159 ArrayRef<QualType> lhsArgs,
11160 ArrayRef<QualType> rhsArgs,
11161 bool stripKindOf) {
11162 if (lhsArgs.size() != rhsArgs.size())
11163 return false;
11164
11165 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11166 if (!typeParams)
11167 return false;
11168
11169 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11170 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11171 continue;
11172
11173 switch (typeParams->begin()[i]->getVariance()) {
11175 if (!stripKindOf ||
11176 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11177 rhsArgs[i].stripObjCKindOfType(ctx))) {
11178 return false;
11179 }
11180 break;
11181
11183 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11184 return false;
11185 break;
11186
11188 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11189 return false;
11190 break;
11191 }
11192 }
11193
11194 return true;
11195}
11196
11198 const ObjCObjectPointerType *Lptr,
11199 const ObjCObjectPointerType *Rptr) {
11200 const ObjCObjectType *LHS = Lptr->getObjectType();
11201 const ObjCObjectType *RHS = Rptr->getObjectType();
11202 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11203 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11204
11205 if (!LDecl || !RDecl)
11206 return {};
11207
11208 // When either LHS or RHS is a kindof type, we should return a kindof type.
11209 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11210 // kindof(A).
11211 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11212
11213 // Follow the left-hand side up the class hierarchy until we either hit a
11214 // root or find the RHS. Record the ancestors in case we don't find it.
11215 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11216 LHSAncestors;
11217 while (true) {
11218 // Record this ancestor. We'll need this if the common type isn't in the
11219 // path from the LHS to the root.
11220 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11221
11222 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11223 // Get the type arguments.
11224 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11225 bool anyChanges = false;
11226 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11227 // Both have type arguments, compare them.
11228 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11229 LHS->getTypeArgs(), RHS->getTypeArgs(),
11230 /*stripKindOf=*/true))
11231 return {};
11232 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11233 // If only one has type arguments, the result will not have type
11234 // arguments.
11235 LHSTypeArgs = {};
11236 anyChanges = true;
11237 }
11238
11239 // Compute the intersection of protocols.
11241 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11242 Protocols);
11243 if (!Protocols.empty())
11244 anyChanges = true;
11245
11246 // If anything in the LHS will have changed, build a new result type.
11247 // If we need to return a kindof type but LHS is not a kindof type, we
11248 // build a new result type.
11249 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11250 QualType Result = getObjCInterfaceType(LHS->getInterface());
11251 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11252 anyKindOf || LHS->isKindOfType());
11254 }
11255
11256 return getObjCObjectPointerType(QualType(LHS, 0));
11257 }
11258
11259 // Find the superclass.
11260 QualType LHSSuperType = LHS->getSuperClassType();
11261 if (LHSSuperType.isNull())
11262 break;
11263
11264 LHS = LHSSuperType->castAs<ObjCObjectType>();
11265 }
11266
11267 // We didn't find anything by following the LHS to its root; now check
11268 // the RHS against the cached set of ancestors.
11269 while (true) {
11270 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11271 if (KnownLHS != LHSAncestors.end()) {
11272 LHS = KnownLHS->second;
11273
11274 // Get the type arguments.
11275 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11276 bool anyChanges = false;
11277 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11278 // Both have type arguments, compare them.
11279 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11280 LHS->getTypeArgs(), RHS->getTypeArgs(),
11281 /*stripKindOf=*/true))
11282 return {};
11283 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11284 // If only one has type arguments, the result will not have type
11285 // arguments.
11286 RHSTypeArgs = {};
11287 anyChanges = true;
11288 }
11289
11290 // Compute the intersection of protocols.
11292 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11293 Protocols);
11294 if (!Protocols.empty())
11295 anyChanges = true;
11296
11297 // If we need to return a kindof type but RHS is not a kindof type, we
11298 // build a new result type.
11299 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11300 QualType Result = getObjCInterfaceType(RHS->getInterface());
11301 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11302 anyKindOf || RHS->isKindOfType());
11304 }
11305
11306 return getObjCObjectPointerType(QualType(RHS, 0));
11307 }
11308
11309 // Find the superclass of the RHS.
11310 QualType RHSSuperType = RHS->getSuperClassType();
11311 if (RHSSuperType.isNull())
11312 break;
11313
11314 RHS = RHSSuperType->castAs<ObjCObjectType>();
11315 }
11316
11317 return {};
11318}
11319
11321 const ObjCObjectType *RHS) {
11322 assert(LHS->getInterface() && "LHS is not an interface type");
11323 assert(RHS->getInterface() && "RHS is not an interface type");
11324
11325 // Verify that the base decls are compatible: the RHS must be a subclass of
11326 // the LHS.
11327 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11328 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11329 if (!IsSuperClass)
11330 return false;
11331
11332 // If the LHS has protocol qualifiers, determine whether all of them are
11333 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11334 // LHS).
11335 if (LHS->getNumProtocols() > 0) {
11336 // OK if conversion of LHS to SuperClass results in narrowing of types
11337 // ; i.e., SuperClass may implement at least one of the protocols
11338 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11339 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11340 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11341 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11342 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11343 // qualifiers.
11344 for (auto *RHSPI : RHS->quals())
11345 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11346 // If there is no protocols associated with RHS, it is not a match.
11347 if (SuperClassInheritedProtocols.empty())
11348 return false;
11349
11350 for (const auto *LHSProto : LHS->quals()) {
11351 bool SuperImplementsProtocol = false;
11352 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11353 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11354 SuperImplementsProtocol = true;
11355 break;
11356 }
11357 if (!SuperImplementsProtocol)
11358 return false;
11359 }
11360 }
11361
11362 // If the LHS is specialized, we may need to check type arguments.
11363 if (LHS->isSpecialized()) {
11364 // Follow the superclass chain until we've matched the LHS class in the
11365 // hierarchy. This substitutes type arguments through.
11366 const ObjCObjectType *RHSSuper = RHS;
11367 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11368 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11369
11370 // If the RHS is specializd, compare type arguments.
11371 if (RHSSuper->isSpecialized() &&
11372 !sameObjCTypeArgs(*this, LHS->getInterface(),
11373 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11374 /*stripKindOf=*/true)) {
11375 return false;
11376 }
11377 }
11378
11379 return true;
11380}
11381
11383 // get the "pointed to" types
11384 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11385 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11386
11387 if (!LHSOPT || !RHSOPT)
11388 return false;
11389
11390 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11391 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11392}
11393
11396 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11397 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11398}
11399
11400/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11401/// both shall have the identically qualified version of a compatible type.
11402/// C99 6.2.7p1: Two types have compatible types if their types are the
11403/// same. See 6.7.[2,3,5] for additional rules.
11405 bool CompareUnqualified) {
11406 if (getLangOpts().CPlusPlus)
11407 return hasSameType(LHS, RHS);
11408
11409 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11410}
11411
11413 return typesAreCompatible(LHS, RHS);
11414}
11415
11417 return !mergeTypes(LHS, RHS, true).isNull();
11418}
11419
11420/// mergeTransparentUnionType - if T is a transparent union type and a member
11421/// of T is compatible with SubType, return the merged type, else return
11422/// QualType()
11424 bool OfBlockPointer,
11425 bool Unqualified) {
11426 if (const RecordType *UT = T->getAsUnionType()) {
11427 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11428 if (UD->hasAttr<TransparentUnionAttr>()) {
11429 for (const auto *I : UD->fields()) {
11430 QualType ET = I->getType().getUnqualifiedType();
11431 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11432 if (!MT.isNull())
11433 return MT;
11434 }
11435 }
11436 }
11437
11438 return {};
11439}
11440
11441/// mergeFunctionParameterTypes - merge two types which appear as function
11442/// parameter types
11444 bool OfBlockPointer,
11445 bool Unqualified) {
11446 // GNU extension: two types are compatible if they appear as a function
11447 // argument, one of the types is a transparent union type and the other
11448 // type is compatible with a union member
11449 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11450 Unqualified);
11451 if (!lmerge.isNull())
11452 return lmerge;
11453
11454 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11455 Unqualified);
11456 if (!rmerge.isNull())
11457 return rmerge;
11458
11459 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11460}
11461
11463 bool OfBlockPointer, bool Unqualified,
11464 bool AllowCXX,
11465 bool IsConditionalOperator) {
11466 const auto *lbase = lhs->castAs<FunctionType>();
11467 const auto *rbase = rhs->castAs<FunctionType>();
11468 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11469 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11470 bool allLTypes = true;
11471 bool allRTypes = true;
11472
11473 // Check return type
11474 QualType retType;
11475 if (OfBlockPointer) {
11476 QualType RHS = rbase->getReturnType();
11477 QualType LHS = lbase->getReturnType();
11478 bool UnqualifiedResult = Unqualified;
11479 if (!UnqualifiedResult)
11480 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11481 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11482 }
11483 else
11484 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11485 Unqualified);
11486 if (retType.isNull())
11487 return {};
11488
11489 if (Unqualified)
11490 retType = retType.getUnqualifiedType();
11491
11492 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11493 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11494 if (Unqualified) {
11495 LRetType = LRetType.getUnqualifiedType();
11496 RRetType = RRetType.getUnqualifiedType();
11497 }
11498
11499 if (getCanonicalType(retType) != LRetType)
11500 allLTypes = false;
11501 if (getCanonicalType(retType) != RRetType)
11502 allRTypes = false;
11503
11504 // FIXME: double check this
11505 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11506 // rbase->getRegParmAttr() != 0 &&
11507 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11508 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11509 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11510
11511 // Compatible functions must have compatible calling conventions
11512 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11513 return {};
11514
11515 // Regparm is part of the calling convention.
11516 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11517 return {};
11518 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11519 return {};
11520
11521 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11522 return {};
11523 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11524 return {};
11525 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11526 return {};
11527
11528 // When merging declarations, it's common for supplemental information like
11529 // attributes to only be present in one of the declarations, and we generally
11530 // want type merging to preserve the union of information. So a merged
11531 // function type should be noreturn if it was noreturn in *either* operand
11532 // type.
11533 //
11534 // But for the conditional operator, this is backwards. The result of the
11535 // operator could be either operand, and its type should conservatively
11536 // reflect that. So a function type in a composite type is noreturn only
11537 // if it's noreturn in *both* operand types.
11538 //
11539 // Arguably, noreturn is a kind of subtype, and the conditional operator
11540 // ought to produce the most specific common supertype of its operand types.
11541 // That would differ from this rule in contravariant positions. However,
11542 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11543 // as a practical matter, it would only affect C code that does abstraction of
11544 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11545 // say the least. So we use the simpler rule.
11546 bool NoReturn = IsConditionalOperator
11547 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11548 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11549 if (lbaseInfo.getNoReturn() != NoReturn)
11550 allLTypes = false;
11551 if (rbaseInfo.getNoReturn() != NoReturn)
11552 allRTypes = false;
11553
11554 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11555
11556 std::optional<FunctionEffectSet> MergedFX;
11557
11558 if (lproto && rproto) { // two C99 style function prototypes
11559 assert((AllowCXX ||
11560 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11561 "C++ shouldn't be here");
11562 // Compatible functions must have the same number of parameters
11563 if (lproto->getNumParams() != rproto->getNumParams())
11564 return {};
11565
11566 // Variadic and non-variadic functions aren't compatible
11567 if (lproto->isVariadic() != rproto->isVariadic())
11568 return {};
11569
11570 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11571 return {};
11572
11573 // Function protos with different 'cfi_salt' values aren't compatible.
11574 if (lproto->getExtraAttributeInfo().CFISalt !=
11575 rproto->getExtraAttributeInfo().CFISalt)
11576 return {};
11577
11578 // Function effects are handled similarly to noreturn, see above.
11579 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11580 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11581 if (LHSFX != RHSFX) {
11582 if (IsConditionalOperator)
11583 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11584 else {
11586 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11587 // Here we're discarding a possible error due to conflicts in the effect
11588 // sets. But we're not in a context where we can report it. The
11589 // operation does however guarantee maintenance of invariants.
11590 }
11591 if (*MergedFX != LHSFX)
11592 allLTypes = false;
11593 if (*MergedFX != RHSFX)
11594 allRTypes = false;
11595 }
11596
11598 bool canUseLeft, canUseRight;
11599 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11600 newParamInfos))
11601 return {};
11602
11603 if (!canUseLeft)
11604 allLTypes = false;
11605 if (!canUseRight)
11606 allRTypes = false;
11607
11608 // Check parameter type compatibility
11610 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11611 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11612 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11614 lParamType, rParamType, OfBlockPointer, Unqualified);
11615 if (paramType.isNull())
11616 return {};
11617
11618 if (Unqualified)
11619 paramType = paramType.getUnqualifiedType();
11620
11621 types.push_back(paramType);
11622 if (Unqualified) {
11623 lParamType = lParamType.getUnqualifiedType();
11624 rParamType = rParamType.getUnqualifiedType();
11625 }
11626
11627 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11628 allLTypes = false;
11629 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11630 allRTypes = false;
11631 }
11632
11633 if (allLTypes) return lhs;
11634 if (allRTypes) return rhs;
11635
11636 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11637 EPI.ExtInfo = einfo;
11638 EPI.ExtParameterInfos =
11639 newParamInfos.empty() ? nullptr : newParamInfos.data();
11640 if (MergedFX)
11641 EPI.FunctionEffects = *MergedFX;
11642 return getFunctionType(retType, types, EPI);
11643 }
11644
11645 if (lproto) allRTypes = false;
11646 if (rproto) allLTypes = false;
11647
11648 const FunctionProtoType *proto = lproto ? lproto : rproto;
11649 if (proto) {
11650 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11651 if (proto->isVariadic())
11652 return {};
11653 // Check that the types are compatible with the types that
11654 // would result from default argument promotions (C99 6.7.5.3p15).
11655 // The only types actually affected are promotable integer
11656 // types and floats, which would be passed as a different
11657 // type depending on whether the prototype is visible.
11658 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11659 QualType paramTy = proto->getParamType(i);
11660
11661 // Look at the converted type of enum types, since that is the type used
11662 // to pass enum values.
11663 if (const auto *ED = paramTy->getAsEnumDecl()) {
11664 paramTy = ED->getIntegerType();
11665 if (paramTy.isNull())
11666 return {};
11667 }
11668
11669 if (isPromotableIntegerType(paramTy) ||
11670 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11671 return {};
11672 }
11673
11674 if (allLTypes) return lhs;
11675 if (allRTypes) return rhs;
11676
11678 EPI.ExtInfo = einfo;
11679 if (MergedFX)
11680 EPI.FunctionEffects = *MergedFX;
11681 return getFunctionType(retType, proto->getParamTypes(), EPI);
11682 }
11683
11684 if (allLTypes) return lhs;
11685 if (allRTypes) return rhs;
11686 return getFunctionNoProtoType(retType, einfo);
11687}
11688
11689/// Given that we have an enum type and a non-enum type, try to merge them.
11690static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11691 QualType other, bool isBlockReturnType) {
11692 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11693 // a signed integer type, or an unsigned integer type.
11694 // Compatibility is based on the underlying type, not the promotion
11695 // type.
11696 QualType underlyingType =
11697 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11698 if (underlyingType.isNull())
11699 return {};
11700 if (Context.hasSameType(underlyingType, other))
11701 return other;
11702
11703 // In block return types, we're more permissive and accept any
11704 // integral type of the same size.
11705 if (isBlockReturnType && other->isIntegerType() &&
11706 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11707 return other;
11708
11709 return {};
11710}
11711
11713 // C17 and earlier and C++ disallow two tag definitions within the same TU
11714 // from being compatible.
11715 if (LangOpts.CPlusPlus || !LangOpts.C23)
11716 return {};
11717
11718 // C23, on the other hand, requires the members to be "the same enough", so
11719 // we use a structural equivalence check.
11722 getLangOpts(), *this, *this, NonEquivalentDecls,
11723 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11724 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11725 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11726}
11727
11728QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11729 bool Unqualified, bool BlockReturnType,
11730 bool IsConditionalOperator) {
11731 // For C++ we will not reach this code with reference types (see below),
11732 // for OpenMP variant call overloading we might.
11733 //
11734 // C++ [expr]: If an expression initially has the type "reference to T", the
11735 // type is adjusted to "T" prior to any further analysis, the expression
11736 // designates the object or function denoted by the reference, and the
11737 // expression is an lvalue unless the reference is an rvalue reference and
11738 // the expression is a function call (possibly inside parentheses).
11739 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11740 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11741 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11742 LHS->getTypeClass() == RHS->getTypeClass())
11743 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11744 OfBlockPointer, Unqualified, BlockReturnType);
11745 if (LHSRefTy || RHSRefTy)
11746 return {};
11747
11748 if (Unqualified) {
11749 LHS = LHS.getUnqualifiedType();
11750 RHS = RHS.getUnqualifiedType();
11751 }
11752
11753 QualType LHSCan = getCanonicalType(LHS),
11754 RHSCan = getCanonicalType(RHS);
11755
11756 // If two types are identical, they are compatible.
11757 if (LHSCan == RHSCan)
11758 return LHS;
11759
11760 // If the qualifiers are different, the types aren't compatible... mostly.
11761 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11762 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11763 if (LQuals != RQuals) {
11764 // If any of these qualifiers are different, we have a type
11765 // mismatch.
11766 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11767 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11768 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11769 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11770 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11771 return {};
11772
11773 // Exactly one GC qualifier difference is allowed: __strong is
11774 // okay if the other type has no GC qualifier but is an Objective
11775 // C object pointer (i.e. implicitly strong by default). We fix
11776 // this by pretending that the unqualified type was actually
11777 // qualified __strong.
11778 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11779 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11780 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11781
11782 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11783 return {};
11784
11785 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11787 }
11788 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11790 }
11791 return {};
11792 }
11793
11794 // Okay, qualifiers are equal.
11795
11796 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11797 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11798
11799 // We want to consider the two function types to be the same for these
11800 // comparisons, just force one to the other.
11801 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11802 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11803
11804 // Same as above for arrays
11805 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11806 LHSClass = Type::ConstantArray;
11807 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11808 RHSClass = Type::ConstantArray;
11809
11810 // ObjCInterfaces are just specialized ObjCObjects.
11811 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11812 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11813
11814 // Canonicalize ExtVector -> Vector.
11815 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11816 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11817
11818 // If the canonical type classes don't match.
11819 if (LHSClass != RHSClass) {
11820 // Note that we only have special rules for turning block enum
11821 // returns into block int returns, not vice-versa.
11822 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11823 return mergeEnumWithInteger(*this, ETy, RHS, false);
11824 }
11825 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11826 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11827 }
11828 // allow block pointer type to match an 'id' type.
11829 if (OfBlockPointer && !BlockReturnType) {
11830 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11831 return LHS;
11832 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11833 return RHS;
11834 }
11835 // Allow __auto_type to match anything; it merges to the type with more
11836 // information.
11837 if (const auto *AT = LHS->getAs<AutoType>()) {
11838 if (!AT->isDeduced() && AT->isGNUAutoType())
11839 return RHS;
11840 }
11841 if (const auto *AT = RHS->getAs<AutoType>()) {
11842 if (!AT->isDeduced() && AT->isGNUAutoType())
11843 return LHS;
11844 }
11845 return {};
11846 }
11847
11848 // The canonical type classes match.
11849 switch (LHSClass) {
11850#define TYPE(Class, Base)
11851#define ABSTRACT_TYPE(Class, Base)
11852#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11853#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11854#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11855#include "clang/AST/TypeNodes.inc"
11856 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11857
11858 case Type::Auto:
11859 case Type::DeducedTemplateSpecialization:
11860 case Type::LValueReference:
11861 case Type::RValueReference:
11862 case Type::MemberPointer:
11863 llvm_unreachable("C++ should never be in mergeTypes");
11864
11865 case Type::ObjCInterface:
11866 case Type::IncompleteArray:
11867 case Type::VariableArray:
11868 case Type::FunctionProto:
11869 case Type::ExtVector:
11870 llvm_unreachable("Types are eliminated above");
11871
11872 case Type::Pointer:
11873 {
11874 // Merge two pointer types, while trying to preserve typedef info
11875 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11876 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11877 if (Unqualified) {
11878 LHSPointee = LHSPointee.getUnqualifiedType();
11879 RHSPointee = RHSPointee.getUnqualifiedType();
11880 }
11881 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11882 Unqualified);
11883 if (ResultType.isNull())
11884 return {};
11885 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11886 return LHS;
11887 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11888 return RHS;
11889 return getPointerType(ResultType);
11890 }
11891 case Type::BlockPointer:
11892 {
11893 // Merge two block pointer types, while trying to preserve typedef info
11894 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11895 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11896 if (Unqualified) {
11897 LHSPointee = LHSPointee.getUnqualifiedType();
11898 RHSPointee = RHSPointee.getUnqualifiedType();
11899 }
11900 if (getLangOpts().OpenCL) {
11901 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11902 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11903 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11904 // 6.12.5) thus the following check is asymmetric.
11905 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11906 return {};
11907 LHSPteeQual.removeAddressSpace();
11908 RHSPteeQual.removeAddressSpace();
11909 LHSPointee =
11910 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11911 RHSPointee =
11912 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11913 }
11914 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11915 Unqualified);
11916 if (ResultType.isNull())
11917 return {};
11918 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11919 return LHS;
11920 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11921 return RHS;
11922 return getBlockPointerType(ResultType);
11923 }
11924 case Type::Atomic:
11925 {
11926 // Merge two pointer types, while trying to preserve typedef info
11927 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11928 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11929 if (Unqualified) {
11930 LHSValue = LHSValue.getUnqualifiedType();
11931 RHSValue = RHSValue.getUnqualifiedType();
11932 }
11933 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11934 Unqualified);
11935 if (ResultType.isNull())
11936 return {};
11937 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11938 return LHS;
11939 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11940 return RHS;
11941 return getAtomicType(ResultType);
11942 }
11943 case Type::ConstantArray:
11944 {
11945 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11946 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11947 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11948 return {};
11949
11950 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11951 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11952 if (Unqualified) {
11953 LHSElem = LHSElem.getUnqualifiedType();
11954 RHSElem = RHSElem.getUnqualifiedType();
11955 }
11956
11957 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11958 if (ResultType.isNull())
11959 return {};
11960
11961 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11962 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11963
11964 // If either side is a variable array, and both are complete, check whether
11965 // the current dimension is definite.
11966 if (LVAT || RVAT) {
11967 auto SizeFetch = [this](const VariableArrayType* VAT,
11968 const ConstantArrayType* CAT)
11969 -> std::pair<bool,llvm::APInt> {
11970 if (VAT) {
11971 std::optional<llvm::APSInt> TheInt;
11972 Expr *E = VAT->getSizeExpr();
11973 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11974 return std::make_pair(true, *TheInt);
11975 return std::make_pair(false, llvm::APSInt());
11976 }
11977 if (CAT)
11978 return std::make_pair(true, CAT->getSize());
11979 return std::make_pair(false, llvm::APInt());
11980 };
11981
11982 bool HaveLSize, HaveRSize;
11983 llvm::APInt LSize, RSize;
11984 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11985 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11986 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11987 return {}; // Definite, but unequal, array dimension
11988 }
11989
11990 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11991 return LHS;
11992 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11993 return RHS;
11994 if (LCAT)
11995 return getConstantArrayType(ResultType, LCAT->getSize(),
11996 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11997 if (RCAT)
11998 return getConstantArrayType(ResultType, RCAT->getSize(),
11999 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12000 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12001 return LHS;
12002 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12003 return RHS;
12004 if (LVAT) {
12005 // FIXME: This isn't correct! But tricky to implement because
12006 // the array's size has to be the size of LHS, but the type
12007 // has to be different.
12008 return LHS;
12009 }
12010 if (RVAT) {
12011 // FIXME: This isn't correct! But tricky to implement because
12012 // the array's size has to be the size of RHS, but the type
12013 // has to be different.
12014 return RHS;
12015 }
12016 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12017 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12018 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12019 }
12020 case Type::FunctionNoProto:
12021 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12022 /*AllowCXX=*/false, IsConditionalOperator);
12023 case Type::Record:
12024 case Type::Enum:
12025 return mergeTagDefinitions(LHS, RHS);
12026 case Type::Builtin:
12027 // Only exactly equal builtin types are compatible, which is tested above.
12028 return {};
12029 case Type::Complex:
12030 // Distinct complex types are incompatible.
12031 return {};
12032 case Type::Vector:
12033 // FIXME: The merged type should be an ExtVector!
12034 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12035 RHSCan->castAs<VectorType>()))
12036 return LHS;
12037 return {};
12038 case Type::ConstantMatrix:
12040 RHSCan->castAs<ConstantMatrixType>()))
12041 return LHS;
12042 return {};
12043 case Type::ObjCObject: {
12044 // Check if the types are assignment compatible.
12045 // FIXME: This should be type compatibility, e.g. whether
12046 // "LHS x; RHS x;" at global scope is legal.
12048 RHS->castAs<ObjCObjectType>()))
12049 return LHS;
12050 return {};
12051 }
12052 case Type::ObjCObjectPointer:
12053 if (OfBlockPointer) {
12056 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12057 return LHS;
12058 return {};
12059 }
12062 return LHS;
12063 return {};
12064 case Type::Pipe:
12065 assert(LHS != RHS &&
12066 "Equivalent pipe types should have already been handled!");
12067 return {};
12068 case Type::ArrayParameter:
12069 assert(LHS != RHS &&
12070 "Equivalent ArrayParameter types should have already been handled!");
12071 return {};
12072 case Type::BitInt: {
12073 // Merge two bit-precise int types, while trying to preserve typedef info.
12074 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12075 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12076 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12077 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12078
12079 // Like unsigned/int, shouldn't have a type if they don't match.
12080 if (LHSUnsigned != RHSUnsigned)
12081 return {};
12082
12083 if (LHSBits != RHSBits)
12084 return {};
12085 return LHS;
12086 }
12087 case Type::HLSLAttributedResource: {
12088 const HLSLAttributedResourceType *LHSTy =
12089 LHS->castAs<HLSLAttributedResourceType>();
12090 const HLSLAttributedResourceType *RHSTy =
12091 RHS->castAs<HLSLAttributedResourceType>();
12092 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12093 LHSTy->getWrappedType()->isHLSLResourceType() &&
12094 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12095
12096 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12097 LHSTy->getContainedType() == RHSTy->getContainedType())
12098 return LHS;
12099 return {};
12100 }
12101 case Type::HLSLInlineSpirv:
12102 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12103 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12104
12105 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12106 LHSTy->getSize() == RHSTy->getSize() &&
12107 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12108 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12109 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12110 return {};
12111
12112 return LHS;
12113 }
12114 return {};
12115 }
12116
12117 llvm_unreachable("Invalid Type::Class!");
12118}
12119
12121 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12122 bool &CanUseFirst, bool &CanUseSecond,
12124 assert(NewParamInfos.empty() && "param info list not empty");
12125 CanUseFirst = CanUseSecond = true;
12126 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12127 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12128
12129 // Fast path: if the first type doesn't have ext parameter infos,
12130 // we match if and only if the second type also doesn't have them.
12131 if (!FirstHasInfo && !SecondHasInfo)
12132 return true;
12133
12134 bool NeedParamInfo = false;
12135 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12136 : SecondFnType->getExtParameterInfos().size();
12137
12138 for (size_t I = 0; I < E; ++I) {
12139 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12140 if (FirstHasInfo)
12141 FirstParam = FirstFnType->getExtParameterInfo(I);
12142 if (SecondHasInfo)
12143 SecondParam = SecondFnType->getExtParameterInfo(I);
12144
12145 // Cannot merge unless everything except the noescape flag matches.
12146 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12147 return false;
12148
12149 bool FirstNoEscape = FirstParam.isNoEscape();
12150 bool SecondNoEscape = SecondParam.isNoEscape();
12151 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12152 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12153 if (NewParamInfos.back().getOpaqueValue())
12154 NeedParamInfo = true;
12155 if (FirstNoEscape != IsNoEscape)
12156 CanUseFirst = false;
12157 if (SecondNoEscape != IsNoEscape)
12158 CanUseSecond = false;
12159 }
12160
12161 if (!NeedParamInfo)
12162 NewParamInfos.clear();
12163
12164 return true;
12165}
12166
12168 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12169 It->second = nullptr;
12170 for (auto *SubClass : ObjCSubClasses[D])
12171 ResetObjCLayout(SubClass);
12172 }
12173}
12174
12175/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12176/// 'RHS' attributes and returns the merged version; including for function
12177/// return types.
12179 QualType LHSCan = getCanonicalType(LHS),
12180 RHSCan = getCanonicalType(RHS);
12181 // If two types are identical, they are compatible.
12182 if (LHSCan == RHSCan)
12183 return LHS;
12184 if (RHSCan->isFunctionType()) {
12185 if (!LHSCan->isFunctionType())
12186 return {};
12187 QualType OldReturnType =
12188 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12189 QualType NewReturnType =
12190 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12191 QualType ResReturnType =
12192 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12193 if (ResReturnType.isNull())
12194 return {};
12195 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12196 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12197 // In either case, use OldReturnType to build the new function type.
12198 const auto *F = LHS->castAs<FunctionType>();
12199 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12200 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12201 EPI.ExtInfo = getFunctionExtInfo(LHS);
12202 QualType ResultType =
12203 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12204 return ResultType;
12205 }
12206 }
12207 return {};
12208 }
12209
12210 // If the qualifiers are different, the types can still be merged.
12211 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12212 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12213 if (LQuals != RQuals) {
12214 // If any of these qualifiers are different, we have a type mismatch.
12215 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12216 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12217 return {};
12218
12219 // Exactly one GC qualifier difference is allowed: __strong is
12220 // okay if the other type has no GC qualifier but is an Objective
12221 // C object pointer (i.e. implicitly strong by default). We fix
12222 // this by pretending that the unqualified type was actually
12223 // qualified __strong.
12224 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12225 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12226 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12227
12228 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12229 return {};
12230
12231 if (GC_L == Qualifiers::Strong)
12232 return LHS;
12233 if (GC_R == Qualifiers::Strong)
12234 return RHS;
12235 return {};
12236 }
12237
12238 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12239 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12240 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12241 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12242 if (ResQT == LHSBaseQT)
12243 return LHS;
12244 if (ResQT == RHSBaseQT)
12245 return RHS;
12246 }
12247 return {};
12248}
12249
12250//===----------------------------------------------------------------------===//
12251// Integer Predicates
12252//===----------------------------------------------------------------------===//
12253
12255 if (const auto *ED = T->getAsEnumDecl())
12256 T = ED->getIntegerType();
12257 if (T->isBooleanType())
12258 return 1;
12259 if (const auto *EIT = T->getAs<BitIntType>())
12260 return EIT->getNumBits();
12261 // For builtin types, just use the standard type sizing method
12262 return (unsigned)getTypeSize(T);
12263}
12264
12266 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12267 T->isFixedPointType()) &&
12268 "Unexpected type");
12269
12270 // Turn <4 x signed int> -> <4 x unsigned int>
12271 if (const auto *VTy = T->getAs<VectorType>())
12272 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12273 VTy->getNumElements(), VTy->getVectorKind());
12274
12275 // For _BitInt, return an unsigned _BitInt with same width.
12276 if (const auto *EITy = T->getAs<BitIntType>())
12277 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12278
12279 // For enums, get the underlying integer type of the enum, and let the general
12280 // integer type signchanging code handle it.
12281 if (const auto *ED = T->getAsEnumDecl())
12282 T = ED->getIntegerType();
12283
12284 switch (T->castAs<BuiltinType>()->getKind()) {
12285 case BuiltinType::Char_U:
12286 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12287 case BuiltinType::Char_S:
12288 case BuiltinType::SChar:
12289 case BuiltinType::Char8:
12290 return UnsignedCharTy;
12291 case BuiltinType::Short:
12292 return UnsignedShortTy;
12293 case BuiltinType::Int:
12294 return UnsignedIntTy;
12295 case BuiltinType::Long:
12296 return UnsignedLongTy;
12297 case BuiltinType::LongLong:
12298 return UnsignedLongLongTy;
12299 case BuiltinType::Int128:
12300 return UnsignedInt128Ty;
12301 // wchar_t is special. It is either signed or not, but when it's signed,
12302 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12303 // version of its underlying type instead.
12304 case BuiltinType::WChar_S:
12305 return getUnsignedWCharType();
12306
12307 case BuiltinType::ShortAccum:
12308 return UnsignedShortAccumTy;
12309 case BuiltinType::Accum:
12310 return UnsignedAccumTy;
12311 case BuiltinType::LongAccum:
12312 return UnsignedLongAccumTy;
12313 case BuiltinType::SatShortAccum:
12315 case BuiltinType::SatAccum:
12316 return SatUnsignedAccumTy;
12317 case BuiltinType::SatLongAccum:
12319 case BuiltinType::ShortFract:
12320 return UnsignedShortFractTy;
12321 case BuiltinType::Fract:
12322 return UnsignedFractTy;
12323 case BuiltinType::LongFract:
12324 return UnsignedLongFractTy;
12325 case BuiltinType::SatShortFract:
12327 case BuiltinType::SatFract:
12328 return SatUnsignedFractTy;
12329 case BuiltinType::SatLongFract:
12331 default:
12332 assert((T->hasUnsignedIntegerRepresentation() ||
12333 T->isUnsignedFixedPointType()) &&
12334 "Unexpected signed integer or fixed point type");
12335 return T;
12336 }
12337}
12338
12340 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12341 T->isFixedPointType()) &&
12342 "Unexpected type");
12343
12344 // Turn <4 x unsigned int> -> <4 x signed int>
12345 if (const auto *VTy = T->getAs<VectorType>())
12346 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12347 VTy->getNumElements(), VTy->getVectorKind());
12348
12349 // For _BitInt, return a signed _BitInt with same width.
12350 if (const auto *EITy = T->getAs<BitIntType>())
12351 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12352
12353 // For enums, get the underlying integer type of the enum, and let the general
12354 // integer type signchanging code handle it.
12355 if (const auto *ED = T->getAsEnumDecl())
12356 T = ED->getIntegerType();
12357
12358 switch (T->castAs<BuiltinType>()->getKind()) {
12359 case BuiltinType::Char_S:
12360 // Plain `char` is mapped to `signed char` even if it's already signed
12361 case BuiltinType::Char_U:
12362 case BuiltinType::UChar:
12363 case BuiltinType::Char8:
12364 return SignedCharTy;
12365 case BuiltinType::UShort:
12366 return ShortTy;
12367 case BuiltinType::UInt:
12368 return IntTy;
12369 case BuiltinType::ULong:
12370 return LongTy;
12371 case BuiltinType::ULongLong:
12372 return LongLongTy;
12373 case BuiltinType::UInt128:
12374 return Int128Ty;
12375 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12376 // there's no matching "signed wchar_t". Therefore we return the signed
12377 // version of its underlying type instead.
12378 case BuiltinType::WChar_U:
12379 return getSignedWCharType();
12380
12381 case BuiltinType::UShortAccum:
12382 return ShortAccumTy;
12383 case BuiltinType::UAccum:
12384 return AccumTy;
12385 case BuiltinType::ULongAccum:
12386 return LongAccumTy;
12387 case BuiltinType::SatUShortAccum:
12388 return SatShortAccumTy;
12389 case BuiltinType::SatUAccum:
12390 return SatAccumTy;
12391 case BuiltinType::SatULongAccum:
12392 return SatLongAccumTy;
12393 case BuiltinType::UShortFract:
12394 return ShortFractTy;
12395 case BuiltinType::UFract:
12396 return FractTy;
12397 case BuiltinType::ULongFract:
12398 return LongFractTy;
12399 case BuiltinType::SatUShortFract:
12400 return SatShortFractTy;
12401 case BuiltinType::SatUFract:
12402 return SatFractTy;
12403 case BuiltinType::SatULongFract:
12404 return SatLongFractTy;
12405 default:
12406 assert(
12407 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12408 "Unexpected signed integer or fixed point type");
12409 return T;
12410 }
12411}
12412
12414
12417
12418//===----------------------------------------------------------------------===//
12419// Builtin Type Computation
12420//===----------------------------------------------------------------------===//
12421
12422/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12423/// pointer over the consumed characters. This returns the resultant type. If
12424/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12425/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12426/// a vector of "i*".
12427///
12428/// RequiresICE is filled in on return to indicate whether the value is required
12429/// to be an Integer Constant Expression.
12430static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12432 bool &RequiresICE,
12433 bool AllowTypeModifiers) {
12434 // Modifiers.
12435 int HowLong = 0;
12436 bool Signed = false, Unsigned = false;
12437 RequiresICE = false;
12438
12439 // Read the prefixed modifiers first.
12440 bool Done = false;
12441 #ifndef NDEBUG
12442 bool IsSpecial = false;
12443 #endif
12444 while (!Done) {
12445 switch (*Str++) {
12446 default: Done = true; --Str; break;
12447 case 'I':
12448 RequiresICE = true;
12449 break;
12450 case 'S':
12451 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12452 assert(!Signed && "Can't use 'S' modifier multiple times!");
12453 Signed = true;
12454 break;
12455 case 'U':
12456 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12457 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12458 Unsigned = true;
12459 break;
12460 case 'L':
12461 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12462 assert(HowLong <= 2 && "Can't have LLLL modifier");
12463 ++HowLong;
12464 break;
12465 case 'N':
12466 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12467 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12468 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12469 #ifndef NDEBUG
12470 IsSpecial = true;
12471 #endif
12472 if (Context.getTargetInfo().getLongWidth() == 32)
12473 ++HowLong;
12474 break;
12475 case 'W':
12476 // This modifier represents int64 type.
12477 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12478 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12479 #ifndef NDEBUG
12480 IsSpecial = true;
12481 #endif
12482 switch (Context.getTargetInfo().getInt64Type()) {
12483 default:
12484 llvm_unreachable("Unexpected integer type");
12486 HowLong = 1;
12487 break;
12489 HowLong = 2;
12490 break;
12491 }
12492 break;
12493 case 'Z':
12494 // This modifier represents int32 type.
12495 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12496 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12497 #ifndef NDEBUG
12498 IsSpecial = true;
12499 #endif
12500 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12501 default:
12502 llvm_unreachable("Unexpected integer type");
12504 HowLong = 0;
12505 break;
12507 HowLong = 1;
12508 break;
12510 HowLong = 2;
12511 break;
12512 }
12513 break;
12514 case 'O':
12515 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12516 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12517 #ifndef NDEBUG
12518 IsSpecial = true;
12519 #endif
12520 if (Context.getLangOpts().OpenCL)
12521 HowLong = 1;
12522 else
12523 HowLong = 2;
12524 break;
12525 }
12526 }
12527
12528 QualType Type;
12529
12530 // Read the base type.
12531 switch (*Str++) {
12532 default: llvm_unreachable("Unknown builtin type letter!");
12533 case 'x':
12534 assert(HowLong == 0 && !Signed && !Unsigned &&
12535 "Bad modifiers used with 'x'!");
12536 Type = Context.Float16Ty;
12537 break;
12538 case 'y':
12539 assert(HowLong == 0 && !Signed && !Unsigned &&
12540 "Bad modifiers used with 'y'!");
12541 Type = Context.BFloat16Ty;
12542 break;
12543 case 'v':
12544 assert(HowLong == 0 && !Signed && !Unsigned &&
12545 "Bad modifiers used with 'v'!");
12546 Type = Context.VoidTy;
12547 break;
12548 case 'h':
12549 assert(HowLong == 0 && !Signed && !Unsigned &&
12550 "Bad modifiers used with 'h'!");
12551 Type = Context.HalfTy;
12552 break;
12553 case 'f':
12554 assert(HowLong == 0 && !Signed && !Unsigned &&
12555 "Bad modifiers used with 'f'!");
12556 Type = Context.FloatTy;
12557 break;
12558 case 'd':
12559 assert(HowLong < 3 && !Signed && !Unsigned &&
12560 "Bad modifiers used with 'd'!");
12561 if (HowLong == 1)
12562 Type = Context.LongDoubleTy;
12563 else if (HowLong == 2)
12564 Type = Context.Float128Ty;
12565 else
12566 Type = Context.DoubleTy;
12567 break;
12568 case 's':
12569 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12570 if (Unsigned)
12571 Type = Context.UnsignedShortTy;
12572 else
12573 Type = Context.ShortTy;
12574 break;
12575 case 'i':
12576 if (HowLong == 3)
12577 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12578 else if (HowLong == 2)
12579 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12580 else if (HowLong == 1)
12581 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12582 else
12583 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12584 break;
12585 case 'c':
12586 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12587 if (Signed)
12588 Type = Context.SignedCharTy;
12589 else if (Unsigned)
12590 Type = Context.UnsignedCharTy;
12591 else
12592 Type = Context.CharTy;
12593 break;
12594 case 'b': // boolean
12595 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12596 Type = Context.BoolTy;
12597 break;
12598 case 'z': // size_t.
12599 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12600 Type = Context.getSizeType();
12601 break;
12602 case 'w': // wchar_t.
12603 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12604 Type = Context.getWideCharType();
12605 break;
12606 case 'F':
12607 Type = Context.getCFConstantStringType();
12608 break;
12609 case 'G':
12610 Type = Context.getObjCIdType();
12611 break;
12612 case 'H':
12613 Type = Context.getObjCSelType();
12614 break;
12615 case 'M':
12616 Type = Context.getObjCSuperType();
12617 break;
12618 case 'a':
12619 Type = Context.getBuiltinVaListType();
12620 assert(!Type.isNull() && "builtin va list type not initialized!");
12621 break;
12622 case 'A':
12623 // This is a "reference" to a va_list; however, what exactly
12624 // this means depends on how va_list is defined. There are two
12625 // different kinds of va_list: ones passed by value, and ones
12626 // passed by reference. An example of a by-value va_list is
12627 // x86, where va_list is a char*. An example of by-ref va_list
12628 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12629 // we want this argument to be a char*&; for x86-64, we want
12630 // it to be a __va_list_tag*.
12631 Type = Context.getBuiltinVaListType();
12632 assert(!Type.isNull() && "builtin va list type not initialized!");
12633 if (Type->isArrayType())
12634 Type = Context.getArrayDecayedType(Type);
12635 else
12636 Type = Context.getLValueReferenceType(Type);
12637 break;
12638 case 'q': {
12639 char *End;
12640 unsigned NumElements = strtoul(Str, &End, 10);
12641 assert(End != Str && "Missing vector size");
12642 Str = End;
12643
12644 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12645 RequiresICE, false);
12646 assert(!RequiresICE && "Can't require vector ICE");
12647
12648 Type = Context.getScalableVectorType(ElementType, NumElements);
12649 break;
12650 }
12651 case 'Q': {
12652 switch (*Str++) {
12653 case 'a': {
12654 Type = Context.SveCountTy;
12655 break;
12656 }
12657 case 'b': {
12658 Type = Context.AMDGPUBufferRsrcTy;
12659 break;
12660 }
12661 default:
12662 llvm_unreachable("Unexpected target builtin type");
12663 }
12664 break;
12665 }
12666 case 'V': {
12667 char *End;
12668 unsigned NumElements = strtoul(Str, &End, 10);
12669 assert(End != Str && "Missing vector size");
12670 Str = End;
12671
12672 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12673 RequiresICE, false);
12674 assert(!RequiresICE && "Can't require vector ICE");
12675
12676 // TODO: No way to make AltiVec vectors in builtins yet.
12677 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12678 break;
12679 }
12680 case 'E': {
12681 char *End;
12682
12683 unsigned NumElements = strtoul(Str, &End, 10);
12684 assert(End != Str && "Missing vector size");
12685
12686 Str = End;
12687
12688 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12689 false);
12690 Type = Context.getExtVectorType(ElementType, NumElements);
12691 break;
12692 }
12693 case 'X': {
12694 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12695 false);
12696 assert(!RequiresICE && "Can't require complex ICE");
12697 Type = Context.getComplexType(ElementType);
12698 break;
12699 }
12700 case 'Y':
12701 Type = Context.getPointerDiffType();
12702 break;
12703 case 'P':
12704 Type = Context.getFILEType();
12705 if (Type.isNull()) {
12707 return {};
12708 }
12709 break;
12710 case 'J':
12711 if (Signed)
12712 Type = Context.getsigjmp_bufType();
12713 else
12714 Type = Context.getjmp_bufType();
12715
12716 if (Type.isNull()) {
12718 return {};
12719 }
12720 break;
12721 case 'K':
12722 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12723 Type = Context.getucontext_tType();
12724
12725 if (Type.isNull()) {
12727 return {};
12728 }
12729 break;
12730 case 'p':
12731 Type = Context.getProcessIDType();
12732 break;
12733 case 'm':
12734 Type = Context.MFloat8Ty;
12735 break;
12736 }
12737
12738 // If there are modifiers and if we're allowed to parse them, go for it.
12739 Done = !AllowTypeModifiers;
12740 while (!Done) {
12741 switch (char c = *Str++) {
12742 default: Done = true; --Str; break;
12743 case '*':
12744 case '&': {
12745 // Both pointers and references can have their pointee types
12746 // qualified with an address space.
12747 char *End;
12748 unsigned AddrSpace = strtoul(Str, &End, 10);
12749 if (End != Str) {
12750 // Note AddrSpace == 0 is not the same as an unspecified address space.
12751 Type = Context.getAddrSpaceQualType(
12752 Type,
12753 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12754 Str = End;
12755 }
12756 if (c == '*')
12757 Type = Context.getPointerType(Type);
12758 else
12759 Type = Context.getLValueReferenceType(Type);
12760 break;
12761 }
12762 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12763 case 'C':
12764 Type = Type.withConst();
12765 break;
12766 case 'D':
12767 Type = Context.getVolatileType(Type);
12768 break;
12769 case 'R':
12770 Type = Type.withRestrict();
12771 break;
12772 }
12773 }
12774
12775 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12776 "Integer constant 'I' type must be an integer");
12777
12778 return Type;
12779}
12780
12781// On some targets such as PowerPC, some of the builtins are defined with custom
12782// type descriptors for target-dependent types. These descriptors are decoded in
12783// other functions, but it may be useful to be able to fall back to default
12784// descriptor decoding to define builtins mixing target-dependent and target-
12785// independent types. This function allows decoding one type descriptor with
12786// default decoding.
12787QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12788 GetBuiltinTypeError &Error, bool &RequireICE,
12789 bool AllowTypeModifiers) const {
12790 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12791}
12792
12793/// GetBuiltinType - Return the type for the specified builtin.
12796 unsigned *IntegerConstantArgs) const {
12797 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12798 if (TypeStr[0] == '\0') {
12800 return {};
12801 }
12802
12803 SmallVector<QualType, 8> ArgTypes;
12804
12805 bool RequiresICE = false;
12806 Error = GE_None;
12807 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12808 RequiresICE, true);
12809 if (Error != GE_None)
12810 return {};
12811
12812 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12813
12814 while (TypeStr[0] && TypeStr[0] != '.') {
12815 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12816 if (Error != GE_None)
12817 return {};
12818
12819 // If this argument is required to be an IntegerConstantExpression and the
12820 // caller cares, fill in the bitmask we return.
12821 if (RequiresICE && IntegerConstantArgs)
12822 *IntegerConstantArgs |= 1 << ArgTypes.size();
12823
12824 // Do array -> pointer decay. The builtin should use the decayed type.
12825 if (Ty->isArrayType())
12826 Ty = getArrayDecayedType(Ty);
12827
12828 ArgTypes.push_back(Ty);
12829 }
12830
12831 if (Id == Builtin::BI__GetExceptionInfo)
12832 return {};
12833
12834 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12835 "'.' should only occur at end of builtin type list!");
12836
12837 bool Variadic = (TypeStr[0] == '.');
12838
12839 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12840 if (BuiltinInfo.isNoReturn(Id))
12841 EI = EI.withNoReturn(true);
12842
12843 // We really shouldn't be making a no-proto type here.
12844 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12845 return getFunctionNoProtoType(ResType, EI);
12846
12848 EPI.ExtInfo = EI;
12849 EPI.Variadic = Variadic;
12850 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12851 EPI.ExceptionSpec.Type =
12853
12854 return getFunctionType(ResType, ArgTypes, EPI);
12855}
12856
12858 const FunctionDecl *FD) {
12859 if (!FD->isExternallyVisible())
12860 return GVA_Internal;
12861
12862 // Non-user-provided functions get emitted as weak definitions with every
12863 // use, no matter whether they've been explicitly instantiated etc.
12864 if (!FD->isUserProvided())
12865 return GVA_DiscardableODR;
12866
12868 switch (FD->getTemplateSpecializationKind()) {
12869 case TSK_Undeclared:
12872 break;
12873
12875 return GVA_StrongODR;
12876
12877 // C++11 [temp.explicit]p10:
12878 // [ Note: The intent is that an inline function that is the subject of
12879 // an explicit instantiation declaration will still be implicitly
12880 // instantiated when used so that the body can be considered for
12881 // inlining, but that no out-of-line copy of the inline function would be
12882 // generated in the translation unit. -- end note ]
12885
12888 break;
12889 }
12890
12891 if (!FD->isInlined())
12892 return External;
12893
12894 if ((!Context.getLangOpts().CPlusPlus &&
12895 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12896 !FD->hasAttr<DLLExportAttr>()) ||
12897 FD->hasAttr<GNUInlineAttr>()) {
12898 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12899
12900 // GNU or C99 inline semantics. Determine whether this symbol should be
12901 // externally visible.
12903 return External;
12904
12905 // C99 inline semantics, where the symbol is not externally visible.
12907 }
12908
12909 // Functions specified with extern and inline in -fms-compatibility mode
12910 // forcibly get emitted. While the body of the function cannot be later
12911 // replaced, the function definition cannot be discarded.
12912 if (FD->isMSExternInline())
12913 return GVA_StrongODR;
12914
12915 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12917 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12918 // Our approach to inheriting constructors is fundamentally different from
12919 // that used by the MS ABI, so keep our inheriting constructor thunks
12920 // internal rather than trying to pick an unambiguous mangling for them.
12921 return GVA_Internal;
12922
12923 return GVA_DiscardableODR;
12924}
12925
12927 const Decl *D, GVALinkage L) {
12928 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12929 // dllexport/dllimport on inline functions.
12930 if (D->hasAttr<DLLImportAttr>()) {
12931 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12933 } else if (D->hasAttr<DLLExportAttr>()) {
12934 if (L == GVA_DiscardableODR)
12935 return GVA_StrongODR;
12936 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12937 // Device-side functions with __global__ attribute must always be
12938 // visible externally so they can be launched from host.
12939 if (D->hasAttr<CUDAGlobalAttr>() &&
12940 (L == GVA_DiscardableODR || L == GVA_Internal))
12941 return GVA_StrongODR;
12942 // Single source offloading languages like CUDA/HIP need to be able to
12943 // access static device variables from host code of the same compilation
12944 // unit. This is done by externalizing the static variable with a shared
12945 // name between the host and device compilation which is the same for the
12946 // same compilation unit whereas different among different compilation
12947 // units.
12948 if (Context.shouldExternalize(D))
12949 return GVA_StrongExternal;
12950 }
12951 return L;
12952}
12953
12954/// Adjust the GVALinkage for a declaration based on what an external AST source
12955/// knows about whether there can be other definitions of this declaration.
12956static GVALinkage
12958 GVALinkage L) {
12959 ExternalASTSource *Source = Ctx.getExternalSource();
12960 if (!Source)
12961 return L;
12962
12963 switch (Source->hasExternalDefinitions(D)) {
12965 // Other translation units rely on us to provide the definition.
12966 if (L == GVA_DiscardableODR)
12967 return GVA_StrongODR;
12968 break;
12969
12972
12974 break;
12975 }
12976 return L;
12977}
12978
12984
12986 const VarDecl *VD) {
12987 // As an extension for interactive REPLs, make sure constant variables are
12988 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12989 // marking them as internal.
12990 if (Context.getLangOpts().CPlusPlus &&
12991 Context.getLangOpts().IncrementalExtensions &&
12992 VD->getType().isConstQualified() &&
12993 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12995 return GVA_DiscardableODR;
12996
12997 if (!VD->isExternallyVisible())
12998 return GVA_Internal;
12999
13000 if (VD->isStaticLocal()) {
13001 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13002 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13003 LexicalContext = LexicalContext->getLexicalParent();
13004
13005 // ObjC Blocks can create local variables that don't have a FunctionDecl
13006 // LexicalContext.
13007 if (!LexicalContext)
13008 return GVA_DiscardableODR;
13009
13010 // Otherwise, let the static local variable inherit its linkage from the
13011 // nearest enclosing function.
13012 auto StaticLocalLinkage =
13013 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13014
13015 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13016 // be emitted in any object with references to the symbol for the object it
13017 // contains, whether inline or out-of-line."
13018 // Similar behavior is observed with MSVC. An alternative ABI could use
13019 // StrongODR/AvailableExternally to match the function, but none are
13020 // known/supported currently.
13021 if (StaticLocalLinkage == GVA_StrongODR ||
13022 StaticLocalLinkage == GVA_AvailableExternally)
13023 return GVA_DiscardableODR;
13024 return StaticLocalLinkage;
13025 }
13026
13027 // MSVC treats in-class initialized static data members as definitions.
13028 // By giving them non-strong linkage, out-of-line definitions won't
13029 // cause link errors.
13030 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13031 return GVA_DiscardableODR;
13032
13033 // Most non-template variables have strong linkage; inline variables are
13034 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13035 GVALinkage StrongLinkage;
13036 switch (Context.getInlineVariableDefinitionKind(VD)) {
13038 StrongLinkage = GVA_StrongExternal;
13039 break;
13042 StrongLinkage = GVA_DiscardableODR;
13043 break;
13045 StrongLinkage = GVA_StrongODR;
13046 break;
13047 }
13048
13049 switch (VD->getTemplateSpecializationKind()) {
13050 case TSK_Undeclared:
13051 return StrongLinkage;
13052
13054 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13055 VD->isStaticDataMember()
13057 : StrongLinkage;
13058
13060 return GVA_StrongODR;
13061
13064
13066 return GVA_DiscardableODR;
13067 }
13068
13069 llvm_unreachable("Invalid Linkage!");
13070}
13071
13077
13079 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13080 if (!VD->isFileVarDecl())
13081 return false;
13082 // Global named register variables (GNU extension) are never emitted.
13083 if (VD->getStorageClass() == SC_Register)
13084 return false;
13085 if (VD->getDescribedVarTemplate() ||
13087 return false;
13088 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13089 // We never need to emit an uninstantiated function template.
13090 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13091 return false;
13092 } else if (isa<PragmaCommentDecl>(D))
13093 return true;
13095 return true;
13096 else if (isa<OMPRequiresDecl>(D))
13097 return true;
13098 else if (isa<OMPThreadPrivateDecl>(D))
13099 return !D->getDeclContext()->isDependentContext();
13100 else if (isa<OMPAllocateDecl>(D))
13101 return !D->getDeclContext()->isDependentContext();
13103 return !D->getDeclContext()->isDependentContext();
13104 else if (isa<ImportDecl>(D))
13105 return true;
13106 else
13107 return false;
13108
13109 // If this is a member of a class template, we do not need to emit it.
13111 return false;
13112
13113 // Weak references don't produce any output by themselves.
13114 if (D->hasAttr<WeakRefAttr>())
13115 return false;
13116
13117 // SYCL device compilation requires that functions defined with the
13118 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13119 // other entities are emitted only if they are used by a function
13120 // defined with one of those attributes.
13121 if (LangOpts.SYCLIsDevice)
13122 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13123 D->hasAttr<SYCLExternalAttr>());
13124
13125 // Aliases and used decls are required.
13126 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13127 return true;
13128
13129 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13130 // Forward declarations aren't required.
13131 if (!FD->doesThisDeclarationHaveABody())
13132 return FD->doesDeclarationForceExternallyVisibleDefinition();
13133
13134 // Constructors and destructors are required.
13135 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13136 return true;
13137
13138 // The key function for a class is required. This rule only comes
13139 // into play when inline functions can be key functions, though.
13140 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13141 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13142 const CXXRecordDecl *RD = MD->getParent();
13143 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13144 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13145 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13146 return true;
13147 }
13148 }
13149 }
13150
13152
13153 // static, static inline, always_inline, and extern inline functions can
13154 // always be deferred. Normal inline functions can be deferred in C99/C++.
13155 // Implicit template instantiations can also be deferred in C++.
13157 }
13158
13159 const auto *VD = cast<VarDecl>(D);
13160 assert(VD->isFileVarDecl() && "Expected file scoped var");
13161
13162 // If the decl is marked as `declare target to`, it should be emitted for the
13163 // host and for the device.
13164 if (LangOpts.OpenMP &&
13165 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13166 return true;
13167
13168 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13170 return false;
13171
13172 if (VD->shouldEmitInExternalSource())
13173 return false;
13174
13175 // Variables that can be needed in other TUs are required.
13178 return true;
13179
13180 // We never need to emit a variable that is available in another TU.
13182 return false;
13183
13184 // Variables that have destruction with side-effects are required.
13185 if (VD->needsDestruction(*this))
13186 return true;
13187
13188 // Variables that have initialization with side-effects are required.
13189 if (VD->hasInitWithSideEffects())
13190 return true;
13191
13192 // Likewise, variables with tuple-like bindings are required if their
13193 // bindings have side-effects.
13194 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13195 for (const auto *BD : DD->flat_bindings())
13196 if (const auto *BindingVD = BD->getHoldingVar())
13197 if (DeclMustBeEmitted(BindingVD))
13198 return true;
13199 }
13200
13201 return false;
13202}
13203
13205 const FunctionDecl *FD,
13206 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13207 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13208 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13209 FD = FD->getMostRecentDecl();
13210 // FIXME: The order of traversal here matters and depends on the order of
13211 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13212 // shouldn't rely on that.
13213 for (auto *CurDecl :
13215 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13216 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13217 SeenDecls.insert(CurFD).second) {
13218 Pred(CurFD);
13219 }
13220 }
13221}
13222
13224 bool IsCXXMethod) const {
13225 // Pass through to the C++ ABI object
13226 if (IsCXXMethod)
13227 return ABI->getDefaultMethodCallConv(IsVariadic);
13228
13229 switch (LangOpts.getDefaultCallingConv()) {
13231 break;
13233 return CC_C;
13235 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13236 return CC_X86FastCall;
13237 break;
13239 if (!IsVariadic)
13240 return CC_X86StdCall;
13241 break;
13243 // __vectorcall cannot be applied to variadic functions.
13244 if (!IsVariadic)
13245 return CC_X86VectorCall;
13246 break;
13248 // __regcall cannot be applied to variadic functions.
13249 if (!IsVariadic)
13250 return CC_X86RegCall;
13251 break;
13253 if (!IsVariadic)
13254 return CC_M68kRTD;
13255 break;
13256 }
13257 return Target->getDefaultCallingConv();
13258}
13259
13261 // Pass through to the C++ ABI object
13262 return ABI->isNearlyEmpty(RD);
13263}
13264
13266 if (!VTContext) {
13267 auto ABI = Target->getCXXABI();
13268 if (ABI.isMicrosoft())
13269 VTContext.reset(new MicrosoftVTableContext(*this));
13270 else {
13271 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13274 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13275 }
13276 }
13277 return VTContext.get();
13278}
13279
13281 if (!T)
13282 T = Target;
13283 switch (T->getCXXABI().getKind()) {
13284 case TargetCXXABI::AppleARM64:
13285 case TargetCXXABI::Fuchsia:
13286 case TargetCXXABI::GenericAArch64:
13287 case TargetCXXABI::GenericItanium:
13288 case TargetCXXABI::GenericARM:
13289 case TargetCXXABI::GenericMIPS:
13290 case TargetCXXABI::iOS:
13291 case TargetCXXABI::WebAssembly:
13292 case TargetCXXABI::WatchOS:
13293 case TargetCXXABI::XL:
13295 case TargetCXXABI::Microsoft:
13297 }
13298 llvm_unreachable("Unsupported ABI");
13299}
13300
13302 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13303 "Device mangle context does not support Microsoft mangling.");
13304 switch (T.getCXXABI().getKind()) {
13305 case TargetCXXABI::AppleARM64:
13306 case TargetCXXABI::Fuchsia:
13307 case TargetCXXABI::GenericAArch64:
13308 case TargetCXXABI::GenericItanium:
13309 case TargetCXXABI::GenericARM:
13310 case TargetCXXABI::GenericMIPS:
13311 case TargetCXXABI::iOS:
13312 case TargetCXXABI::WebAssembly:
13313 case TargetCXXABI::WatchOS:
13314 case TargetCXXABI::XL:
13316 *this, getDiagnostics(),
13317 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13318 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13319 return RD->getDeviceLambdaManglingNumber();
13320 return std::nullopt;
13321 },
13322 /*IsAux=*/true);
13323 case TargetCXXABI::Microsoft:
13325 /*IsAux=*/true);
13326 }
13327 llvm_unreachable("Unsupported ABI");
13328}
13329
13330CXXABI::~CXXABI() = default;
13331
13333 return ASTRecordLayouts.getMemorySize() +
13334 llvm::capacity_in_bytes(ObjCLayouts) +
13335 llvm::capacity_in_bytes(KeyFunctions) +
13336 llvm::capacity_in_bytes(ObjCImpls) +
13337 llvm::capacity_in_bytes(BlockVarCopyInits) +
13338 llvm::capacity_in_bytes(DeclAttrs) +
13339 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13340 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13341 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13342 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13343 llvm::capacity_in_bytes(OverriddenMethods) +
13344 llvm::capacity_in_bytes(Types) +
13345 llvm::capacity_in_bytes(VariableArrayTypes);
13346}
13347
13348/// getIntTypeForBitwidth -
13349/// sets integer QualTy according to specified details:
13350/// bitwidth, signed/unsigned.
13351/// Returns empty type if there is no appropriate target types.
13353 unsigned Signed) const {
13355 CanQualType QualTy = getFromTargetType(Ty);
13356 if (!QualTy && DestWidth == 128)
13357 return Signed ? Int128Ty : UnsignedInt128Ty;
13358 return QualTy;
13359}
13360
13361/// getRealTypeForBitwidth -
13362/// sets floating point QualTy according to specified bitwidth.
13363/// Returns empty type if there is no appropriate target types.
13365 FloatModeKind ExplicitType) const {
13366 FloatModeKind Ty =
13367 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13368 switch (Ty) {
13370 return HalfTy;
13372 return FloatTy;
13374 return DoubleTy;
13376 return LongDoubleTy;
13378 return Float128Ty;
13380 return Ibm128Ty;
13382 return {};
13383 }
13384
13385 llvm_unreachable("Unhandled TargetInfo::RealType value");
13386}
13387
13388void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13389 if (Number <= 1)
13390 return;
13391
13392 MangleNumbers[ND] = Number;
13393
13394 if (Listener)
13395 Listener->AddedManglingNumber(ND, Number);
13396}
13397
13399 bool ForAuxTarget) const {
13400 auto I = MangleNumbers.find(ND);
13401 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13402 // CUDA/HIP host compilation encodes host and device mangling numbers
13403 // as lower and upper half of 32 bit integer.
13404 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13405 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13406 } else {
13407 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13408 "number for aux target");
13409 }
13410 return Res > 1 ? Res : 1;
13411}
13412
13413void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13414 if (Number <= 1)
13415 return;
13416
13417 StaticLocalNumbers[VD] = Number;
13418
13419 if (Listener)
13420 Listener->AddedStaticLocalNumbers(VD, Number);
13421}
13422
13424 auto I = StaticLocalNumbers.find(VD);
13425 return I != StaticLocalNumbers.end() ? I->second : 1;
13426}
13427
13429 bool IsDestroying) {
13430 if (!IsDestroying) {
13431 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13432 return;
13433 }
13434 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13435}
13436
13438 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13439}
13440
13442 bool IsTypeAware) {
13443 if (!IsTypeAware) {
13444 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13445 return;
13446 }
13447 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13448}
13449
13451 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13452}
13453
13456 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13457 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13458 if (!MCtx)
13460 return *MCtx;
13461}
13462
13465 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13466 std::unique_ptr<MangleNumberingContext> &MCtx =
13467 ExtraMangleNumberingContexts[D];
13468 if (!MCtx)
13470 return *MCtx;
13471}
13472
13473std::unique_ptr<MangleNumberingContext>
13475 return ABI->createMangleNumberingContext();
13476}
13477
13478const CXXConstructorDecl *
13480 return ABI->getCopyConstructorForExceptionObject(
13482}
13483
13485 CXXConstructorDecl *CD) {
13486 return ABI->addCopyConstructorForExceptionObject(
13489}
13490
13492 TypedefNameDecl *DD) {
13493 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13494}
13495
13498 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13499}
13500
13502 DeclaratorDecl *DD) {
13503 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13504}
13505
13507 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13508}
13509
13511 ParamIndices[D] = index;
13512}
13513
13515 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13516 assert(I != ParamIndices.end() &&
13517 "ParmIndices lacks entry set by ParmVarDecl");
13518 return I->second;
13519}
13520
13522 unsigned Length) const {
13523 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13524 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13525 EltTy = EltTy.withConst();
13526
13527 EltTy = adjustStringLiteralBaseType(EltTy);
13528
13529 // Get an array type for the string, according to C99 6.4.5. This includes
13530 // the null terminator character.
13531 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13532 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13533}
13534
13537 StringLiteral *&Result = StringLiteralCache[Key];
13538 if (!Result)
13540 *this, Key, StringLiteralKind::Ordinary,
13541 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13542 SourceLocation());
13543 return Result;
13544}
13545
13546MSGuidDecl *
13548 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13549
13550 llvm::FoldingSetNodeID ID;
13551 MSGuidDecl::Profile(ID, Parts);
13552
13553 void *InsertPos;
13554 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13555 return Existing;
13556
13557 QualType GUIDType = getMSGuidType().withConst();
13558 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13559 MSGuidDecls.InsertNode(New, InsertPos);
13560 return New;
13561}
13562
13565 const APValue &APVal) const {
13566 llvm::FoldingSetNodeID ID;
13568
13569 void *InsertPos;
13570 if (UnnamedGlobalConstantDecl *Existing =
13571 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13572 return Existing;
13573
13575 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13576 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13577 return New;
13578}
13579
13582 assert(T->isRecordType() && "template param object of unexpected type");
13583
13584 // C++ [temp.param]p8:
13585 // [...] a static storage duration object of type 'const T' [...]
13586 T.addConst();
13587
13588 llvm::FoldingSetNodeID ID;
13590
13591 void *InsertPos;
13592 if (TemplateParamObjectDecl *Existing =
13593 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13594 return Existing;
13595
13596 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13597 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13598 return New;
13599}
13600
13602 const llvm::Triple &T = getTargetInfo().getTriple();
13603 if (!T.isOSDarwin())
13604 return false;
13605
13606 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13607 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13608 return false;
13609
13610 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13611 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13612 uint64_t Size = sizeChars.getQuantity();
13613 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13614 unsigned Align = alignChars.getQuantity();
13615 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13616 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13617}
13618
13619bool
13621 const ObjCMethodDecl *MethodImpl) {
13622 // No point trying to match an unavailable/deprecated mothod.
13623 if (MethodDecl->hasAttr<UnavailableAttr>()
13624 || MethodDecl->hasAttr<DeprecatedAttr>())
13625 return false;
13626 if (MethodDecl->getObjCDeclQualifier() !=
13627 MethodImpl->getObjCDeclQualifier())
13628 return false;
13629 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13630 return false;
13631
13632 if (MethodDecl->param_size() != MethodImpl->param_size())
13633 return false;
13634
13635 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13636 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13637 EF = MethodDecl->param_end();
13638 IM != EM && IF != EF; ++IM, ++IF) {
13639 const ParmVarDecl *DeclVar = (*IF);
13640 const ParmVarDecl *ImplVar = (*IM);
13641 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13642 return false;
13643 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13644 return false;
13645 }
13646
13647 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13648}
13649
13651 LangAS AS;
13653 AS = LangAS::Default;
13654 else
13655 AS = QT->getPointeeType().getAddressSpace();
13656
13658}
13659
13662}
13663
13664bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13665 if (X == Y)
13666 return true;
13667 if (!X || !Y)
13668 return false;
13669 llvm::FoldingSetNodeID IDX, IDY;
13670 X->Profile(IDX, *this, /*Canonical=*/true);
13671 Y->Profile(IDY, *this, /*Canonical=*/true);
13672 return IDX == IDY;
13673}
13674
13675// The getCommon* helpers return, for given 'same' X and Y entities given as
13676// inputs, another entity which is also the 'same' as the inputs, but which
13677// is closer to the canonical form of the inputs, each according to a given
13678// criteria.
13679// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13680// the regular ones.
13681
13683 if (!declaresSameEntity(X, Y))
13684 return nullptr;
13685 for (const Decl *DX : X->redecls()) {
13686 // If we reach Y before reaching the first decl, that means X is older.
13687 if (DX == Y)
13688 return X;
13689 // If we reach the first decl, then Y is older.
13690 if (DX->isFirstDecl())
13691 return Y;
13692 }
13693 llvm_unreachable("Corrupt redecls chain");
13694}
13695
13696template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13697static T *getCommonDecl(T *X, T *Y) {
13698 return cast_or_null<T>(
13699 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13700 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13701}
13702
13703template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13704static T *getCommonDeclChecked(T *X, T *Y) {
13705 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13706 const_cast<Decl *>(cast<Decl>(Y))));
13707}
13708
13710 TemplateName Y,
13711 bool IgnoreDeduced = false) {
13712 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13713 return X;
13714 // FIXME: There are cases here where we could find a common template name
13715 // with more sugar. For example one could be a SubstTemplateTemplate*
13716 // replacing the other.
13717 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13718 if (CX.getAsVoidPointer() !=
13720 return TemplateName();
13721 return CX;
13722}
13723
13726 bool IgnoreDeduced) {
13727 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13728 assert(R.getAsVoidPointer() != nullptr);
13729 return R;
13730}
13731
13733 ArrayRef<QualType> Ys, bool Unqualified = false) {
13734 assert(Xs.size() == Ys.size());
13735 SmallVector<QualType, 8> Rs(Xs.size());
13736 for (size_t I = 0; I < Rs.size(); ++I)
13737 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13738 return Rs;
13739}
13740
13741template <class T>
13742static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13743 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13744 : SourceLocation();
13745}
13746
13748 const TemplateArgument &X,
13749 const TemplateArgument &Y) {
13750 if (X.getKind() != Y.getKind())
13751 return TemplateArgument();
13752
13753 switch (X.getKind()) {
13755 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13756 return TemplateArgument();
13757 return TemplateArgument(
13758 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13760 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13761 return TemplateArgument();
13762 return TemplateArgument(
13763 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13764 /*Unqualified=*/true);
13766 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13767 return TemplateArgument();
13768 // FIXME: Try to keep the common sugar.
13769 return X;
13771 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13772 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13773 if (!CTN.getAsVoidPointer())
13774 return TemplateArgument();
13775 return TemplateArgument(CTN);
13776 }
13778 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13780 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13781 if (!CTN.getAsVoidPointer())
13782 return TemplateName();
13783 auto NExpX = X.getNumTemplateExpansions();
13784 assert(NExpX == Y.getNumTemplateExpansions());
13785 return TemplateArgument(CTN, NExpX);
13786 }
13787 default:
13788 // FIXME: Handle the other argument kinds.
13789 return X;
13790 }
13791}
13792
13797 if (Xs.size() != Ys.size())
13798 return true;
13799 R.resize(Xs.size());
13800 for (size_t I = 0; I < R.size(); ++I) {
13801 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13802 if (R[I].isNull())
13803 return true;
13804 }
13805 return false;
13806}
13807
13812 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13813 assert(!Different);
13814 (void)Different;
13815 return R;
13816}
13817
13818template <class T>
13820 bool IsSame) {
13821 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13822 if (KX == KY)
13823 return KX;
13825 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13826 return KX;
13827}
13828
13829/// Returns a NestedNameSpecifier which has only the common sugar
13830/// present in both NNS1 and NNS2.
13833 NestedNameSpecifier NNS2, bool IsSame) {
13834 // If they are identical, all sugar is common.
13835 if (NNS1 == NNS2)
13836 return NNS1;
13837
13838 // IsSame implies both Qualifiers are equivalent.
13839 NestedNameSpecifier Canon = NNS1.getCanonical();
13840 if (Canon != NNS2.getCanonical()) {
13841 assert(!IsSame && "Should be the same NestedNameSpecifier");
13842 // If they are not the same, there is nothing to unify.
13843 return std::nullopt;
13844 }
13845
13846 NestedNameSpecifier R = std::nullopt;
13847 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13848 assert(Kind == NNS2.getKind());
13849 switch (Kind) {
13851 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13852 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13853 auto Kind = Namespace1->getKind();
13854 if (Kind != Namespace2->getKind() ||
13855 (Kind == Decl::NamespaceAlias &&
13856 !declaresSameEntity(Namespace1, Namespace2))) {
13858 Ctx,
13859 ::getCommonDeclChecked(Namespace1->getNamespace(),
13860 Namespace2->getNamespace()),
13861 /*Prefix=*/std::nullopt);
13862 break;
13863 }
13864 // The prefixes for namespaces are not significant, its declaration
13865 // identifies it uniquely.
13866 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13867 /*IsSame=*/false);
13868 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13869 Prefix);
13870 break;
13871 }
13873 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13874 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13875 /*Unqualified=*/true)
13876 .getTypePtr();
13878 break;
13879 }
13881 // FIXME: Can __super even be used with data members?
13882 // If it's only usable in functions, we will never see it here,
13883 // unless we save the qualifiers used in function types.
13884 // In that case, it might be possible NNS2 is a type,
13885 // in which case we should degrade the result to
13886 // a CXXRecordType.
13888 NNS2.getAsMicrosoftSuper()));
13889 break;
13890 }
13893 // These are singletons.
13894 llvm_unreachable("singletons did not compare equal");
13895 }
13896 assert(R.getCanonical() == Canon);
13897 return R;
13898}
13899
13900template <class T>
13902 const T *Y, bool IsSame) {
13903 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13904}
13905
13906template <class T>
13907static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13908 const T *Y) {
13909 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13910}
13911
13912template <class T>
13914 Qualifiers &QX, const T *Y,
13915 Qualifiers &QY) {
13916 QualType EX = X->getElementType(), EY = Y->getElementType();
13917 QualType R = Ctx.getCommonSugaredType(EX, EY,
13918 /*Unqualified=*/true);
13919 // Qualifiers common to both element types.
13920 Qualifiers RQ = R.getQualifiers();
13921 // For each side, move to the top level any qualifiers which are not common to
13922 // both element types. The caller must assume top level qualifiers might
13923 // be different, even if they are the same type, and can be treated as sugar.
13924 QX += EX.getQualifiers() - RQ;
13925 QY += EY.getQualifiers() - RQ;
13926 return R;
13927}
13928
13929template <class T>
13930static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13931 const T *Y) {
13932 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13933}
13934
13935template <class T>
13936static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13937 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13938 return X->getSizeExpr();
13939}
13940
13941static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13942 assert(X->getSizeModifier() == Y->getSizeModifier());
13943 return X->getSizeModifier();
13944}
13945
13947 const ArrayType *Y) {
13948 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13949 return X->getIndexTypeCVRQualifiers();
13950}
13951
13952// Merges two type lists such that the resulting vector will contain
13953// each type (in a canonical sense) only once, in the order they appear
13954// from X to Y. If they occur in both X and Y, the result will contain
13955// the common sugared type between them.
13956static void mergeTypeLists(const ASTContext &Ctx,
13959 llvm::DenseMap<QualType, unsigned> Found;
13960 for (auto Ts : {X, Y}) {
13961 for (QualType T : Ts) {
13962 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13963 if (!Res.second) {
13964 QualType &U = Out[Res.first->second];
13965 U = Ctx.getCommonSugaredType(U, T);
13966 } else {
13967 Out.emplace_back(T);
13968 }
13969 }
13970 }
13971}
13972
13973FunctionProtoType::ExceptionSpecInfo
13976 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13977 bool AcceptDependent) const {
13978 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13979
13980 // If either of them can throw anything, that is the result.
13981 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13982 if (EST1 == I)
13983 return ESI1;
13984 if (EST2 == I)
13985 return ESI2;
13986 }
13987
13988 // If either of them is non-throwing, the result is the other.
13989 for (auto I :
13991 if (EST1 == I)
13992 return ESI2;
13993 if (EST2 == I)
13994 return ESI1;
13995 }
13996
13997 // If we're left with value-dependent computed noexcept expressions, we're
13998 // stuck. Before C++17, we can just drop the exception specification entirely,
13999 // since it's not actually part of the canonical type. And this should never
14000 // happen in C++17, because it would mean we were computing the composite
14001 // pointer type of dependent types, which should never happen.
14002 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14003 assert(AcceptDependent &&
14004 "computing composite pointer type of dependent types");
14006 }
14007
14008 // Switch over the possibilities so that people adding new values know to
14009 // update this function.
14010 switch (EST1) {
14011 case EST_None:
14012 case EST_DynamicNone:
14013 case EST_MSAny:
14014 case EST_BasicNoexcept:
14016 case EST_NoexceptFalse:
14017 case EST_NoexceptTrue:
14018 case EST_NoThrow:
14019 llvm_unreachable("These ESTs should be handled above");
14020
14021 case EST_Dynamic: {
14022 // This is the fun case: both exception specifications are dynamic. Form
14023 // the union of the two lists.
14024 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14025 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14026 ESI2.Exceptions);
14028 Result.Exceptions = ExceptionTypeStorage;
14029 return Result;
14030 }
14031
14032 case EST_Unevaluated:
14033 case EST_Uninstantiated:
14034 case EST_Unparsed:
14035 llvm_unreachable("shouldn't see unresolved exception specifications here");
14036 }
14037
14038 llvm_unreachable("invalid ExceptionSpecificationType");
14039}
14040
14042 Qualifiers &QX, const Type *Y,
14043 Qualifiers &QY) {
14044 Type::TypeClass TC = X->getTypeClass();
14045 assert(TC == Y->getTypeClass());
14046 switch (TC) {
14047#define UNEXPECTED_TYPE(Class, Kind) \
14048 case Type::Class: \
14049 llvm_unreachable("Unexpected " Kind ": " #Class);
14050
14051#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14052#define TYPE(Class, Base)
14053#include "clang/AST/TypeNodes.inc"
14054
14055#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14057 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14058 SUGAR_FREE_TYPE(DependentBitInt)
14060 SUGAR_FREE_TYPE(ObjCInterface)
14061 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14062 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14063 SUGAR_FREE_TYPE(UnresolvedUsing)
14064 SUGAR_FREE_TYPE(HLSLAttributedResource)
14065 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14066#undef SUGAR_FREE_TYPE
14067#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14068 NON_UNIQUE_TYPE(TypeOfExpr)
14069 NON_UNIQUE_TYPE(VariableArray)
14070#undef NON_UNIQUE_TYPE
14071
14072 UNEXPECTED_TYPE(TypeOf, "sugar")
14073
14074#undef UNEXPECTED_TYPE
14075
14076 case Type::Auto: {
14077 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14078 assert(AX->getDeducedType().isNull());
14079 assert(AY->getDeducedType().isNull());
14080 assert(AX->getKeyword() == AY->getKeyword());
14081 assert(AX->isInstantiationDependentType() ==
14082 AY->isInstantiationDependentType());
14083 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14084 AY->getTypeConstraintArguments());
14085 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14087 AX->containsUnexpandedParameterPack(),
14088 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14089 AY->getTypeConstraintConcept()),
14090 As);
14091 }
14092 case Type::IncompleteArray: {
14093 const auto *AX = cast<IncompleteArrayType>(X),
14095 return Ctx.getIncompleteArrayType(
14096 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14098 }
14099 case Type::DependentSizedArray: {
14100 const auto *AX = cast<DependentSizedArrayType>(X),
14102 return Ctx.getDependentSizedArrayType(
14103 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14104 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14106 }
14107 case Type::ConstantArray: {
14108 const auto *AX = cast<ConstantArrayType>(X),
14109 *AY = cast<ConstantArrayType>(Y);
14110 assert(AX->getSize() == AY->getSize());
14111 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14112 ? AX->getSizeExpr()
14113 : nullptr;
14114 return Ctx.getConstantArrayType(
14115 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14117 }
14118 case Type::ArrayParameter: {
14119 const auto *AX = cast<ArrayParameterType>(X),
14120 *AY = cast<ArrayParameterType>(Y);
14121 assert(AX->getSize() == AY->getSize());
14122 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14123 ? AX->getSizeExpr()
14124 : nullptr;
14125 auto ArrayTy = Ctx.getConstantArrayType(
14126 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14128 return Ctx.getArrayParameterType(ArrayTy);
14129 }
14130 case Type::Atomic: {
14131 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14132 return Ctx.getAtomicType(
14133 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14134 }
14135 case Type::Complex: {
14136 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14137 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14138 }
14139 case Type::Pointer: {
14140 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14141 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14142 }
14143 case Type::BlockPointer: {
14144 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14145 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14146 }
14147 case Type::ObjCObjectPointer: {
14148 const auto *PX = cast<ObjCObjectPointerType>(X),
14150 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14151 }
14152 case Type::MemberPointer: {
14153 const auto *PX = cast<MemberPointerType>(X),
14154 *PY = cast<MemberPointerType>(Y);
14155 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14156 PY->getMostRecentCXXRecordDecl()));
14157 return Ctx.getMemberPointerType(
14158 getCommonPointeeType(Ctx, PX, PY),
14159 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14160 PX->getMostRecentCXXRecordDecl());
14161 }
14162 case Type::LValueReference: {
14163 const auto *PX = cast<LValueReferenceType>(X),
14165 // FIXME: Preserve PointeeTypeAsWritten.
14166 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14167 PX->isSpelledAsLValue() ||
14168 PY->isSpelledAsLValue());
14169 }
14170 case Type::RValueReference: {
14171 const auto *PX = cast<RValueReferenceType>(X),
14173 // FIXME: Preserve PointeeTypeAsWritten.
14174 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14175 }
14176 case Type::DependentAddressSpace: {
14177 const auto *PX = cast<DependentAddressSpaceType>(X),
14179 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14180 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14181 PX->getAddrSpaceExpr(),
14182 getCommonAttrLoc(PX, PY));
14183 }
14184 case Type::FunctionNoProto: {
14185 const auto *FX = cast<FunctionNoProtoType>(X),
14187 assert(FX->getExtInfo() == FY->getExtInfo());
14188 return Ctx.getFunctionNoProtoType(
14189 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14190 FX->getExtInfo());
14191 }
14192 case Type::FunctionProto: {
14193 const auto *FX = cast<FunctionProtoType>(X),
14194 *FY = cast<FunctionProtoType>(Y);
14195 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14196 EPIY = FY->getExtProtoInfo();
14197 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14198 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14199 assert(!EPIX.ExtParameterInfos ||
14200 llvm::equal(
14201 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14202 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14203 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14204 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14205 assert(EPIX.Variadic == EPIY.Variadic);
14206
14207 // FIXME: Can we handle an empty EllipsisLoc?
14208 // Use emtpy EllipsisLoc if X and Y differ.
14209
14210 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14211
14212 QualType R =
14213 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14214 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14215 /*Unqualified=*/true);
14216
14217 SmallVector<QualType, 8> Exceptions;
14219 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14220 return Ctx.getFunctionType(R, P, EPIX);
14221 }
14222 case Type::ObjCObject: {
14223 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14224 assert(
14225 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14226 OY->getProtocols().begin(), OY->getProtocols().end(),
14227 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14228 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14229 }) &&
14230 "protocol lists must be the same");
14231 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14232 OY->getTypeArgsAsWritten());
14233 return Ctx.getObjCObjectType(
14234 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14235 OX->getProtocols(),
14236 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14237 }
14238 case Type::ConstantMatrix: {
14239 const auto *MX = cast<ConstantMatrixType>(X),
14240 *MY = cast<ConstantMatrixType>(Y);
14241 assert(MX->getNumRows() == MY->getNumRows());
14242 assert(MX->getNumColumns() == MY->getNumColumns());
14243 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14244 MX->getNumRows(), MX->getNumColumns());
14245 }
14246 case Type::DependentSizedMatrix: {
14247 const auto *MX = cast<DependentSizedMatrixType>(X),
14249 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14250 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14251 return Ctx.getDependentSizedMatrixType(
14252 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14253 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14254 }
14255 case Type::Vector: {
14256 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14257 assert(VX->getNumElements() == VY->getNumElements());
14258 assert(VX->getVectorKind() == VY->getVectorKind());
14259 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14260 VX->getNumElements(), VX->getVectorKind());
14261 }
14262 case Type::ExtVector: {
14263 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14264 assert(VX->getNumElements() == VY->getNumElements());
14265 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14266 VX->getNumElements());
14267 }
14268 case Type::DependentSizedExtVector: {
14269 const auto *VX = cast<DependentSizedExtVectorType>(X),
14272 getCommonSizeExpr(Ctx, VX, VY),
14273 getCommonAttrLoc(VX, VY));
14274 }
14275 case Type::DependentVector: {
14276 const auto *VX = cast<DependentVectorType>(X),
14278 assert(VX->getVectorKind() == VY->getVectorKind());
14279 return Ctx.getDependentVectorType(
14280 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14281 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14282 }
14283 case Type::Enum:
14284 case Type::Record:
14285 case Type::InjectedClassName: {
14286 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14287 return Ctx.getTagType(
14288 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14289 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14290 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14291 /*OwnedTag=*/false);
14292 }
14293 case Type::TemplateSpecialization: {
14294 const auto *TX = cast<TemplateSpecializationType>(X),
14296 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14297 TY->template_arguments());
14299 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14300 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14301 TY->getTemplateName(),
14302 /*IgnoreDeduced=*/true),
14303 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14304 }
14305 case Type::Decltype: {
14306 const auto *DX = cast<DecltypeType>(X);
14307 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14308 assert(DX->isDependentType());
14309 assert(DY->isDependentType());
14310 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14311 // As Decltype is not uniqued, building a common type would be wasteful.
14312 return QualType(DX, 0);
14313 }
14314 case Type::PackIndexing: {
14315 const auto *DX = cast<PackIndexingType>(X);
14316 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14317 assert(DX->isDependentType());
14318 assert(DY->isDependentType());
14319 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14320 return QualType(DX, 0);
14321 }
14322 case Type::DependentName: {
14323 const auto *NX = cast<DependentNameType>(X),
14324 *NY = cast<DependentNameType>(Y);
14325 assert(NX->getIdentifier() == NY->getIdentifier());
14326 return Ctx.getDependentNameType(
14327 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14328 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14329 }
14330 case Type::DependentTemplateSpecialization: {
14333 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14334 TY->template_arguments());
14335 const DependentTemplateStorage &SX = TX->getDependentTemplateName(),
14336 &SY = TY->getDependentTemplateName();
14337 assert(SX.getName() == SY.getName());
14339 getCommonNNS(Ctx, SX.getQualifier(), SY.getQualifier(),
14340 /*IsSame=*/true),
14341 SX.getName(), SX.hasTemplateKeyword() || SY.hasTemplateKeyword());
14343 getCommonTypeKeyword(TX, TY, /*IsSame=*/true), Name, As);
14344 }
14345 case Type::UnaryTransform: {
14346 const auto *TX = cast<UnaryTransformType>(X),
14347 *TY = cast<UnaryTransformType>(Y);
14348 assert(TX->getUTTKind() == TY->getUTTKind());
14349 return Ctx.getUnaryTransformType(
14350 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14351 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14352 TY->getUnderlyingType()),
14353 TX->getUTTKind());
14354 }
14355 case Type::PackExpansion: {
14356 const auto *PX = cast<PackExpansionType>(X),
14357 *PY = cast<PackExpansionType>(Y);
14358 assert(PX->getNumExpansions() == PY->getNumExpansions());
14359 return Ctx.getPackExpansionType(
14360 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14361 PX->getNumExpansions(), false);
14362 }
14363 case Type::Pipe: {
14364 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14365 assert(PX->isReadOnly() == PY->isReadOnly());
14366 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14368 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14369 }
14370 case Type::TemplateTypeParm: {
14371 const auto *TX = cast<TemplateTypeParmType>(X),
14373 assert(TX->getDepth() == TY->getDepth());
14374 assert(TX->getIndex() == TY->getIndex());
14375 assert(TX->isParameterPack() == TY->isParameterPack());
14376 return Ctx.getTemplateTypeParmType(
14377 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14378 getCommonDecl(TX->getDecl(), TY->getDecl()));
14379 }
14380 }
14381 llvm_unreachable("Unknown Type Class");
14382}
14383
14385 const Type *Y,
14386 SplitQualType Underlying) {
14387 Type::TypeClass TC = X->getTypeClass();
14388 if (TC != Y->getTypeClass())
14389 return QualType();
14390 switch (TC) {
14391#define UNEXPECTED_TYPE(Class, Kind) \
14392 case Type::Class: \
14393 llvm_unreachable("Unexpected " Kind ": " #Class);
14394#define TYPE(Class, Base)
14395#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14396#include "clang/AST/TypeNodes.inc"
14397
14398#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14401 CANONICAL_TYPE(BlockPointer)
14404 CANONICAL_TYPE(ConstantArray)
14405 CANONICAL_TYPE(ArrayParameter)
14406 CANONICAL_TYPE(ConstantMatrix)
14408 CANONICAL_TYPE(ExtVector)
14409 CANONICAL_TYPE(FunctionNoProto)
14410 CANONICAL_TYPE(FunctionProto)
14411 CANONICAL_TYPE(IncompleteArray)
14412 CANONICAL_TYPE(HLSLAttributedResource)
14413 CANONICAL_TYPE(HLSLInlineSpirv)
14414 CANONICAL_TYPE(LValueReference)
14415 CANONICAL_TYPE(ObjCInterface)
14416 CANONICAL_TYPE(ObjCObject)
14417 CANONICAL_TYPE(ObjCObjectPointer)
14421 CANONICAL_TYPE(RValueReference)
14422 CANONICAL_TYPE(VariableArray)
14424#undef CANONICAL_TYPE
14425
14426#undef UNEXPECTED_TYPE
14427
14428 case Type::Adjusted: {
14429 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14430 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14431 if (!Ctx.hasSameType(OX, OY))
14432 return QualType();
14433 // FIXME: It's inefficient to have to unify the original types.
14434 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14435 Ctx.getQualifiedType(Underlying));
14436 }
14437 case Type::Decayed: {
14438 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14439 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14440 if (!Ctx.hasSameType(OX, OY))
14441 return QualType();
14442 // FIXME: It's inefficient to have to unify the original types.
14443 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14444 Ctx.getQualifiedType(Underlying));
14445 }
14446 case Type::Attributed: {
14447 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14448 AttributedType::Kind Kind = AX->getAttrKind();
14449 if (Kind != AY->getAttrKind())
14450 return QualType();
14451 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14452 if (!Ctx.hasSameType(MX, MY))
14453 return QualType();
14454 // FIXME: It's inefficient to have to unify the modified types.
14455 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14456 Ctx.getQualifiedType(Underlying),
14457 AX->getAttr());
14458 }
14459 case Type::BTFTagAttributed: {
14460 const auto *BX = cast<BTFTagAttributedType>(X);
14461 const BTFTypeTagAttr *AX = BX->getAttr();
14462 // The attribute is not uniqued, so just compare the tag.
14463 if (AX->getBTFTypeTag() !=
14464 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14465 return QualType();
14466 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14467 }
14468 case Type::Auto: {
14469 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14470
14471 AutoTypeKeyword KW = AX->getKeyword();
14472 if (KW != AY->getKeyword())
14473 return QualType();
14474
14475 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14476 AY->getTypeConstraintConcept());
14478 if (CD &&
14479 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14480 AY->getTypeConstraintArguments())) {
14481 CD = nullptr; // The arguments differ, so make it unconstrained.
14482 As.clear();
14483 }
14484
14485 // Both auto types can't be dependent, otherwise they wouldn't have been
14486 // sugar. This implies they can't contain unexpanded packs either.
14487 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14488 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14489 }
14490 case Type::PackIndexing:
14491 case Type::Decltype:
14492 return QualType();
14493 case Type::DeducedTemplateSpecialization:
14494 // FIXME: Try to merge these.
14495 return QualType();
14496 case Type::MacroQualified: {
14497 const auto *MX = cast<MacroQualifiedType>(X),
14498 *MY = cast<MacroQualifiedType>(Y);
14499 const IdentifierInfo *IX = MX->getMacroIdentifier();
14500 if (IX != MY->getMacroIdentifier())
14501 return QualType();
14502 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14503 }
14504 case Type::SubstTemplateTypeParm: {
14505 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14507 Decl *CD =
14508 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14509 if (!CD)
14510 return QualType();
14511 unsigned Index = SX->getIndex();
14512 if (Index != SY->getIndex())
14513 return QualType();
14514 auto PackIndex = SX->getPackIndex();
14515 if (PackIndex != SY->getPackIndex())
14516 return QualType();
14517 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14518 CD, Index, PackIndex,
14519 SX->getFinal() && SY->getFinal());
14520 }
14521 case Type::ObjCTypeParam:
14522 // FIXME: Try to merge these.
14523 return QualType();
14524 case Type::Paren:
14525 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14526
14527 case Type::TemplateSpecialization: {
14528 const auto *TX = cast<TemplateSpecializationType>(X),
14530 TemplateName CTN =
14531 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14532 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14533 if (!CTN.getAsVoidPointer())
14534 return QualType();
14536 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14537 TY->template_arguments()))
14538 return QualType();
14540 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14541 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14542 }
14543 case Type::Typedef: {
14544 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14545 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14546 if (!CD)
14547 return QualType();
14548 return Ctx.getTypedefType(
14549 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14550 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14551 Ctx.getQualifiedType(Underlying));
14552 }
14553 case Type::TypeOf: {
14554 // The common sugar between two typeof expressions, where one is
14555 // potentially a typeof_unqual and the other is not, we unify to the
14556 // qualified type as that retains the most information along with the type.
14557 // We only return a typeof_unqual type when both types are unqual types.
14562 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14563 }
14564 case Type::TypeOfExpr:
14565 return QualType();
14566
14567 case Type::UnaryTransform: {
14568 const auto *UX = cast<UnaryTransformType>(X),
14569 *UY = cast<UnaryTransformType>(Y);
14570 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14571 if (KX != UY->getUTTKind())
14572 return QualType();
14573 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14574 if (!Ctx.hasSameType(BX, BY))
14575 return QualType();
14576 // FIXME: It's inefficient to have to unify the base types.
14577 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14578 Ctx.getQualifiedType(Underlying), KX);
14579 }
14580 case Type::Using: {
14581 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14582 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14583 if (!CD)
14584 return QualType();
14585 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14586 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14587 CD, Ctx.getQualifiedType(Underlying));
14588 }
14589 case Type::MemberPointer: {
14590 const auto *PX = cast<MemberPointerType>(X),
14591 *PY = cast<MemberPointerType>(Y);
14592 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14593 assert(Cls == PY->getMostRecentCXXRecordDecl());
14594 return Ctx.getMemberPointerType(
14595 ::getCommonPointeeType(Ctx, PX, PY),
14596 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14597 }
14598 case Type::CountAttributed: {
14599 const auto *DX = cast<CountAttributedType>(X),
14601 if (DX->isCountInBytes() != DY->isCountInBytes())
14602 return QualType();
14603 if (DX->isOrNull() != DY->isOrNull())
14604 return QualType();
14605 Expr *CEX = DX->getCountExpr();
14606 Expr *CEY = DY->getCountExpr();
14607 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14608 if (Ctx.hasSameExpr(CEX, CEY))
14609 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14610 DX->isCountInBytes(), DX->isOrNull(),
14611 CDX);
14612 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14613 return QualType();
14614 // Two declarations with the same integer constant may still differ in their
14615 // expression pointers, so we need to evaluate them.
14616 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14617 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14618 if (VX != VY)
14619 return QualType();
14620 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14621 DX->isCountInBytes(), DX->isOrNull(),
14622 CDX);
14623 }
14624 case Type::PredefinedSugar:
14625 assert(cast<PredefinedSugarType>(X)->getKind() !=
14627 return QualType();
14628 }
14629 llvm_unreachable("Unhandled Type Class");
14630}
14631
14632static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14634 while (true) {
14635 QTotal.addConsistentQualifiers(T.Quals);
14636 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14637 if (NT == QualType(T.Ty, 0))
14638 break;
14639 R.push_back(T);
14640 T = NT.split();
14641 }
14642 return R;
14643}
14644
14646 bool Unqualified) const {
14647 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14648 if (X == Y)
14649 return X;
14650 if (!Unqualified) {
14651 if (X.isCanonical())
14652 return X;
14653 if (Y.isCanonical())
14654 return Y;
14655 }
14656
14657 SplitQualType SX = X.split(), SY = Y.split();
14658 Qualifiers QX, QY;
14659 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14660 // until we reach their underlying "canonical nodes". Note these are not
14661 // necessarily canonical types, as they may still have sugared properties.
14662 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14663 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14664
14665 // If this is an ArrayType, the element qualifiers are interchangeable with
14666 // the top level qualifiers.
14667 // * In case the canonical nodes are the same, the elements types are already
14668 // the same.
14669 // * Otherwise, the element types will be made the same, and any different
14670 // element qualifiers will be moved up to the top level qualifiers, per
14671 // 'getCommonArrayElementType'.
14672 // In both cases, this means there may be top level qualifiers which differ
14673 // between X and Y. If so, these differing qualifiers are redundant with the
14674 // element qualifiers, and can be removed without changing the canonical type.
14675 // The desired behaviour is the same as for the 'Unqualified' case here:
14676 // treat the redundant qualifiers as sugar, remove the ones which are not
14677 // common to both sides.
14678 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14679
14680 if (SX.Ty != SY.Ty) {
14681 // The canonical nodes differ. Build a common canonical node out of the two,
14682 // unifying their sugar. This may recurse back here.
14683 SX.Ty =
14684 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14685 } else {
14686 // The canonical nodes were identical: We may have desugared too much.
14687 // Add any common sugar back in.
14688 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14689 QX -= SX.Quals;
14690 QY -= SY.Quals;
14691 SX = Xs.pop_back_val();
14692 SY = Ys.pop_back_val();
14693 }
14694 }
14695 if (KeepCommonQualifiers)
14697 else
14698 assert(QX == QY);
14699
14700 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14701 // related. Walk up these nodes, unifying them and adding the result.
14702 while (!Xs.empty() && !Ys.empty()) {
14703 auto Underlying = SplitQualType(
14704 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14705 SX = Xs.pop_back_val();
14706 SY = Ys.pop_back_val();
14707 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14709 // Stop at the first pair which is unrelated.
14710 if (!SX.Ty) {
14711 SX.Ty = Underlying.Ty;
14712 break;
14713 }
14714 QX -= Underlying.Quals;
14715 };
14716
14717 // Add back the missing accumulated qualifiers, which were stripped off
14718 // with the sugar nodes we could not unify.
14719 QualType R = getQualifiedType(SX.Ty, QX);
14720 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14721 return R;
14722}
14723
14725 assert(Ty->isFixedPointType());
14726
14728 return Ty;
14729
14730 switch (Ty->castAs<BuiltinType>()->getKind()) {
14731 default:
14732 llvm_unreachable("Not a saturated fixed point type!");
14733 case BuiltinType::SatShortAccum:
14734 return ShortAccumTy;
14735 case BuiltinType::SatAccum:
14736 return AccumTy;
14737 case BuiltinType::SatLongAccum:
14738 return LongAccumTy;
14739 case BuiltinType::SatUShortAccum:
14740 return UnsignedShortAccumTy;
14741 case BuiltinType::SatUAccum:
14742 return UnsignedAccumTy;
14743 case BuiltinType::SatULongAccum:
14744 return UnsignedLongAccumTy;
14745 case BuiltinType::SatShortFract:
14746 return ShortFractTy;
14747 case BuiltinType::SatFract:
14748 return FractTy;
14749 case BuiltinType::SatLongFract:
14750 return LongFractTy;
14751 case BuiltinType::SatUShortFract:
14752 return UnsignedShortFractTy;
14753 case BuiltinType::SatUFract:
14754 return UnsignedFractTy;
14755 case BuiltinType::SatULongFract:
14756 return UnsignedLongFractTy;
14757 }
14758}
14759
14761 assert(Ty->isFixedPointType());
14762
14763 if (Ty->isSaturatedFixedPointType()) return Ty;
14764
14765 switch (Ty->castAs<BuiltinType>()->getKind()) {
14766 default:
14767 llvm_unreachable("Not a fixed point type!");
14768 case BuiltinType::ShortAccum:
14769 return SatShortAccumTy;
14770 case BuiltinType::Accum:
14771 return SatAccumTy;
14772 case BuiltinType::LongAccum:
14773 return SatLongAccumTy;
14774 case BuiltinType::UShortAccum:
14776 case BuiltinType::UAccum:
14777 return SatUnsignedAccumTy;
14778 case BuiltinType::ULongAccum:
14780 case BuiltinType::ShortFract:
14781 return SatShortFractTy;
14782 case BuiltinType::Fract:
14783 return SatFractTy;
14784 case BuiltinType::LongFract:
14785 return SatLongFractTy;
14786 case BuiltinType::UShortFract:
14788 case BuiltinType::UFract:
14789 return SatUnsignedFractTy;
14790 case BuiltinType::ULongFract:
14792 }
14793}
14794
14796 if (LangOpts.OpenCL)
14798
14799 if (LangOpts.CUDA)
14801
14802 return getLangASFromTargetAS(AS);
14803}
14804
14805// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14806// doesn't include ASTContext.h
14807template
14809 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14811 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14812 const clang::ASTContext &Ctx, Decl *Value);
14813
14815 assert(Ty->isFixedPointType());
14816
14817 const TargetInfo &Target = getTargetInfo();
14818 switch (Ty->castAs<BuiltinType>()->getKind()) {
14819 default:
14820 llvm_unreachable("Not a fixed point type!");
14821 case BuiltinType::ShortAccum:
14822 case BuiltinType::SatShortAccum:
14823 return Target.getShortAccumScale();
14824 case BuiltinType::Accum:
14825 case BuiltinType::SatAccum:
14826 return Target.getAccumScale();
14827 case BuiltinType::LongAccum:
14828 case BuiltinType::SatLongAccum:
14829 return Target.getLongAccumScale();
14830 case BuiltinType::UShortAccum:
14831 case BuiltinType::SatUShortAccum:
14832 return Target.getUnsignedShortAccumScale();
14833 case BuiltinType::UAccum:
14834 case BuiltinType::SatUAccum:
14835 return Target.getUnsignedAccumScale();
14836 case BuiltinType::ULongAccum:
14837 case BuiltinType::SatULongAccum:
14838 return Target.getUnsignedLongAccumScale();
14839 case BuiltinType::ShortFract:
14840 case BuiltinType::SatShortFract:
14841 return Target.getShortFractScale();
14842 case BuiltinType::Fract:
14843 case BuiltinType::SatFract:
14844 return Target.getFractScale();
14845 case BuiltinType::LongFract:
14846 case BuiltinType::SatLongFract:
14847 return Target.getLongFractScale();
14848 case BuiltinType::UShortFract:
14849 case BuiltinType::SatUShortFract:
14850 return Target.getUnsignedShortFractScale();
14851 case BuiltinType::UFract:
14852 case BuiltinType::SatUFract:
14853 return Target.getUnsignedFractScale();
14854 case BuiltinType::ULongFract:
14855 case BuiltinType::SatULongFract:
14856 return Target.getUnsignedLongFractScale();
14857 }
14858}
14859
14861 assert(Ty->isFixedPointType());
14862
14863 const TargetInfo &Target = getTargetInfo();
14864 switch (Ty->castAs<BuiltinType>()->getKind()) {
14865 default:
14866 llvm_unreachable("Not a fixed point type!");
14867 case BuiltinType::ShortAccum:
14868 case BuiltinType::SatShortAccum:
14869 return Target.getShortAccumIBits();
14870 case BuiltinType::Accum:
14871 case BuiltinType::SatAccum:
14872 return Target.getAccumIBits();
14873 case BuiltinType::LongAccum:
14874 case BuiltinType::SatLongAccum:
14875 return Target.getLongAccumIBits();
14876 case BuiltinType::UShortAccum:
14877 case BuiltinType::SatUShortAccum:
14878 return Target.getUnsignedShortAccumIBits();
14879 case BuiltinType::UAccum:
14880 case BuiltinType::SatUAccum:
14881 return Target.getUnsignedAccumIBits();
14882 case BuiltinType::ULongAccum:
14883 case BuiltinType::SatULongAccum:
14884 return Target.getUnsignedLongAccumIBits();
14885 case BuiltinType::ShortFract:
14886 case BuiltinType::SatShortFract:
14887 case BuiltinType::Fract:
14888 case BuiltinType::SatFract:
14889 case BuiltinType::LongFract:
14890 case BuiltinType::SatLongFract:
14891 case BuiltinType::UShortFract:
14892 case BuiltinType::SatUShortFract:
14893 case BuiltinType::UFract:
14894 case BuiltinType::SatUFract:
14895 case BuiltinType::ULongFract:
14896 case BuiltinType::SatULongFract:
14897 return 0;
14898 }
14899}
14900
14901llvm::FixedPointSemantics
14903 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14904 "Can only get the fixed point semantics for a "
14905 "fixed point or integer type.");
14906 if (Ty->isIntegerType())
14907 return llvm::FixedPointSemantics::GetIntegerSemantics(
14908 getIntWidth(Ty), Ty->isSignedIntegerType());
14909
14910 bool isSigned = Ty->isSignedFixedPointType();
14911 return llvm::FixedPointSemantics(
14912 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14914 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14915}
14916
14917llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14918 assert(Ty->isFixedPointType());
14919 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14920}
14921
14922llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14923 assert(Ty->isFixedPointType());
14924 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14925}
14926
14928 assert(Ty->isUnsignedFixedPointType() &&
14929 "Expected unsigned fixed point type");
14930
14931 switch (Ty->castAs<BuiltinType>()->getKind()) {
14932 case BuiltinType::UShortAccum:
14933 return ShortAccumTy;
14934 case BuiltinType::UAccum:
14935 return AccumTy;
14936 case BuiltinType::ULongAccum:
14937 return LongAccumTy;
14938 case BuiltinType::SatUShortAccum:
14939 return SatShortAccumTy;
14940 case BuiltinType::SatUAccum:
14941 return SatAccumTy;
14942 case BuiltinType::SatULongAccum:
14943 return SatLongAccumTy;
14944 case BuiltinType::UShortFract:
14945 return ShortFractTy;
14946 case BuiltinType::UFract:
14947 return FractTy;
14948 case BuiltinType::ULongFract:
14949 return LongFractTy;
14950 case BuiltinType::SatUShortFract:
14951 return SatShortFractTy;
14952 case BuiltinType::SatUFract:
14953 return SatFractTy;
14954 case BuiltinType::SatULongFract:
14955 return SatLongFractTy;
14956 default:
14957 llvm_unreachable("Unexpected unsigned fixed point type");
14958 }
14959}
14960
14961// Given a list of FMV features, return a concatenated list of the
14962// corresponding backend features (which may contain duplicates).
14963static std::vector<std::string> getFMVBackendFeaturesFor(
14964 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14965 std::vector<std::string> BackendFeats;
14966 llvm::AArch64::ExtensionSet FeatureBits;
14967 for (StringRef F : FMVFeatStrings)
14968 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14969 if (FMVExt->ID)
14970 FeatureBits.enable(*FMVExt->ID);
14971 FeatureBits.toLLVMFeatureList(BackendFeats);
14972 return BackendFeats;
14973}
14974
14975ParsedTargetAttr
14976ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14977 assert(TD != nullptr);
14978 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14979
14980 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14981 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14982 });
14983 return ParsedAttr;
14984}
14985
14986void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14987 const FunctionDecl *FD) const {
14988 if (FD)
14989 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14990 else
14991 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14992 Target->getTargetOpts().CPU,
14993 Target->getTargetOpts().Features);
14994}
14995
14996// Fills in the supplied string map with the set of target features for the
14997// passed in function.
14998void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14999 GlobalDecl GD) const {
15000 StringRef TargetCPU = Target->getTargetOpts().CPU;
15001 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15002 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15004
15005 // Make a copy of the features as passed on the command line into the
15006 // beginning of the additional features from the function to override.
15007 // AArch64 handles command line option features in parseTargetAttr().
15008 if (!Target->getTriple().isAArch64())
15009 ParsedAttr.Features.insert(
15010 ParsedAttr.Features.begin(),
15011 Target->getTargetOpts().FeaturesAsWritten.begin(),
15012 Target->getTargetOpts().FeaturesAsWritten.end());
15013
15014 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15015 TargetCPU = ParsedAttr.CPU;
15016
15017 // Now populate the feature map, first with the TargetCPU which is either
15018 // the default or a new one from the target attribute string. Then we'll use
15019 // the passed in features (FeaturesAsWritten) along with the new ones from
15020 // the attribute.
15021 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15022 ParsedAttr.Features);
15023 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15025 Target->getCPUSpecificCPUDispatchFeatures(
15026 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15027 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15028 Features.insert(Features.begin(),
15029 Target->getTargetOpts().FeaturesAsWritten.begin(),
15030 Target->getTargetOpts().FeaturesAsWritten.end());
15031 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15032 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15033 if (Target->getTriple().isAArch64()) {
15035 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15036 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15037 Features.insert(Features.begin(),
15038 Target->getTargetOpts().FeaturesAsWritten.begin(),
15039 Target->getTargetOpts().FeaturesAsWritten.end());
15040 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15041 } else if (Target->getTriple().isRISCV()) {
15042 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15043 std::vector<std::string> Features;
15044 if (VersionStr != "default") {
15045 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15046 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15047 ParsedAttr.Features.end());
15048 }
15049 Features.insert(Features.begin(),
15050 Target->getTargetOpts().FeaturesAsWritten.begin(),
15051 Target->getTargetOpts().FeaturesAsWritten.end());
15052 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15053 } else {
15054 std::vector<std::string> Features;
15055 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15056 if (VersionStr.starts_with("arch="))
15057 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15058 else if (VersionStr != "default")
15059 Features.push_back((StringRef{"+"} + VersionStr).str());
15060 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15061 }
15062 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15063 std::vector<std::string> Features;
15064 if (Target->getTriple().isRISCV()) {
15065 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15066 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15067 ParsedAttr.Features.end());
15068 } else {
15069 assert(Target->getTriple().isAArch64());
15071 TV->getFeatures(Feats);
15072 Features = getFMVBackendFeaturesFor(Feats);
15073 }
15074 Features.insert(Features.begin(),
15075 Target->getTargetOpts().FeaturesAsWritten.begin(),
15076 Target->getTargetOpts().FeaturesAsWritten.end());
15077 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15078 } else {
15079 FeatureMap = Target->getTargetOpts().FeatureMap;
15080 }
15081}
15082
15084 CanQualType KernelNameType,
15085 const FunctionDecl *FD) {
15086 // Host and device compilation may use different ABIs and different ABIs
15087 // may allocate name mangling discriminators differently. A discriminator
15088 // override is used to ensure consistent discriminator allocation across
15089 // host and device compilation.
15090 auto DeviceDiscriminatorOverrider =
15091 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15092 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15093 if (RD->isLambda())
15094 return RD->getDeviceLambdaManglingNumber();
15095 return std::nullopt;
15096 };
15097 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15098 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15099
15100 // Construct a mangled name for the SYCL kernel caller offload entry point.
15101 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15102 // name the SYCL kernel caller offload entry point function. This mangling
15103 // does not suffice to clearly identify symbols that correspond to SYCL
15104 // kernel caller functions, nor is this mangling natural for targets that
15105 // use a non-Itanium ABI.
15106 std::string Buffer;
15107 Buffer.reserve(128);
15108 llvm::raw_string_ostream Out(Buffer);
15109 MC->mangleCanonicalTypeName(KernelNameType, Out);
15110 std::string KernelName = Out.str();
15111
15112 return {KernelNameType, FD, KernelName};
15113}
15114
15116 // If the function declaration to register is invalid or dependent, the
15117 // registration attempt is ignored.
15118 if (FD->isInvalidDecl() || FD->isTemplated())
15119 return;
15120
15121 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15122 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15123
15124 // Be tolerant of multiple registration attempts so long as each attempt
15125 // is for the same entity. Callers are obligated to detect and diagnose
15126 // conflicting kernel names prior to calling this function.
15127 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15128 auto IT = SYCLKernels.find(KernelNameType);
15129 assert((IT == SYCLKernels.end() ||
15130 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15131 "SYCL kernel name conflict");
15132 (void)IT;
15133 SYCLKernels.insert(std::make_pair(
15134 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15135}
15136
15138 CanQualType KernelNameType = getCanonicalType(T);
15139 return SYCLKernels.at(KernelNameType);
15140}
15141
15143 CanQualType KernelNameType = getCanonicalType(T);
15144 auto IT = SYCLKernels.find(KernelNameType);
15145 if (IT != SYCLKernels.end())
15146 return &IT->second;
15147 return nullptr;
15148}
15149
15151 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15152 return *OMPTraitInfoVector.back();
15153}
15154
15157 const ASTContext::SectionInfo &Section) {
15158 if (Section.Decl)
15159 return DB << Section.Decl;
15160 return DB << "a prior #pragma section";
15161}
15162
15163bool ASTContext::mayExternalize(const Decl *D) const {
15164 bool IsInternalVar =
15165 isa<VarDecl>(D) &&
15167 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15168 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15169 (D->hasAttr<CUDAConstantAttr>() &&
15170 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15171 // CUDA/HIP: managed variables need to be externalized since it is
15172 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15173 // anonymous name space needs to be externalized to avoid duplicate symbols.
15174 return (IsInternalVar &&
15175 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15176 (D->hasAttr<CUDAGlobalAttr>() &&
15178 GVA_Internal);
15179}
15180
15182 return mayExternalize(D) &&
15183 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15185}
15186
15187StringRef ASTContext::getCUIDHash() const {
15188 if (!CUIDHash.empty())
15189 return CUIDHash;
15190 if (LangOpts.CUID.empty())
15191 return StringRef();
15192 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15193 return CUIDHash;
15194}
15195
15196const CXXRecordDecl *
15198 assert(ThisClass);
15199 assert(ThisClass->isPolymorphic());
15200 const CXXRecordDecl *PrimaryBase = ThisClass;
15201 while (1) {
15202 assert(PrimaryBase);
15203 assert(PrimaryBase->isPolymorphic());
15204 auto &Layout = getASTRecordLayout(PrimaryBase);
15205 auto Base = Layout.getPrimaryBase();
15206 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15207 break;
15208 PrimaryBase = Base;
15209 }
15210 return PrimaryBase;
15211}
15212
15214 StringRef MangledName) {
15215 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15216 assert(Method->isVirtual());
15217 bool DefaultIncludesPointerAuth =
15218 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15219
15220 if (!DefaultIncludesPointerAuth)
15221 return true;
15222
15223 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15224 if (Existing != ThunksToBeAbbreviated.end())
15225 return Existing->second.contains(MangledName.str());
15226
15227 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15228 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15229 auto VtableContext = getVTableContext();
15230 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15231 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15232 for (const auto &Thunk : *ThunkInfos) {
15233 SmallString<256> ElidedName;
15234 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15235 if (Destructor)
15236 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15237 Thunk, /* elideOverrideInfo */ true,
15238 ElidedNameStream);
15239 else
15240 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15241 ElidedNameStream);
15242 SmallString<256> MangledName;
15243 llvm::raw_svector_ostream mangledNameStream(MangledName);
15244 if (Destructor)
15245 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15246 Thunk, /* elideOverrideInfo */ false,
15247 mangledNameStream);
15248 else
15249 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15250 mangledNameStream);
15251
15252 Thunks[ElidedName].push_back(std::string(MangledName));
15253 }
15254 }
15255 llvm::StringSet<> SimplifiedThunkNames;
15256 for (auto &ThunkList : Thunks) {
15257 llvm::sort(ThunkList.second);
15258 SimplifiedThunkNames.insert(ThunkList.second[0]);
15259 }
15260 bool Result = SimplifiedThunkNames.contains(MangledName);
15261 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15262 return Result;
15263}
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 getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
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 const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
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 bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
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 NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
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)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
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
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
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 bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > 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 uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
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)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:422
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
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.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
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:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
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.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
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.
CanQualType AccumTy
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
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
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.
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.
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
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.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:956
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ 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
CanQualType SatUnsignedFractTy
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 areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
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 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:744
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) 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.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
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.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
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 getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
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,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:745
CanQualType FloatTy
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
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 ...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
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.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
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
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.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
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.
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
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
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
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
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...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
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.
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...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
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
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
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
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...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition ASTContext.h:742
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:894
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:741
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:927
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
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
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...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
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
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
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
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
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.
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
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
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
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
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:523
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
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,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:743
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
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.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
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:930
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
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.
friend class NestedNameSpecifier
Definition ASTContext.h:189
void PrintStats() const
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.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
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
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:746
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) 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
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.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
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:793
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
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.
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.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:515
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
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".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
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.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
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.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:936
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:814
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
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.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
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 ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
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
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
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...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
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
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...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
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.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
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.
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
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
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 hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
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)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
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
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:859
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
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
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
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:952
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
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...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
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.
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:943
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.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
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.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
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.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
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.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
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...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
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
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
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.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
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/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3507
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3526
Represents a loop initializing the elements of an array.
Definition Expr.h:5904
llvm::APInt getArraySize() const
Definition Expr.h:5926
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5924
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3908
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3738
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3752
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3756
QualType getElementType() const
Definition TypeBase.h:3750
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3760
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:6816
Expr * getPtr() const
Definition Expr.h:6847
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8147
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8195
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8212
unsigned getNumBits() const
Definition TypeBase.h:8207
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4634
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6560
Pointer to a block type.
Definition TypeBase.h:3558
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3575
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 TypeBase.h:3182
Kind getKind() const
Definition TypeBase.h:3230
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3398
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
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 TypeBase.h:3293
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3308
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:205
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:199
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3776
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3872
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3832
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3891
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3852
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4389
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4410
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4427
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4407
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4418
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3454
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3490
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3541
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1272
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
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:319
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:779
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4077
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4099
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8240
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4027
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4056
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4117
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4142
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4448
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4468
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6227
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6232
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4243
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4268
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:904
Represents an enum.
Definition Decl.h:4004
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4111
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3078
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4164
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:833
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3053
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:4001
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1717
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1764
ExtVectorType - Extended vector type.
Definition TypeBase.h:4283
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:246
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5416
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
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:4641
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:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3832
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2409
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
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:4019
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5250
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5686
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5724
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5082
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5116
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4860
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4876
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5282
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5786
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5589
unsigned getNumParams() const
Definition TypeBase.h:5560
QualType getParamType(unsigned i) const
Definition TypeBase.h:5562
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3991
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5567
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5755
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5751
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4589
CallingConv getCC() const
Definition TypeBase.h:4648
unsigned getRegParm() const
Definition TypeBase.h:4641
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4637
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4660
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4504
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4544
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4478
ExtInfo getExtInfo() const
Definition TypeBase.h:4834
QualType getReturnType() const
Definition TypeBase.h:4818
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
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.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5015
Represents a C array with an unspecified size.
Definition TypeBase.h:3925
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3942
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 TypeBase.h:3633
@ 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...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4392
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4429
MSGuidDeclParts Parts
Definition DeclCXX.h:4394
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6161
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
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 TypeBase.h:4367
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4374
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3669
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3712
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:316
bool isExternallyVisible() const
Definition Decl.h:432
Represent a C++ namespace.
Definition Decl.h:591
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3245
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
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:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
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:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7905
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:951
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
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 TypeBase.h:7961
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8042
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:958
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8036
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8118
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7998
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8019
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7973
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8013
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8080
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8025
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
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:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4357
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3320
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3334
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1789
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8178
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3346
QualType getPointeeType() const
Definition TypeBase.h:3356
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3361
PredefinedSugarKind Kind
Definition TypeBase.h:8254
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8427
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2871
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8474
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8432
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
QualType withConst() const
Definition TypeBase.h:1159
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8383
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8437
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8364
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8416
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8400
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8347
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
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:2994
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8375
Represents a template name as written in source code.
void Profile(llvm::FoldingSetNodeID &ID)
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8290
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:384
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:638
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:689
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:624
bool hasUnaligned() const
Definition TypeBase.h:511
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
unsigned getFastQualifiers() const
Definition TypeBase.h:619
void removeAddressSpace()
Definition TypeBase.h:596
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:455
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
void addObjCGCAttr(GC type)
Definition TypeBase.h:524
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3651
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:4309
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5125
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
RecordDecl * getMostRecentDecl()
Definition Decl.h:4335
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5166
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
bool field_empty() const
Definition Decl.h:4520
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3589
QualType getPointeeType() const
Definition TypeBase.h:3607
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3615
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.
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.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1801
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
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.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
TagTypeKind TagKind
Definition Decl.h:3719
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3945
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
TagKind getTagKind() const
Definition Decl.h:3908
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
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:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone 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.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
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.
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.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
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.
NamedDecl * getParam(unsigned Idx)
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.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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.
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, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:240
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
ConceptReference * getConceptReference() const
Definition ASTConcept.h:244
Represents a declaration of a type.
Definition Decl.h:3510
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:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:216
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6193
A container of type source information.
Definition TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8600
bool isVoidType() const
Definition TypeBase.h:8936
bool isObjCBuiltinType() const
Definition TypeBase.h:8800
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2682
bool isIncompleteArrayType() const
Definition TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2209
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8683
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2430
bool isArrayType() const
Definition TypeBase.h:8679
bool isCharType() const
Definition Type.cpp:2136
bool isPointerType() const
Definition TypeBase.h:8580
bool isArrayParameterType() const
Definition TypeBase.h:8695
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8980
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9226
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9020
bool isEnumeralType() const
Definition TypeBase.h:8711
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8770
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9054
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2917
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2808
bool isBitIntType() const
Definition TypeBase.h:8845
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2800
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8992
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9008
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2423
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3137
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2297
@ SizeT
The "size_t" type.
Definition TypeBase.h:2291
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2294
bool isObjCIdType() const
Definition TypeBase.h:8782
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9016
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9212
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2440
bool isFunctionType() const
Definition TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition TypeBase.h:8749
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9034
bool isVectorType() const
Definition TypeBase.h:8719
bool isObjCClassType() const
Definition TypeBase.h:8788
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2664
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2599
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2939
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:2257
bool isAnyPointerType() const
Definition TypeBase.h:8588
TypeClass getTypeClass() const
Definition TypeBase.h:2403
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9159
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8973
bool isRecordType() const
Definition TypeBase.h:8707
bool isObjCRetainableType() const
Definition Type.cpp:5336
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5066
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5629
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
QualType getUnderlyingType() const
Definition Decl.h:3614
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6137
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4449
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4477
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5998
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6035
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4031
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4096
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3786
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3457
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3358
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6075
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5449
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
bool hasInit() const
Definition Decl.cpp:2398
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:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
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:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3982
Expr * getSizeExpr() const
Definition TypeBase.h:3996
Represents a GCC generic vector type.
Definition TypeBase.h:4191
unsigned getNumElements() const
Definition TypeBase.h:4206
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4215
VectorKind getVectorKind() const
Definition TypeBase.h:4211
QualType getElementType() const
Definition TypeBase.h:4205
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
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
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
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 TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8478
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
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.
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.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ TypeAlignment
Definition TypeBase.h:76
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3735
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5911
@ Struct
The "struct" keyword.
Definition TypeBase.h:5908
@ Class
The "class" keyword.
Definition TypeBase.h:5917
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4161
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4170
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4158
@ Generic
not a target-specific vector type
Definition TypeBase.h:4152
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4176
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4179
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4173
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:144
@ None
The alignment was not explicit in code.
Definition ASTContext.h:146
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:155
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:149
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:152
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5881
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5886
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5902
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5883
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5892
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5889
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5895
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5899
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ 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)
unsigned long uint64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6606
Expr * getCopyExpr() const
Definition Expr.h:6613
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
ArrayRef< TemplateArgument > Args
Holds information about the various types of exception specification.
Definition TypeBase.h:5339
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5341
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5344
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5347
Extra information about a function prototype.
Definition TypeBase.h:5367
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5413
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5372
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5417
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5406
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3264
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:175
bool isAlignRequired()
Definition ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition ASTContext.h:161
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986
static bool isEqual(const FoldingSetNodeID &LHS, const FoldingSetNodeID &RHS)
static unsigned getHashValue(const FoldingSetNodeID &Val)