clang 23.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"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "llvm/ADT/APFixedPoint.h"
70#include "llvm/ADT/APInt.h"
71#include "llvm/ADT/APSInt.h"
72#include "llvm/ADT/ArrayRef.h"
73#include "llvm/ADT/DenseMap.h"
74#include "llvm/ADT/DenseSet.h"
75#include "llvm/ADT/FoldingSet.h"
76#include "llvm/ADT/PointerUnion.h"
77#include "llvm/ADT/STLExtras.h"
78#include "llvm/ADT/SmallPtrSet.h"
79#include "llvm/ADT/SmallVector.h"
80#include "llvm/ADT/StringExtras.h"
81#include "llvm/ADT/StringRef.h"
82#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
83#include "llvm/Support/Capacity.h"
84#include "llvm/Support/Casting.h"
85#include "llvm/Support/Compiler.h"
86#include "llvm/Support/ErrorHandling.h"
87#include "llvm/Support/MD5.h"
88#include "llvm/Support/MathExtras.h"
89#include "llvm/Support/SipHash.h"
90#include "llvm/Support/raw_ostream.h"
91#include "llvm/TargetParser/AArch64TargetParser.h"
92#include "llvm/TargetParser/Triple.h"
93#include <algorithm>
94#include <cassert>
95#include <cstddef>
96#include <cstdint>
97#include <cstdlib>
98#include <map>
99#include <memory>
100#include <optional>
101#include <string>
102#include <tuple>
103#include <utility>
104
105using namespace clang;
106
117
118/// \returns The locations that are relevant when searching for Doc comments
119/// related to \p D.
122 assert(D);
123
124 // User can not attach documentation to implicit declarations.
125 if (D->isImplicit())
126 return {};
127
128 // User can not attach documentation to implicit instantiations.
129 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
130 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
131 return {};
132 }
133
134 if (const auto *VD = dyn_cast<VarDecl>(D)) {
135 if (VD->isStaticDataMember() &&
136 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
137 return {};
138 }
139
140 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
141 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
142 return {};
143 }
144
145 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
146 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
147 if (TSK == TSK_ImplicitInstantiation ||
148 TSK == TSK_Undeclared)
149 return {};
150 }
151
152 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
153 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
154 return {};
155 }
156 if (const auto *TD = dyn_cast<TagDecl>(D)) {
157 // When tag declaration (but not definition!) is part of the
158 // decl-specifier-seq of some other declaration, it doesn't get comment
159 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
160 return {};
161 }
162 // TODO: handle comments for function parameters properly.
163 if (isa<ParmVarDecl>(D))
164 return {};
165
166 // TODO: we could look up template parameter documentation in the template
167 // documentation.
171 return {};
172
174 // Find declaration location.
175 // For Objective-C declarations we generally don't expect to have multiple
176 // declarators, thus use declaration starting location as the "declaration
177 // location".
178 // For all other declarations multiple declarators are used quite frequently,
179 // so we use the location of the identifier as the "declaration location".
180 SourceLocation BaseLocation;
184 // Allow association with Y across {} in `typedef struct X {} Y`.
186 BaseLocation = D->getBeginLoc();
187 else
188 BaseLocation = D->getLocation();
189
190 if (!D->getLocation().isMacroID()) {
191 Locations.emplace_back(BaseLocation);
192 } else {
193 const auto *DeclCtx = D->getDeclContext();
194
195 // When encountering definitions generated from a macro (that are not
196 // contained by another declaration in the macro) we need to try and find
197 // the comment at the location of the expansion but if there is no comment
198 // there we should retry to see if there is a comment inside the macro as
199 // well. To this end we return first BaseLocation to first look at the
200 // expansion site, the second value is the spelling location of the
201 // beginning of the declaration defined inside the macro.
202 if (!(DeclCtx &&
203 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
204 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
205 }
206
207 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
208 // we don't refer to the macro argument location at the expansion site (this
209 // can happen if the name's spelling is provided via macro argument), and
210 // always to the declaration itself.
211 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
212 }
213
214 return Locations;
215}
216
218 const Decl *D, const SourceLocation RepresentativeLocForDecl,
219 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
220 // If the declaration doesn't map directly to a location in a file, we
221 // can't find the comment.
222 if (RepresentativeLocForDecl.isInvalid() ||
223 !RepresentativeLocForDecl.isFileID())
224 return nullptr;
225
226 // If there are no comments anywhere, we won't find anything.
227 if (CommentsInTheFile.empty())
228 return nullptr;
229
230 // Decompose the location for the declaration and find the beginning of the
231 // file buffer.
232 const FileIDAndOffset DeclLocDecomp =
233 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
234
235 // Slow path.
236 auto OffsetCommentBehindDecl =
237 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
238
239 // First check whether we have a trailing comment.
240 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
241 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
242 if ((CommentBehindDecl->isDocumentation() ||
243 LangOpts.CommentOpts.ParseAllComments) &&
244 CommentBehindDecl->isTrailingComment() &&
247
248 // Check that Doxygen trailing comment comes after the declaration, starts
249 // on the same line and in the same file as the declaration.
250 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
251 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
252 OffsetCommentBehindDecl->first)) {
253 return CommentBehindDecl;
254 }
255 }
256 }
257
258 // The comment just after the declaration was not a trailing comment.
259 // Let's look at the previous comment.
260 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
261 return nullptr;
262
263 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
264 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
265
266 // Check that we actually have a non-member Doxygen comment.
267 if (!(CommentBeforeDecl->isDocumentation() ||
268 LangOpts.CommentOpts.ParseAllComments) ||
269 CommentBeforeDecl->isTrailingComment())
270 return nullptr;
271
272 // Decompose the end of the comment.
273 const unsigned CommentEndOffset =
274 Comments.getCommentEndOffset(CommentBeforeDecl);
275
276 // Get the corresponding buffer.
277 bool Invalid = false;
278 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
279 &Invalid).data();
280 if (Invalid)
281 return nullptr;
282
283 // Extract text between the comment and declaration.
284 StringRef Text(Buffer + CommentEndOffset,
285 DeclLocDecomp.second - CommentEndOffset);
286
287 // There should be no other declarations or preprocessor directives between
288 // comment and declaration.
289 if (Text.find_last_of(";{}#@") != StringRef::npos)
290 return nullptr;
291
292 return CommentBeforeDecl;
293}
294
296 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
297
298 for (const auto DeclLoc : DeclLocs) {
299 // If the declaration doesn't map directly to a location in a file, we
300 // can't find the comment.
301 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
302 continue;
303
305 ExternalSource->ReadComments();
306 CommentsLoaded = true;
307 }
308
309 if (Comments.empty())
310 continue;
311
312 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
313 if (!File.isValid())
314 continue;
315
316 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
317 if (!CommentsInThisFile || CommentsInThisFile->empty())
318 continue;
319
320 if (RawComment *Comment =
321 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
322 return Comment;
323 }
324
325 return nullptr;
326}
327
329 assert(LangOpts.RetainCommentsFromSystemHeaders ||
330 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
331 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
332}
333
335 const Decl *D,
336 const Decl **OriginalDecl) const {
337 if (!D) {
338 if (OriginalDecl)
339 OriginalDecl = nullptr;
340 return nullptr;
341 }
342
343 D = &adjustDeclToTemplate(*D);
344
345 // Any comment directly attached to D?
346 {
347 auto DeclComment = DeclRawComments.find(D);
348 if (DeclComment != DeclRawComments.end()) {
349 if (OriginalDecl)
350 *OriginalDecl = D;
351 return DeclComment->second;
352 }
353 }
354
355 // Any comment attached to any redeclaration of D?
356 const Decl *CanonicalD = D->getCanonicalDecl();
357 if (!CanonicalD)
358 return nullptr;
359
360 {
361 auto RedeclComment = RedeclChainComments.find(CanonicalD);
362 if (RedeclComment != RedeclChainComments.end()) {
363 if (OriginalDecl)
364 *OriginalDecl = RedeclComment->second;
365 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
366 assert(CommentAtRedecl != DeclRawComments.end() &&
367 "This decl is supposed to have comment attached.");
368 return CommentAtRedecl->second;
369 }
370 }
371
372 // Any redeclarations of D that we haven't checked for comments yet?
373 const Decl *LastCheckedRedecl = [&]() {
374 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
375 bool CanUseCommentlessCache = false;
376 if (LastChecked) {
377 for (auto *Redecl : CanonicalD->redecls()) {
378 if (Redecl == D) {
379 CanUseCommentlessCache = true;
380 break;
381 }
382 if (Redecl == LastChecked)
383 break;
384 }
385 }
386 // FIXME: This could be improved so that even if CanUseCommentlessCache
387 // is false, once we've traversed past CanonicalD we still skip ahead
388 // LastChecked.
389 return CanUseCommentlessCache ? LastChecked : nullptr;
390 }();
391
392 for (const Decl *Redecl : D->redecls()) {
393 assert(Redecl);
394 // Skip all redeclarations that have been checked previously.
395 if (LastCheckedRedecl) {
396 if (LastCheckedRedecl == Redecl) {
397 LastCheckedRedecl = nullptr;
398 }
399 continue;
400 }
401 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
402 if (RedeclComment) {
403 cacheRawCommentForDecl(*Redecl, *RedeclComment);
404 if (OriginalDecl)
405 *OriginalDecl = Redecl;
406 return RedeclComment;
407 }
408 CommentlessRedeclChains[CanonicalD] = Redecl;
409 }
410
411 if (OriginalDecl)
412 *OriginalDecl = nullptr;
413 return nullptr;
414}
415
417 const RawComment &Comment) const {
418 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
419 DeclRawComments.try_emplace(&OriginalD, &Comment);
420 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
421 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
422 CommentlessRedeclChains.erase(CanonicalDecl);
423}
424
425static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
427 const DeclContext *DC = ObjCMethod->getDeclContext();
428 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
429 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
430 if (!ID)
431 return;
432 // Add redeclared method here.
433 for (const auto *Ext : ID->known_extensions()) {
434 if (ObjCMethodDecl *RedeclaredMethod =
435 Ext->getMethod(ObjCMethod->getSelector(),
436 ObjCMethod->isInstanceMethod()))
437 Redeclared.push_back(RedeclaredMethod);
438 }
439 }
440}
441
443 const Preprocessor *PP) {
444 if (Comments.empty() || Decls.empty())
445 return;
446
447 FileID File;
448 for (const Decl *D : Decls) {
449 if (D->isInvalidDecl())
450 continue;
451
452 D = &adjustDeclToTemplate(*D);
453 SourceLocation Loc = D->getLocation();
454 if (Loc.isValid()) {
455 // See if there are any new comments that are not attached to a decl.
456 // The location doesn't have to be precise - we care only about the file.
457 File = SourceMgr.getDecomposedLoc(Loc).first;
458 break;
459 }
460 }
461
462 if (File.isInvalid())
463 return;
464
465 auto CommentsInThisFile = Comments.getCommentsInFile(File);
466 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
467 CommentsInThisFile->rbegin()->second->isAttached())
468 return;
469
470 // There is at least one comment not attached to a decl.
471 // Maybe it should be attached to one of Decls?
472 //
473 // Note that this way we pick up not only comments that precede the
474 // declaration, but also comments that *follow* the declaration -- thanks to
475 // the lookahead in the lexer: we've consumed the semicolon and looked
476 // ahead through comments.
477 for (const Decl *D : Decls) {
478 assert(D);
479 if (D->isInvalidDecl())
480 continue;
481
482 D = &adjustDeclToTemplate(*D);
483
484 if (DeclRawComments.count(D) > 0)
485 continue;
486
487 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
488
489 for (const auto DeclLoc : DeclLocs) {
490 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
491 continue;
492
493 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
494 D, DeclLoc, *CommentsInThisFile)) {
495 cacheRawCommentForDecl(*D, *DocComment);
496 comments::FullComment *FC = DocComment->parse(*this, PP, D);
497 ParsedComments[D->getCanonicalDecl()] = FC;
498 break;
499 }
500 }
501 }
502}
503
505 const Decl *D) const {
506 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
507 ThisDeclInfo->CommentDecl = D;
508 ThisDeclInfo->IsFilled = false;
509 ThisDeclInfo->fill();
510 ThisDeclInfo->CommentDecl = FC->getDecl();
511 if (!ThisDeclInfo->TemplateParameters)
512 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
514 new (*this) comments::FullComment(FC->getBlocks(),
515 ThisDeclInfo);
516 return CFC;
517}
518
521 return RC ? RC->parse(*this, nullptr, D) : nullptr;
522}
523
525 const Decl *D,
526 const Preprocessor *PP) const {
527 if (!D || D->isInvalidDecl())
528 return nullptr;
529 D = &adjustDeclToTemplate(*D);
530
531 const Decl *Canonical = D->getCanonicalDecl();
532 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
533 ParsedComments.find(Canonical);
534
535 if (Pos != ParsedComments.end()) {
536 if (Canonical != D) {
537 comments::FullComment *FC = Pos->second;
539 return CFC;
540 }
541 return Pos->second;
542 }
543
544 const Decl *OriginalDecl = nullptr;
545
546 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
547 if (!RC) {
550 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
551 if (OMD && OMD->isPropertyAccessor())
552 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
553 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
554 return cloneFullComment(FC, D);
555 if (OMD)
556 addRedeclaredMethods(OMD, Overridden);
557 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
558 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
559 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
560 return cloneFullComment(FC, D);
561 }
562 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
563 // Attach any tag type's documentation to its typedef if latter
564 // does not have one of its own.
565 QualType QT = TD->getUnderlyingType();
566 if (const auto *TT = QT->getAs<TagType>())
567 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
568 return cloneFullComment(FC, D);
569 }
570 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
571 while (IC->getSuperClass()) {
572 IC = IC->getSuperClass();
574 return cloneFullComment(FC, D);
575 }
576 }
577 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
578 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
580 return cloneFullComment(FC, D);
581 }
582 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
583 if (!(RD = RD->getDefinition()))
584 return nullptr;
585 // Check non-virtual bases.
586 for (const auto &I : RD->bases()) {
587 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
588 continue;
589 QualType Ty = I.getType();
590 if (Ty.isNull())
591 continue;
593 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
594 continue;
595
597 return cloneFullComment(FC, D);
598 }
599 }
600 // Check virtual bases.
601 for (const auto &I : RD->vbases()) {
602 if (I.getAccessSpecifier() != AS_public)
603 continue;
604 QualType Ty = I.getType();
605 if (Ty.isNull())
606 continue;
607 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
608 if (!(VirtualBase= VirtualBase->getDefinition()))
609 continue;
611 return cloneFullComment(FC, D);
612 }
613 }
614 }
615 return nullptr;
616 }
617
618 // If the RawComment was attached to other redeclaration of this Decl, we
619 // should parse the comment in context of that other Decl. This is important
620 // because comments can contain references to parameter names which can be
621 // different across redeclarations.
622 if (D != OriginalDecl && OriginalDecl)
623 return getCommentForDecl(OriginalDecl, PP);
624
625 comments::FullComment *FC = RC->parse(*this, PP, D);
626 ParsedComments[Canonical] = FC;
627 return FC;
628}
629
630void ASTContext::CanonicalTemplateTemplateParm::Profile(
631 llvm::FoldingSetNodeID &ID, const ASTContext &C,
633 ID.AddInteger(Parm->getDepth());
634 ID.AddInteger(Parm->getPosition());
635 ID.AddBoolean(Parm->isParameterPack());
636 ID.AddInteger(Parm->templateParameterKind());
637
639 ID.AddInteger(Params->size());
641 PEnd = Params->end();
642 P != PEnd; ++P) {
643 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
644 ID.AddInteger(0);
645 ID.AddBoolean(TTP->isParameterPack());
646 ID.AddInteger(
647 TTP->getNumExpansionParameters().toInternalRepresentation());
648 continue;
649 }
650
651 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
652 ID.AddInteger(1);
653 ID.AddBoolean(NTTP->isParameterPack());
654 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
655 .getAsOpaquePtr());
656 if (NTTP->isExpandedParameterPack()) {
657 ID.AddBoolean(true);
658 ID.AddInteger(NTTP->getNumExpansionTypes());
659 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
660 QualType T = NTTP->getExpansionType(I);
661 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
662 }
663 } else
664 ID.AddBoolean(false);
665 continue;
666 }
667
668 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
669 ID.AddInteger(2);
670 Profile(ID, C, TTP);
671 }
672}
673
674TemplateTemplateParmDecl *
676 TemplateTemplateParmDecl *TTP) const {
677 // Check if we already have a canonical template template parameter.
678 llvm::FoldingSetNodeID ID;
679 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
680 void *InsertPos = nullptr;
681 CanonicalTemplateTemplateParm *Canonical
682 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
683 if (Canonical)
684 return Canonical->getParam();
685
686 // Build a canonical template parameter list.
688 SmallVector<NamedDecl *, 4> CanonParams;
689 CanonParams.reserve(Params->size());
691 PEnd = Params->end();
692 P != PEnd; ++P) {
693 // Note that, per C++20 [temp.over.link]/6, when determining whether
694 // template-parameters are equivalent, constraints are ignored.
695 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
698 TTP->getDepth(), TTP->getIndex(), nullptr, false,
699 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
700 TTP->getNumExpansionParameters());
701 CanonParams.push_back(NewTTP);
702 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
703 QualType T = getUnconstrainedType(getCanonicalType(NTTP->getType()));
706 if (NTTP->isExpandedParameterPack()) {
707 SmallVector<QualType, 2> ExpandedTypes;
709 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
710 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
711 ExpandedTInfos.push_back(
712 getTrivialTypeSourceInfo(ExpandedTypes.back()));
713 }
714
718 NTTP->getDepth(),
719 NTTP->getPosition(), nullptr,
720 T,
721 TInfo,
722 ExpandedTypes,
723 ExpandedTInfos);
724 } else {
728 NTTP->getDepth(),
729 NTTP->getPosition(), nullptr,
730 T,
731 NTTP->isParameterPack(),
732 TInfo);
733 }
734 CanonParams.push_back(Param);
735 } else
736 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
738 }
739
742 TTP->getPosition(), TTP->isParameterPack(), nullptr,
744 /*Typename=*/false,
746 CanonParams, SourceLocation(),
747 /*RequiresClause=*/nullptr));
748
749 // Get the new insert position for the node we care about.
750 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
751 assert(!Canonical && "Shouldn't be in the map!");
752 (void)Canonical;
753
754 // Create the canonical template template parameter entry.
755 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
756 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
757 return CanonTTP;
758}
759
762 TemplateTemplateParmDecl *TTP) const {
763 llvm::FoldingSetNodeID ID;
764 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
765 void *InsertPos = nullptr;
766 CanonicalTemplateTemplateParm *Canonical =
767 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
768 return Canonical ? Canonical->getParam() : nullptr;
769}
770
773 TemplateTemplateParmDecl *CanonTTP) const {
774 llvm::FoldingSetNodeID ID;
775 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
776 void *InsertPos = nullptr;
777 if (auto *Existing =
778 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
779 return Existing->getParam();
780 CanonTemplateTemplateParms.InsertNode(
781 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
782 return CanonTTP;
783}
784
785/// For the purposes of overflow pattern exclusion, does this match the
786/// while(i--) pattern?
787static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
788 if (UO->getOpcode() != UO_PostDec)
789 return false;
790
791 if (!UO->getType()->isUnsignedIntegerType())
792 return false;
793
794 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
797 return false;
798
799 // all Parents (usually just one) must be a WhileStmt
800 return llvm::all_of(
802 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
803}
804
806 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
807 // ... like -1UL;
808 if (UO->getOpcode() == UO_Minus &&
809 getLangOpts().isOverflowPatternExcluded(
811 UO->isIntegerConstantExpr(*this)) {
812 return true;
813 }
814
815 if (matchesPostDecrInWhile(UO, *this))
816 return true;
817
818 return false;
819}
820
821/// Check if a type can have its sanitizer instrumentation elided based on its
822/// presence within an ignorelist.
824 const QualType &Ty) const {
825 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
826 return NoSanitizeL->containsType(Mask, TyName);
827}
828
830 auto Kind = getTargetInfo().getCXXABI().getKind();
831 return getLangOpts().CXXABI.value_or(Kind);
832}
833
834CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
835 if (!LangOpts.CPlusPlus) return nullptr;
836
837 switch (getCXXABIKind()) {
838 case TargetCXXABI::AppleARM64:
839 case TargetCXXABI::Fuchsia:
840 case TargetCXXABI::GenericARM: // Same as Itanium at this level
841 case TargetCXXABI::iOS:
842 case TargetCXXABI::WatchOS:
843 case TargetCXXABI::GenericAArch64:
844 case TargetCXXABI::GenericMIPS:
845 case TargetCXXABI::GenericItanium:
846 case TargetCXXABI::WebAssembly:
847 case TargetCXXABI::XL:
848 return CreateItaniumCXXABI(*this);
849 case TargetCXXABI::Microsoft:
850 return CreateMicrosoftCXXABI(*this);
851 }
852 llvm_unreachable("Invalid CXXABI type!");
853}
854
856 if (!InterpContext) {
857 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
858 }
859 return *InterpContext;
860}
861
863 if (!ParentMapCtx)
864 ParentMapCtx.reset(new ParentMapContext(*this));
865 return *ParentMapCtx;
866}
867
869 const LangOptions &LangOpts) {
870 switch (LangOpts.getAddressSpaceMapMangling()) {
872 return TI.useAddressSpaceMapMangling();
874 return true;
876 return false;
877 }
878 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
879}
880
882 IdentifierTable &idents, SelectorTable &sels,
884 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
885 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
886 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
887 DependentSizedMatrixTypes(this_()),
888 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
889 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
890 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
891 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
892 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
893 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
894 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
895 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
896 LangOpts.XRayNeverInstrumentFiles,
897 LangOpts.XRayAttrListFiles, SM)),
898 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
899 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
900 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
901 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
902 CompCategories(this_()), LastSDM(nullptr, 0) {
904}
905
907 // Release the DenseMaps associated with DeclContext objects.
908 // FIXME: Is this the ideal solution?
909 ReleaseDeclContextMaps();
910
911 // Call all of the deallocation functions on all of their targets.
912 for (auto &Pair : Deallocations)
913 (Pair.first)(Pair.second);
914 Deallocations.clear();
915
916 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
917 // because they can contain DenseMaps.
918 for (llvm::DenseMap<const ObjCInterfaceDecl *,
920 I = ObjCLayouts.begin(),
921 E = ObjCLayouts.end();
922 I != E;)
923 // Increment in loop to prevent using deallocated memory.
924 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
925 R->Destroy(*this);
926 ObjCLayouts.clear();
927
928 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
929 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
930 // Increment in loop to prevent using deallocated memory.
931 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
932 R->Destroy(*this);
933 }
934 ASTRecordLayouts.clear();
935
936 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
937 AEnd = DeclAttrs.end();
938 A != AEnd; ++A)
939 A->second->~AttrVec();
940 DeclAttrs.clear();
941
942 for (const auto &Value : ModuleInitializers)
943 Value.second->~PerModuleInitializers();
944 ModuleInitializers.clear();
945
946 TUDecl = nullptr;
947 XRayFilter.reset();
948 NoSanitizeL.reset();
949}
950
952
953void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
954 TraversalScope = TopLevelDecls;
956}
957
958void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
959 Deallocations.push_back({Callback, Data});
960}
961
962void
966
968 llvm::errs() << "\n*** AST Context Stats:\n";
969 llvm::errs() << " " << Types.size() << " types total.\n";
970
971 unsigned counts[] = {
972#define TYPE(Name, Parent) 0,
973#define ABSTRACT_TYPE(Name, Parent)
974#include "clang/AST/TypeNodes.inc"
975 0 // Extra
976 };
977
978 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
979 Type *T = Types[i];
980 counts[(unsigned)T->getTypeClass()]++;
981 }
982
983 unsigned Idx = 0;
984 unsigned TotalBytes = 0;
985#define TYPE(Name, Parent) \
986 if (counts[Idx]) \
987 llvm::errs() << " " << counts[Idx] << " " << #Name \
988 << " types, " << sizeof(Name##Type) << " each " \
989 << "(" << counts[Idx] * sizeof(Name##Type) \
990 << " bytes)\n"; \
991 TotalBytes += counts[Idx] * sizeof(Name##Type); \
992 ++Idx;
993#define ABSTRACT_TYPE(Name, Parent)
994#include "clang/AST/TypeNodes.inc"
995
996 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
997
998 // Implicit special member functions.
999 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1001 << " implicit default constructors created\n";
1002 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1004 << " implicit copy constructors created\n";
1005 if (getLangOpts().CPlusPlus)
1006 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1008 << " implicit move constructors created\n";
1009 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1011 << " implicit copy assignment operators created\n";
1012 if (getLangOpts().CPlusPlus)
1013 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1015 << " implicit move assignment operators created\n";
1016 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1018 << " implicit destructors created\n";
1019
1020 if (ExternalSource) {
1021 llvm::errs() << "\n";
1022 ExternalSource->PrintStats();
1023 }
1024
1025 BumpAlloc.PrintStats();
1026}
1027
1029 bool NotifyListeners) {
1030 if (NotifyListeners)
1031 if (auto *Listener = getASTMutationListener();
1033 Listener->RedefinedHiddenDefinition(ND, M);
1034
1035 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1036}
1037
1039 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1040 if (It == MergedDefModules.end())
1041 return;
1042
1043 auto &Merged = It->second;
1044 llvm::DenseSet<Module*> Found;
1045 for (Module *&M : Merged)
1046 if (!Found.insert(M).second)
1047 M = nullptr;
1048 llvm::erase(Merged, nullptr);
1049}
1050
1053 auto MergedIt =
1054 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1055 if (MergedIt == MergedDefModules.end())
1056 return {};
1057 return MergedIt->second;
1058}
1059
1060void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1061 if (LazyInitializers.empty())
1062 return;
1063
1064 auto *Source = Ctx.getExternalSource();
1065 assert(Source && "lazy initializers but no external source");
1066
1067 auto LazyInits = std::move(LazyInitializers);
1068 LazyInitializers.clear();
1069
1070 for (auto ID : LazyInits)
1071 Initializers.push_back(Source->GetExternalDecl(ID));
1072
1073 assert(LazyInitializers.empty() &&
1074 "GetExternalDecl for lazy module initializer added more inits");
1075}
1076
1078 // One special case: if we add a module initializer that imports another
1079 // module, and that module's only initializer is an ImportDecl, simplify.
1080 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1081 auto It = ModuleInitializers.find(ID->getImportedModule());
1082
1083 // Maybe the ImportDecl does nothing at all. (Common case.)
1084 if (It == ModuleInitializers.end())
1085 return;
1086
1087 // Maybe the ImportDecl only imports another ImportDecl.
1088 auto &Imported = *It->second;
1089 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1090 Imported.resolve(*this);
1091 auto *OnlyDecl = Imported.Initializers.front();
1092 if (isa<ImportDecl>(OnlyDecl))
1093 D = OnlyDecl;
1094 }
1095 }
1096
1097 auto *&Inits = ModuleInitializers[M];
1098 if (!Inits)
1099 Inits = new (*this) PerModuleInitializers;
1100 Inits->Initializers.push_back(D);
1101}
1102
1105 auto *&Inits = ModuleInitializers[M];
1106 if (!Inits)
1107 Inits = new (*this) PerModuleInitializers;
1108 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1109 IDs.begin(), IDs.end());
1110}
1111
1113 auto It = ModuleInitializers.find(M);
1114 if (It == ModuleInitializers.end())
1115 return {};
1116
1117 auto *Inits = It->second;
1118 Inits->resolve(*this);
1119 return Inits->Initializers;
1120}
1121
1123 assert(M->isNamedModule());
1124 assert(!CurrentCXXNamedModule &&
1125 "We should set named module for ASTContext for only once");
1126 CurrentCXXNamedModule = M;
1127}
1128
1129bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1130 if (!M1 != !M2)
1131 return false;
1132
1133 /// Get the representative module for M. The representative module is the
1134 /// first module unit for a specific primary module name. So that the module
1135 /// units have the same representative module belongs to the same module.
1136 ///
1137 /// The process is helpful to reduce the expensive string operations.
1138 auto GetRepresentativeModule = [this](const Module *M) {
1139 auto Iter = SameModuleLookupSet.find(M);
1140 if (Iter != SameModuleLookupSet.end())
1141 return Iter->second;
1142
1143 const Module *RepresentativeModule =
1144 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1145 .first->second;
1146 SameModuleLookupSet[M] = RepresentativeModule;
1147 return RepresentativeModule;
1148 };
1149
1150 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1151 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1152}
1153
1155 if (!ExternCContext)
1156 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1157
1158 return ExternCContext;
1159}
1160
1171
1172#define BuiltinTemplate(BTName) \
1173 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1174 if (!Decl##BTName) \
1175 Decl##BTName = \
1176 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1177 return Decl##BTName; \
1178 }
1179#include "clang/Basic/BuiltinTemplates.inc"
1180
1182 RecordDecl::TagKind TK) const {
1183 SourceLocation Loc;
1184 RecordDecl *NewDecl;
1185 if (getLangOpts().CPlusPlus)
1186 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1187 Loc, &Idents.get(Name));
1188 else
1189 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1190 &Idents.get(Name));
1191 NewDecl->setImplicit();
1192 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1193 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1194 return NewDecl;
1195}
1196
1198 StringRef Name) const {
1201 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1202 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1203 NewDecl->setImplicit();
1204 return NewDecl;
1205}
1206
1208 if (!Int128Decl)
1209 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1210 return Int128Decl;
1211}
1212
1214 if (!UInt128Decl)
1215 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1216 return UInt128Decl;
1217}
1218
1219void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1220 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1222 Types.push_back(Ty);
1223}
1224
1226 const TargetInfo *AuxTarget) {
1227 assert((!this->Target || this->Target == &Target) &&
1228 "Incorrect target reinitialization");
1229 assert(VoidTy.isNull() && "Context reinitialized?");
1230
1231 this->Target = &Target;
1232 this->AuxTarget = AuxTarget;
1233
1234 ABI.reset(createCXXABI(Target));
1235 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1236
1237 // C99 6.2.5p19.
1238 InitBuiltinType(VoidTy, BuiltinType::Void);
1239
1240 // C99 6.2.5p2.
1241 InitBuiltinType(BoolTy, BuiltinType::Bool);
1242 // C99 6.2.5p3.
1243 if (LangOpts.CharIsSigned)
1244 InitBuiltinType(CharTy, BuiltinType::Char_S);
1245 else
1246 InitBuiltinType(CharTy, BuiltinType::Char_U);
1247 // C99 6.2.5p4.
1248 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1249 InitBuiltinType(ShortTy, BuiltinType::Short);
1250 InitBuiltinType(IntTy, BuiltinType::Int);
1251 InitBuiltinType(LongTy, BuiltinType::Long);
1252 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1253
1254 // C99 6.2.5p6.
1255 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1256 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1257 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1258 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1259 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1260
1261 // C99 6.2.5p10.
1262 InitBuiltinType(FloatTy, BuiltinType::Float);
1263 InitBuiltinType(DoubleTy, BuiltinType::Double);
1264 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1265
1266 // GNU extension, __float128 for IEEE quadruple precision
1267 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1268
1269 // __ibm128 for IBM extended precision
1270 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1271
1272 // C11 extension ISO/IEC TS 18661-3
1273 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1274
1275 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1276 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1277 InitBuiltinType(AccumTy, BuiltinType::Accum);
1278 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1279 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1280 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1281 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1282 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1283 InitBuiltinType(FractTy, BuiltinType::Fract);
1284 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1285 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1286 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1287 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1288 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1289 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1290 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1291 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1292 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1293 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1294 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1295 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1296 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1297 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1298 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1299 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1300
1301 // GNU extension, 128-bit integers.
1302 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1303 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1304
1305 // C++ 3.9.1p5
1306 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1307 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1308 else // -fshort-wchar makes wchar_t be unsigned.
1309 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1310 if (LangOpts.CPlusPlus && LangOpts.WChar)
1312 else {
1313 // C99 (or C++ using -fno-wchar).
1314 WideCharTy = getFromTargetType(Target.getWCharType());
1315 }
1316
1317 WIntTy = getFromTargetType(Target.getWIntType());
1318
1319 // C++20 (proposed)
1320 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1321
1322 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1323 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1324 else // C99
1325 Char16Ty = getFromTargetType(Target.getChar16Type());
1326
1327 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1328 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1329 else // C99
1330 Char32Ty = getFromTargetType(Target.getChar32Type());
1331
1332 // Placeholder type for type-dependent expressions whose type is
1333 // completely unknown. No code should ever check a type against
1334 // DependentTy and users should never see it; however, it is here to
1335 // help diagnose failures to properly check for type-dependent
1336 // expressions.
1337 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1338
1339 // Placeholder type for functions.
1340 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1341
1342 // Placeholder type for bound members.
1343 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1344
1345 // Placeholder type for unresolved templates.
1346 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1347
1348 // Placeholder type for pseudo-objects.
1349 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1350
1351 // "any" type; useful for debugger-like clients.
1352 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1353
1354 // Placeholder type for unbridged ARC casts.
1355 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1356
1357 // Placeholder type for builtin functions.
1358 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1359
1360 // Placeholder type for OMP array sections.
1361 if (LangOpts.OpenMP) {
1362 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1363 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1364 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1365 }
1366 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1367 // don't bother, as we're just using the same type as OMP.
1368 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1369 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1370 }
1371 if (LangOpts.MatrixTypes)
1372 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1373
1374 // Builtin types for 'id', 'Class', and 'SEL'.
1375 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1376 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1377 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1378
1379 if (LangOpts.OpenCL) {
1380#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1381 InitBuiltinType(SingletonId, BuiltinType::Id);
1382#include "clang/Basic/OpenCLImageTypes.def"
1383
1384 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1385 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1386 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1387 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1388 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1389
1390#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1391 InitBuiltinType(Id##Ty, BuiltinType::Id);
1392#include "clang/Basic/OpenCLExtensionTypes.def"
1393 }
1394
1395 if (LangOpts.HLSL) {
1396#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1397 InitBuiltinType(SingletonId, BuiltinType::Id);
1398#include "clang/Basic/HLSLIntangibleTypes.def"
1399 }
1400
1401 if (Target.hasAArch64ACLETypes() ||
1402 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1403#define SVE_TYPE(Name, Id, SingletonId) \
1404 InitBuiltinType(SingletonId, BuiltinType::Id);
1405#include "clang/Basic/AArch64ACLETypes.def"
1406 }
1407
1408 if (Target.getTriple().isPPC64()) {
1409#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1410 InitBuiltinType(Id##Ty, BuiltinType::Id);
1411#include "clang/Basic/PPCTypes.def"
1412#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1413 InitBuiltinType(Id##Ty, BuiltinType::Id);
1414#include "clang/Basic/PPCTypes.def"
1415 }
1416
1417 if (Target.hasRISCVVTypes()) {
1418#define RVV_TYPE(Name, Id, SingletonId) \
1419 InitBuiltinType(SingletonId, BuiltinType::Id);
1420#include "clang/Basic/RISCVVTypes.def"
1421 }
1422
1423 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1424#define WASM_TYPE(Name, Id, SingletonId) \
1425 InitBuiltinType(SingletonId, BuiltinType::Id);
1426#include "clang/Basic/WebAssemblyReferenceTypes.def"
1427 }
1428
1429 if (Target.getTriple().isAMDGPU() ||
1430 (Target.getTriple().isSPIRV() &&
1431 Target.getTriple().getVendor() == llvm::Triple::AMD) ||
1432 (AuxTarget &&
1433 (AuxTarget->getTriple().isAMDGPU() ||
1434 ((AuxTarget->getTriple().isSPIRV() &&
1435 AuxTarget->getTriple().getVendor() == llvm::Triple::AMD))))) {
1436#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1437 InitBuiltinType(SingletonId, BuiltinType::Id);
1438#include "clang/Basic/AMDGPUTypes.def"
1439 }
1440
1441 // Builtin type for __objc_yes and __objc_no
1442 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1444
1445 ObjCConstantStringType = QualType();
1446
1447 ObjCSuperType = QualType();
1448
1449 // void * type
1450 if (LangOpts.OpenCLGenericAddressSpace) {
1451 auto Q = VoidTy.getQualifiers();
1452 Q.setAddressSpace(LangAS::opencl_generic);
1454 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1455 } else {
1457 }
1458
1459 // nullptr type (C++0x 2.14.7)
1460 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1461
1462 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1463 InitBuiltinType(HalfTy, BuiltinType::Half);
1464
1465 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1466
1467 // Builtin type used to help define __builtin_va_list.
1468 VaListTagDecl = nullptr;
1469
1470 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1471 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1474 }
1475}
1476
1478 return SourceMgr.getDiagnostics();
1479}
1480
1482 AttrVec *&Result = DeclAttrs[D];
1483 if (!Result) {
1484 void *Mem = Allocate(sizeof(AttrVec));
1485 Result = new (Mem) AttrVec;
1486 }
1487
1488 return *Result;
1489}
1490
1491/// Erase the attributes corresponding to the given declaration.
1493 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1494 if (Pos != DeclAttrs.end()) {
1495 Pos->second->~AttrVec();
1496 DeclAttrs.erase(Pos);
1497 }
1498}
1499
1500// FIXME: Remove ?
1503 assert(Var->isStaticDataMember() && "Not a static data member");
1505 .dyn_cast<MemberSpecializationInfo *>();
1506}
1507
1510 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1511 TemplateOrInstantiation.find(Var);
1512 if (Pos == TemplateOrInstantiation.end())
1513 return {};
1514
1515 return Pos->second;
1516}
1517
1518void
1521 SourceLocation PointOfInstantiation) {
1522 assert(Inst->isStaticDataMember() && "Not a static data member");
1523 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1525 Tmpl, TSK, PointOfInstantiation));
1526}
1527
1528void
1531 assert(!TemplateOrInstantiation[Inst] &&
1532 "Already noted what the variable was instantiated from");
1533 TemplateOrInstantiation[Inst] = TSI;
1534}
1535
1536NamedDecl *
1538 return InstantiatedFromUsingDecl.lookup(UUD);
1539}
1540
1541void
1543 assert((isa<UsingDecl>(Pattern) ||
1546 "pattern decl is not a using decl");
1547 assert((isa<UsingDecl>(Inst) ||
1550 "instantiation did not produce a using decl");
1551 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1552 InstantiatedFromUsingDecl[Inst] = Pattern;
1553}
1554
1557 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1558}
1559
1561 UsingEnumDecl *Pattern) {
1562 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1563 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1564}
1565
1568 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1569}
1570
1571void
1573 UsingShadowDecl *Pattern) {
1574 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1575 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1576}
1577
1578FieldDecl *
1580 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1581}
1582
1584 FieldDecl *Tmpl) {
1585 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1586 "Instantiated field decl is not unnamed");
1587 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1588 "Template field decl is not unnamed");
1589 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1590 "Already noted what unnamed field was instantiated from");
1591
1592 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1593}
1594
1599
1604
1605unsigned
1607 auto Range = overridden_methods(Method);
1608 return Range.end() - Range.begin();
1609}
1610
1613 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1614 OverriddenMethods.find(Method->getCanonicalDecl());
1615 if (Pos == OverriddenMethods.end())
1616 return overridden_method_range(nullptr, nullptr);
1617 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1618}
1619
1621 const CXXMethodDecl *Overridden) {
1622 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1623 OverriddenMethods[Method].push_back(Overridden);
1624}
1625
1627 const NamedDecl *D,
1628 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1629 assert(D);
1630
1631 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1632 Overridden.append(overridden_methods_begin(CXXMethod),
1633 overridden_methods_end(CXXMethod));
1634 return;
1635 }
1636
1637 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1638 if (!Method)
1639 return;
1640
1642 Method->getOverriddenMethods(OverDecls);
1643 Overridden.append(OverDecls.begin(), OverDecls.end());
1644}
1645
1646std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1648 assert(RD);
1649 CXXRecordDecl *D = RD->getDefinition();
1650 auto it = RelocatableClasses.find(D);
1651 if (it != RelocatableClasses.end())
1652 return it->getSecond();
1653 return std::nullopt;
1654}
1655
1658 assert(RD);
1659 CXXRecordDecl *D = RD->getDefinition();
1660 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1661 RelocatableClasses.insert({D, Info});
1662}
1663
1665 const ASTContext &Context, const CXXRecordDecl *Class) {
1666 if (!Class->isPolymorphic())
1667 return false;
1668 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1669 using AuthAttr = VTablePointerAuthenticationAttr;
1670 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1671 if (!ExplicitAuth)
1672 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1673 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1674 ExplicitAuth->getAddressDiscrimination();
1675 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1676 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1677 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1678}
1679
1680ASTContext::PointerAuthContent
1681ASTContext::findPointerAuthContent(QualType T) const {
1682 assert(isPointerAuthenticationAvailable());
1683
1684 T = T.getCanonicalType();
1685 if (T->isDependentType())
1686 return PointerAuthContent::None;
1687
1689 return PointerAuthContent::AddressDiscriminatedData;
1690 const RecordDecl *RD = T->getAsRecordDecl();
1691 if (!RD)
1692 return PointerAuthContent::None;
1693
1694 if (RD->isInvalidDecl())
1695 return PointerAuthContent::None;
1696
1697 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1698 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1699 return Existing->second;
1700
1701 PointerAuthContent Result = PointerAuthContent::None;
1702
1703 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1704 auto [ResultIter, DidAdd] =
1705 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1706 (void)ResultIter;
1707 (void)DidAdd;
1708 assert(DidAdd);
1709 return Result;
1710 };
1711 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1712 static_assert(PointerAuthContent::None <
1713 PointerAuthContent::AddressDiscriminatedVTable);
1714 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1715 PointerAuthContent::AddressDiscriminatedData);
1716 if (NewResult > Result)
1717 Result = NewResult;
1718 return Result != PointerAuthContent::AddressDiscriminatedData;
1719 };
1720 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1722 !ShouldContinueAfterUpdate(
1723 PointerAuthContent::AddressDiscriminatedVTable))
1724 return SaveResultAndReturn();
1725 for (auto Base : CXXRD->bases()) {
1726 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1727 return SaveResultAndReturn();
1728 }
1729 }
1730 for (auto *FieldDecl : RD->fields()) {
1731 if (!ShouldContinueAfterUpdate(
1732 findPointerAuthContent(FieldDecl->getType())))
1733 return SaveResultAndReturn();
1734 }
1735 return SaveResultAndReturn();
1736}
1737
1739 assert(!Import->getNextLocalImport() &&
1740 "Import declaration already in the chain");
1741 assert(!Import->isFromASTFile() && "Non-local import declaration");
1742 if (!FirstLocalImport) {
1743 FirstLocalImport = Import;
1744 LastLocalImport = Import;
1745 return;
1746 }
1747
1748 LastLocalImport->setNextLocalImport(Import);
1749 LastLocalImport = Import;
1750}
1751
1752//===----------------------------------------------------------------------===//
1753// Type Sizing and Analysis
1754//===----------------------------------------------------------------------===//
1755
1756/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1757/// scalar floating point type.
1758const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1759 switch (T->castAs<BuiltinType>()->getKind()) {
1760 default:
1761 llvm_unreachable("Not a floating point type!");
1762 case BuiltinType::BFloat16:
1763 return Target->getBFloat16Format();
1764 case BuiltinType::Float16:
1765 return Target->getHalfFormat();
1766 case BuiltinType::Half:
1767 return Target->getHalfFormat();
1768 case BuiltinType::Float: return Target->getFloatFormat();
1769 case BuiltinType::Double: return Target->getDoubleFormat();
1770 case BuiltinType::Ibm128:
1771 return Target->getIbm128Format();
1772 case BuiltinType::LongDouble:
1773 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1774 return AuxTarget->getLongDoubleFormat();
1775 return Target->getLongDoubleFormat();
1776 case BuiltinType::Float128:
1777 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1778 return AuxTarget->getFloat128Format();
1779 return Target->getFloat128Format();
1780 }
1781}
1782
1783CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1784 unsigned Align = Target->getCharWidth();
1785
1786 const unsigned AlignFromAttr = D->getMaxAlignment();
1787 if (AlignFromAttr)
1788 Align = AlignFromAttr;
1789
1790 // __attribute__((aligned)) can increase or decrease alignment
1791 // *except* on a struct or struct member, where it only increases
1792 // alignment unless 'packed' is also specified.
1793 //
1794 // It is an error for alignas to decrease alignment, so we can
1795 // ignore that possibility; Sema should diagnose it.
1796 bool UseAlignAttrOnly;
1797 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1798 UseAlignAttrOnly =
1799 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1800 else
1801 UseAlignAttrOnly = AlignFromAttr != 0;
1802 // If we're using the align attribute only, just ignore everything
1803 // else about the declaration and its type.
1804 if (UseAlignAttrOnly) {
1805 // do nothing
1806 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1807 QualType T = VD->getType();
1808 if (const auto *RT = T->getAs<ReferenceType>()) {
1809 if (ForAlignof)
1810 T = RT->getPointeeType();
1811 else
1812 T = getPointerType(RT->getPointeeType());
1813 }
1814 QualType BaseT = getBaseElementType(T);
1815 if (T->isFunctionType())
1816 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1817 else if (!BaseT->isIncompleteType()) {
1818 // Adjust alignments of declarations with array type by the
1819 // large-array alignment on the target.
1820 if (const ArrayType *arrayType = getAsArrayType(T)) {
1821 unsigned MinWidth = Target->getLargeArrayMinWidth();
1822 if (!ForAlignof && MinWidth) {
1824 Align = std::max(Align, Target->getLargeArrayAlign());
1827 Align = std::max(Align, Target->getLargeArrayAlign());
1828 }
1829 }
1830 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1831 if (BaseT.getQualifiers().hasUnaligned())
1832 Align = Target->getCharWidth();
1833 }
1834
1835 // Ensure minimum alignment for global variables.
1836 if (const auto *VD = dyn_cast<VarDecl>(D))
1837 if (VD->hasGlobalStorage() && !ForAlignof) {
1838 uint64_t TypeSize =
1839 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1840 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1841 }
1842
1843 // Fields can be subject to extra alignment constraints, like if
1844 // the field is packed, the struct is packed, or the struct has a
1845 // a max-field-alignment constraint (#pragma pack). So calculate
1846 // the actual alignment of the field within the struct, and then
1847 // (as we're expected to) constrain that by the alignment of the type.
1848 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1849 const RecordDecl *Parent = Field->getParent();
1850 // We can only produce a sensible answer if the record is valid.
1851 if (!Parent->isInvalidDecl()) {
1852 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1853
1854 // Start with the record's overall alignment.
1855 unsigned FieldAlign = toBits(Layout.getAlignment());
1856
1857 // Use the GCD of that and the offset within the record.
1858 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1859 if (Offset > 0) {
1860 // Alignment is always a power of 2, so the GCD will be a power of 2,
1861 // which means we get to do this crazy thing instead of Euclid's.
1862 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1863 if (LowBitOfOffset < FieldAlign)
1864 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1865 }
1866
1867 Align = std::min(Align, FieldAlign);
1868 }
1869 }
1870 }
1871
1872 // Some targets have hard limitation on the maximum requestable alignment in
1873 // aligned attribute for static variables.
1874 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1875 const auto *VD = dyn_cast<VarDecl>(D);
1876 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1877 Align = std::min(Align, MaxAlignedAttr);
1878
1879 return toCharUnitsFromBits(Align);
1880}
1881
1883 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1884}
1885
1886// getTypeInfoDataSizeInChars - Return the size of a type, in
1887// chars. If the type is a record, its data size is returned. This is
1888// the size of the memcpy that's performed when assigning this type
1889// using a trivial copy/move assignment operator.
1892
1893 // In C++, objects can sometimes be allocated into the tail padding
1894 // of a base-class subobject. We decide whether that's possible
1895 // during class layout, so here we can just trust the layout results.
1896 if (getLangOpts().CPlusPlus) {
1897 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1898 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1899 Info.Width = layout.getDataSize();
1900 }
1901 }
1902
1903 return Info;
1904}
1905
1906/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1907/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1910 const ConstantArrayType *CAT) {
1911 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1912 uint64_t Size = CAT->getZExtSize();
1913 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1914 (uint64_t)(-1)/Size) &&
1915 "Overflow in array type char size evaluation");
1916 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1917 unsigned Align = EltInfo.Align.getQuantity();
1918 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1919 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1920 Width = llvm::alignTo(Width, Align);
1923 EltInfo.AlignRequirement);
1924}
1925
1927 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1928 return getConstantArrayInfoInChars(*this, CAT);
1929 TypeInfo Info = getTypeInfo(T);
1932}
1933
1935 return getTypeInfoInChars(T.getTypePtr());
1936}
1937
1939 // HLSL doesn't promote all small integer types to int, it
1940 // just uses the rank-based promotion rules for all types.
1941 if (getLangOpts().HLSL)
1942 return false;
1943
1944 if (const auto *BT = T->getAs<BuiltinType>())
1945 switch (BT->getKind()) {
1946 case BuiltinType::Bool:
1947 case BuiltinType::Char_S:
1948 case BuiltinType::Char_U:
1949 case BuiltinType::SChar:
1950 case BuiltinType::UChar:
1951 case BuiltinType::Short:
1952 case BuiltinType::UShort:
1953 case BuiltinType::WChar_S:
1954 case BuiltinType::WChar_U:
1955 case BuiltinType::Char8:
1956 case BuiltinType::Char16:
1957 case BuiltinType::Char32:
1958 return true;
1959 default:
1960 return false;
1961 }
1962
1963 // Enumerated types are promotable to their compatible integer types
1964 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1965 if (const auto *ED = T->getAsEnumDecl()) {
1966 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1967 ED->isScoped())
1968 return false;
1969
1970 return true;
1971 }
1972
1973 // OverflowBehaviorTypes are promotable if their underlying type is promotable
1974 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
1975 return isPromotableIntegerType(OBT->getUnderlyingType());
1976 }
1977
1978 return false;
1979}
1980
1984
1986 return isAlignmentRequired(T.getTypePtr());
1987}
1988
1990 bool NeedsPreferredAlignment) const {
1991 // An alignment on a typedef overrides anything else.
1992 if (const auto *TT = T->getAs<TypedefType>())
1993 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1994 return Align;
1995
1996 // If we have an (array of) complete type, we're done.
1997 T = getBaseElementType(T);
1998 if (!T->isIncompleteType())
1999 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2000
2001 // If we had an array type, its element type might be a typedef
2002 // type with an alignment attribute.
2003 if (const auto *TT = T->getAs<TypedefType>())
2004 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2005 return Align;
2006
2007 // Otherwise, see if the declaration of the type had an attribute.
2008 if (const auto *TD = T->getAsTagDecl())
2009 return TD->getMaxAlignment();
2010
2011 return 0;
2012}
2013
2015 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2016 if (I != MemoizedTypeInfo.end())
2017 return I->second;
2018
2019 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2020 TypeInfo TI = getTypeInfoImpl(T);
2021 MemoizedTypeInfo[T] = TI;
2022 return TI;
2023}
2024
2025/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2026/// method does not work on incomplete types.
2027///
2028/// FIXME: Pointers into different addr spaces could have different sizes and
2029/// alignment requirements: getPointerInfo should take an AddrSpace, this
2030/// should take a QualType, &c.
2031TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2032 uint64_t Width = 0;
2033 unsigned Align = 8;
2036 switch (T->getTypeClass()) {
2037#define TYPE(Class, Base)
2038#define ABSTRACT_TYPE(Class, Base)
2039#define NON_CANONICAL_TYPE(Class, Base)
2040#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2041#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2042 case Type::Class: \
2043 assert(!T->isDependentType() && "should not see dependent types here"); \
2044 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2045#include "clang/AST/TypeNodes.inc"
2046 llvm_unreachable("Should not see dependent types");
2047
2048 case Type::FunctionNoProto:
2049 case Type::FunctionProto:
2050 // GCC extension: alignof(function) = 32 bits
2051 Width = 0;
2052 Align = 32;
2053 break;
2054
2055 case Type::IncompleteArray:
2056 case Type::VariableArray:
2057 case Type::ConstantArray:
2058 case Type::ArrayParameter: {
2059 // Model non-constant sized arrays as size zero, but track the alignment.
2060 uint64_t Size = 0;
2061 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2062 Size = CAT->getZExtSize();
2063
2064 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2065 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2066 "Overflow in array type bit size evaluation");
2067 Width = EltInfo.Width * Size;
2068 Align = EltInfo.Align;
2069 AlignRequirement = EltInfo.AlignRequirement;
2070 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2071 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2072 Width = llvm::alignTo(Width, Align);
2073 break;
2074 }
2075
2076 case Type::ExtVector:
2077 case Type::Vector: {
2078 const auto *VT = cast<VectorType>(T);
2079 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2080 Width = VT->isPackedVectorBoolType(*this)
2081 ? VT->getNumElements()
2082 : EltInfo.Width * VT->getNumElements();
2083 // Enforce at least byte size and alignment.
2084 Width = std::max<unsigned>(8, Width);
2085 Align = std::max<unsigned>(
2086 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2087
2088 // If the alignment is not a power of 2, round up to the next power of 2.
2089 // This happens for non-power-of-2 length vectors.
2090 if (Align & (Align-1)) {
2091 Align = llvm::bit_ceil(Align);
2092 Width = llvm::alignTo(Width, Align);
2093 }
2094 // Adjust the alignment based on the target max.
2095 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2096 if (TargetVectorAlign && TargetVectorAlign < Align)
2097 Align = TargetVectorAlign;
2098 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2099 // Adjust the alignment for fixed-length SVE vectors. This is important
2100 // for non-power-of-2 vector lengths.
2101 Align = 128;
2102 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2103 // Adjust the alignment for fixed-length SVE predicates.
2104 Align = 16;
2105 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2106 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2107 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2108 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2109 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2110 // Adjust the alignment for fixed-length RVV vectors.
2111 Align = std::min<unsigned>(64, Width);
2112 break;
2113 }
2114
2115 case Type::ConstantMatrix: {
2116 const auto *MT = cast<ConstantMatrixType>(T);
2117 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2118 // The internal layout of a matrix value is implementation defined.
2119 // Initially be ABI compatible with arrays with respect to alignment and
2120 // size.
2121 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2122 Align = ElementInfo.Align;
2123 break;
2124 }
2125
2126 case Type::Builtin:
2127 switch (cast<BuiltinType>(T)->getKind()) {
2128 default: llvm_unreachable("Unknown builtin type!");
2129 case BuiltinType::Void:
2130 // GCC extension: alignof(void) = 8 bits.
2131 Width = 0;
2132 Align = 8;
2133 break;
2134 case BuiltinType::Bool:
2135 Width = Target->getBoolWidth();
2136 Align = Target->getBoolAlign();
2137 break;
2138 case BuiltinType::Char_S:
2139 case BuiltinType::Char_U:
2140 case BuiltinType::UChar:
2141 case BuiltinType::SChar:
2142 case BuiltinType::Char8:
2143 Width = Target->getCharWidth();
2144 Align = Target->getCharAlign();
2145 break;
2146 case BuiltinType::WChar_S:
2147 case BuiltinType::WChar_U:
2148 Width = Target->getWCharWidth();
2149 Align = Target->getWCharAlign();
2150 break;
2151 case BuiltinType::Char16:
2152 Width = Target->getChar16Width();
2153 Align = Target->getChar16Align();
2154 break;
2155 case BuiltinType::Char32:
2156 Width = Target->getChar32Width();
2157 Align = Target->getChar32Align();
2158 break;
2159 case BuiltinType::UShort:
2160 case BuiltinType::Short:
2161 Width = Target->getShortWidth();
2162 Align = Target->getShortAlign();
2163 break;
2164 case BuiltinType::UInt:
2165 case BuiltinType::Int:
2166 Width = Target->getIntWidth();
2167 Align = Target->getIntAlign();
2168 break;
2169 case BuiltinType::ULong:
2170 case BuiltinType::Long:
2171 Width = Target->getLongWidth();
2172 Align = Target->getLongAlign();
2173 break;
2174 case BuiltinType::ULongLong:
2175 case BuiltinType::LongLong:
2176 Width = Target->getLongLongWidth();
2177 Align = Target->getLongLongAlign();
2178 break;
2179 case BuiltinType::Int128:
2180 case BuiltinType::UInt128:
2181 Width = 128;
2182 Align = Target->getInt128Align();
2183 break;
2184 case BuiltinType::ShortAccum:
2185 case BuiltinType::UShortAccum:
2186 case BuiltinType::SatShortAccum:
2187 case BuiltinType::SatUShortAccum:
2188 Width = Target->getShortAccumWidth();
2189 Align = Target->getShortAccumAlign();
2190 break;
2191 case BuiltinType::Accum:
2192 case BuiltinType::UAccum:
2193 case BuiltinType::SatAccum:
2194 case BuiltinType::SatUAccum:
2195 Width = Target->getAccumWidth();
2196 Align = Target->getAccumAlign();
2197 break;
2198 case BuiltinType::LongAccum:
2199 case BuiltinType::ULongAccum:
2200 case BuiltinType::SatLongAccum:
2201 case BuiltinType::SatULongAccum:
2202 Width = Target->getLongAccumWidth();
2203 Align = Target->getLongAccumAlign();
2204 break;
2205 case BuiltinType::ShortFract:
2206 case BuiltinType::UShortFract:
2207 case BuiltinType::SatShortFract:
2208 case BuiltinType::SatUShortFract:
2209 Width = Target->getShortFractWidth();
2210 Align = Target->getShortFractAlign();
2211 break;
2212 case BuiltinType::Fract:
2213 case BuiltinType::UFract:
2214 case BuiltinType::SatFract:
2215 case BuiltinType::SatUFract:
2216 Width = Target->getFractWidth();
2217 Align = Target->getFractAlign();
2218 break;
2219 case BuiltinType::LongFract:
2220 case BuiltinType::ULongFract:
2221 case BuiltinType::SatLongFract:
2222 case BuiltinType::SatULongFract:
2223 Width = Target->getLongFractWidth();
2224 Align = Target->getLongFractAlign();
2225 break;
2226 case BuiltinType::BFloat16:
2227 if (Target->hasBFloat16Type()) {
2228 Width = Target->getBFloat16Width();
2229 Align = Target->getBFloat16Align();
2230 } else if ((getLangOpts().SYCLIsDevice ||
2231 (getLangOpts().OpenMP &&
2232 getLangOpts().OpenMPIsTargetDevice)) &&
2233 AuxTarget->hasBFloat16Type()) {
2234 Width = AuxTarget->getBFloat16Width();
2235 Align = AuxTarget->getBFloat16Align();
2236 }
2237 break;
2238 case BuiltinType::Float16:
2239 case BuiltinType::Half:
2240 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2241 !getLangOpts().OpenMPIsTargetDevice) {
2242 Width = Target->getHalfWidth();
2243 Align = Target->getHalfAlign();
2244 } else {
2245 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2246 "Expected OpenMP device compilation.");
2247 Width = AuxTarget->getHalfWidth();
2248 Align = AuxTarget->getHalfAlign();
2249 }
2250 break;
2251 case BuiltinType::Float:
2252 Width = Target->getFloatWidth();
2253 Align = Target->getFloatAlign();
2254 break;
2255 case BuiltinType::Double:
2256 Width = Target->getDoubleWidth();
2257 Align = Target->getDoubleAlign();
2258 break;
2259 case BuiltinType::Ibm128:
2260 Width = Target->getIbm128Width();
2261 Align = Target->getIbm128Align();
2262 break;
2263 case BuiltinType::LongDouble:
2264 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2265 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2266 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2267 Width = AuxTarget->getLongDoubleWidth();
2268 Align = AuxTarget->getLongDoubleAlign();
2269 } else {
2270 Width = Target->getLongDoubleWidth();
2271 Align = Target->getLongDoubleAlign();
2272 }
2273 break;
2274 case BuiltinType::Float128:
2275 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2276 !getLangOpts().OpenMPIsTargetDevice) {
2277 Width = Target->getFloat128Width();
2278 Align = Target->getFloat128Align();
2279 } else {
2280 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2281 "Expected OpenMP device compilation.");
2282 Width = AuxTarget->getFloat128Width();
2283 Align = AuxTarget->getFloat128Align();
2284 }
2285 break;
2286 case BuiltinType::NullPtr:
2287 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2288 Width = Target->getPointerWidth(LangAS::Default);
2289 Align = Target->getPointerAlign(LangAS::Default);
2290 break;
2291 case BuiltinType::ObjCId:
2292 case BuiltinType::ObjCClass:
2293 case BuiltinType::ObjCSel:
2294 Width = Target->getPointerWidth(LangAS::Default);
2295 Align = Target->getPointerAlign(LangAS::Default);
2296 break;
2297 case BuiltinType::OCLSampler:
2298 case BuiltinType::OCLEvent:
2299 case BuiltinType::OCLClkEvent:
2300 case BuiltinType::OCLQueue:
2301 case BuiltinType::OCLReserveID:
2302#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2303 case BuiltinType::Id:
2304#include "clang/Basic/OpenCLImageTypes.def"
2305#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2306 case BuiltinType::Id:
2307#include "clang/Basic/OpenCLExtensionTypes.def"
2308 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2309 Width = Target->getPointerWidth(AS);
2310 Align = Target->getPointerAlign(AS);
2311 break;
2312 // The SVE types are effectively target-specific. The length of an
2313 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2314 // of 128 bits. There is one predicate bit for each vector byte, so the
2315 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2316 //
2317 // Because the length is only known at runtime, we use a dummy value
2318 // of 0 for the static length. The alignment values are those defined
2319 // by the Procedure Call Standard for the Arm Architecture.
2320#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2321 case BuiltinType::Id: \
2322 Width = 0; \
2323 Align = 128; \
2324 break;
2325#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2326 case BuiltinType::Id: \
2327 Width = 0; \
2328 Align = 16; \
2329 break;
2330#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2331 case BuiltinType::Id: \
2332 Width = 0; \
2333 Align = 16; \
2334 break;
2335#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2336 case BuiltinType::Id: \
2337 Width = Bits; \
2338 Align = Bits; \
2339 break;
2340#include "clang/Basic/AArch64ACLETypes.def"
2341#define PPC_VECTOR_TYPE(Name, Id, Size) \
2342 case BuiltinType::Id: \
2343 Width = Size; \
2344 Align = Size; \
2345 break;
2346#include "clang/Basic/PPCTypes.def"
2347#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2348 IsFP, IsBF) \
2349 case BuiltinType::Id: \
2350 Width = 0; \
2351 Align = ElBits; \
2352 break;
2353#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2354 case BuiltinType::Id: \
2355 Width = 0; \
2356 Align = 8; \
2357 break;
2358#include "clang/Basic/RISCVVTypes.def"
2359#define WASM_TYPE(Name, Id, SingletonId) \
2360 case BuiltinType::Id: \
2361 Width = 0; \
2362 Align = 8; \
2363 break;
2364#include "clang/Basic/WebAssemblyReferenceTypes.def"
2365#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2366 case BuiltinType::ID: \
2367 Width = WIDTH; \
2368 Align = ALIGN; \
2369 break;
2370#include "clang/Basic/AMDGPUTypes.def"
2371#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2372#include "clang/Basic/HLSLIntangibleTypes.def"
2373 Width = Target->getPointerWidth(LangAS::Default);
2374 Align = Target->getPointerAlign(LangAS::Default);
2375 break;
2376 }
2377 break;
2378 case Type::ObjCObjectPointer:
2379 Width = Target->getPointerWidth(LangAS::Default);
2380 Align = Target->getPointerAlign(LangAS::Default);
2381 break;
2382 case Type::BlockPointer:
2383 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2384 Width = Target->getPointerWidth(AS);
2385 Align = Target->getPointerAlign(AS);
2386 break;
2387 case Type::LValueReference:
2388 case Type::RValueReference:
2389 // alignof and sizeof should never enter this code path here, so we go
2390 // the pointer route.
2391 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2392 Width = Target->getPointerWidth(AS);
2393 Align = Target->getPointerAlign(AS);
2394 break;
2395 case Type::Pointer:
2396 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2397 Width = Target->getPointerWidth(AS);
2398 Align = Target->getPointerAlign(AS);
2399 break;
2400 case Type::MemberPointer: {
2401 const auto *MPT = cast<MemberPointerType>(T);
2402 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2403 Width = MPI.Width;
2404 Align = MPI.Align;
2405 break;
2406 }
2407 case Type::Complex: {
2408 // Complex types have the same alignment as their elements, but twice the
2409 // size.
2410 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2411 Width = EltInfo.Width * 2;
2412 Align = EltInfo.Align;
2413 break;
2414 }
2415 case Type::ObjCObject:
2416 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2417 case Type::Adjusted:
2418 case Type::Decayed:
2419 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2420 case Type::ObjCInterface: {
2421 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2422 if (ObjCI->getDecl()->isInvalidDecl()) {
2423 Width = 8;
2424 Align = 8;
2425 break;
2426 }
2427 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2428 Width = toBits(Layout.getSize());
2429 Align = toBits(Layout.getAlignment());
2430 break;
2431 }
2432 case Type::BitInt: {
2433 const auto *EIT = cast<BitIntType>(T);
2434 Align = Target->getBitIntAlign(EIT->getNumBits());
2435 Width = Target->getBitIntWidth(EIT->getNumBits());
2436 break;
2437 }
2438 case Type::Record:
2439 case Type::Enum: {
2440 const auto *TT = cast<TagType>(T);
2441 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2442
2443 if (TD->isInvalidDecl()) {
2444 Width = 8;
2445 Align = 8;
2446 break;
2447 }
2448
2449 if (isa<EnumType>(TT)) {
2450 const EnumDecl *ED = cast<EnumDecl>(TD);
2451 TypeInfo Info =
2453 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2454 Info.Align = AttrAlign;
2456 }
2457 return Info;
2458 }
2459
2460 const auto *RD = cast<RecordDecl>(TD);
2461 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2462 Width = toBits(Layout.getSize());
2463 Align = toBits(Layout.getAlignment());
2464 AlignRequirement = RD->hasAttr<AlignedAttr>()
2466 : AlignRequirementKind::None;
2467 break;
2468 }
2469
2470 case Type::SubstTemplateTypeParm:
2472 getReplacementType().getTypePtr());
2473
2474 case Type::Auto:
2475 case Type::DeducedTemplateSpecialization: {
2476 const auto *A = cast<DeducedType>(T);
2477 assert(!A->getDeducedType().isNull() &&
2478 "cannot request the size of an undeduced or dependent auto type");
2479 return getTypeInfo(A->getDeducedType().getTypePtr());
2480 }
2481
2482 case Type::Paren:
2483 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2484
2485 case Type::MacroQualified:
2486 return getTypeInfo(
2487 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2488
2489 case Type::ObjCTypeParam:
2490 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2491
2492 case Type::Using:
2493 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2494
2495 case Type::Typedef: {
2496 const auto *TT = cast<TypedefType>(T);
2497 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2498 // If the typedef has an aligned attribute on it, it overrides any computed
2499 // alignment we have. This violates the GCC documentation (which says that
2500 // attribute(aligned) can only round up) but matches its implementation.
2501 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2502 Align = AttrAlign;
2503 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2504 } else {
2505 Align = Info.Align;
2506 AlignRequirement = Info.AlignRequirement;
2507 }
2508 Width = Info.Width;
2509 break;
2510 }
2511
2512 case Type::Attributed:
2513 return getTypeInfo(
2514 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2515
2516 case Type::CountAttributed:
2517 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2518
2519 case Type::BTFTagAttributed:
2520 return getTypeInfo(
2521 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2522
2523 case Type::OverflowBehavior:
2524 return getTypeInfo(
2526
2527 case Type::HLSLAttributedResource:
2528 return getTypeInfo(
2529 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2530
2531 case Type::HLSLInlineSpirv: {
2532 const auto *ST = cast<HLSLInlineSpirvType>(T);
2533 // Size is specified in bytes, convert to bits
2534 Width = ST->getSize() * 8;
2535 Align = ST->getAlignment();
2536 if (Width == 0 && Align == 0) {
2537 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2538 Width = 32;
2539 Align = 32;
2540 }
2541 break;
2542 }
2543
2544 case Type::Atomic: {
2545 // Start with the base type information.
2546 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2547 Width = Info.Width;
2548 Align = Info.Align;
2549
2550 if (!Width) {
2551 // An otherwise zero-sized type should still generate an
2552 // atomic operation.
2553 Width = Target->getCharWidth();
2554 assert(Align);
2555 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2556 // If the size of the type doesn't exceed the platform's max
2557 // atomic promotion width, make the size and alignment more
2558 // favorable to atomic operations:
2559
2560 // Round the size up to a power of 2.
2561 Width = llvm::bit_ceil(Width);
2562
2563 // Set the alignment equal to the size.
2564 Align = static_cast<unsigned>(Width);
2565 }
2566 }
2567 break;
2568
2569 case Type::PredefinedSugar:
2570 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2571
2572 case Type::Pipe:
2573 Width = Target->getPointerWidth(LangAS::opencl_global);
2574 Align = Target->getPointerAlign(LangAS::opencl_global);
2575 break;
2576 }
2577
2578 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2579 return TypeInfo(Width, Align, AlignRequirement);
2580}
2581
2583 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2584 if (I != MemoizedUnadjustedAlign.end())
2585 return I->second;
2586
2587 unsigned UnadjustedAlign;
2588 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2589 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2590 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2591 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2592 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2593 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2594 } else {
2595 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2596 }
2597
2598 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2599 return UnadjustedAlign;
2600}
2601
2603 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2604 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2605 return SimdAlign;
2606}
2607
2608/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2610 return CharUnits::fromQuantity(BitSize / getCharWidth());
2611}
2612
2613/// toBits - Convert a size in characters to a size in characters.
2614int64_t ASTContext::toBits(CharUnits CharSize) const {
2615 return CharSize.getQuantity() * getCharWidth();
2616}
2617
2618/// getTypeSizeInChars - Return the size of the specified type, in characters.
2619/// This method does not work on incomplete types.
2626
2627/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2628/// characters. This method does not work on incomplete types.
2635
2636/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2637/// type, in characters, before alignment adjustments. This method does
2638/// not work on incomplete types.
2645
2646/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2647/// type for the current target in bits. This can be different than the ABI
2648/// alignment in cases where it is beneficial for performance or backwards
2649/// compatibility preserving to overalign a data type. (Note: despite the name,
2650/// the preferred alignment is ABI-impacting, and not an optimization.)
2651unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2652 TypeInfo TI = getTypeInfo(T);
2653 unsigned ABIAlign = TI.Align;
2654
2655 T = T->getBaseElementTypeUnsafe();
2656
2657 // The preferred alignment of member pointers is that of a pointer.
2658 if (T->isMemberPointerType())
2659 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2660
2661 if (!Target->allowsLargerPreferedTypeAlignment())
2662 return ABIAlign;
2663
2664 if (const auto *RD = T->getAsRecordDecl()) {
2665 // When used as part of a typedef, or together with a 'packed' attribute,
2666 // the 'aligned' attribute can be used to decrease alignment. Note that the
2667 // 'packed' case is already taken into consideration when computing the
2668 // alignment, we only need to handle the typedef case here.
2670 RD->isInvalidDecl())
2671 return ABIAlign;
2672
2673 unsigned PreferredAlign = static_cast<unsigned>(
2674 toBits(getASTRecordLayout(RD).PreferredAlignment));
2675 assert(PreferredAlign >= ABIAlign &&
2676 "PreferredAlign should be at least as large as ABIAlign.");
2677 return PreferredAlign;
2678 }
2679
2680 // Double (and, for targets supporting AIX `power` alignment, long double) and
2681 // long long should be naturally aligned (despite requiring less alignment) if
2682 // possible.
2683 if (const auto *CT = T->getAs<ComplexType>())
2684 T = CT->getElementType().getTypePtr();
2685 if (const auto *ED = T->getAsEnumDecl())
2686 T = ED->getIntegerType().getTypePtr();
2687 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2688 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2689 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2690 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2691 Target->defaultsToAIXPowerAlignment()))
2692 // Don't increase the alignment if an alignment attribute was specified on a
2693 // typedef declaration.
2694 if (!TI.isAlignRequired())
2695 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2696
2697 return ABIAlign;
2698}
2699
2700/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2701/// for __attribute__((aligned)) on this target, to be used if no alignment
2702/// value is specified.
2706
2707/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2708/// to a global variable of the specified type.
2710 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2711 return std::max(getPreferredTypeAlign(T),
2712 getMinGlobalAlignOfVar(TypeSize, VD));
2713}
2714
2715/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2716/// should be given to a global variable of the specified type.
2721
2723 const VarDecl *VD) const {
2724 // Make the default handling as that of a non-weak definition in the
2725 // current translation unit.
2726 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2727 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2728}
2729
2731 CharUnits Offset = CharUnits::Zero();
2732 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2733 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2734 Offset += Layout->getBaseClassOffset(Base);
2735 Layout = &getASTRecordLayout(Base);
2736 }
2737 return Offset;
2738}
2739
2741 const ValueDecl *MPD = MP.getMemberPointerDecl();
2744 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2746 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2747 const CXXRecordDecl *Base = RD;
2748 const CXXRecordDecl *Derived = Path[I];
2749 if (DerivedMember)
2750 std::swap(Base, Derived);
2752 RD = Path[I];
2753 }
2754 if (DerivedMember)
2756 return ThisAdjustment;
2757}
2758
2759/// DeepCollectObjCIvars -
2760/// This routine first collects all declared, but not synthesized, ivars in
2761/// super class and then collects all ivars, including those synthesized for
2762/// current class. This routine is used for implementation of current class
2763/// when all ivars, declared and synthesized are known.
2765 bool leafClass,
2767 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2768 DeepCollectObjCIvars(SuperClass, false, Ivars);
2769 if (!leafClass) {
2770 llvm::append_range(Ivars, OI->ivars());
2771 } else {
2772 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2773 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2774 Iv= Iv->getNextIvar())
2775 Ivars.push_back(Iv);
2776 }
2777}
2778
2779/// CollectInheritedProtocols - Collect all protocols in current class and
2780/// those inherited by it.
2783 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2784 // We can use protocol_iterator here instead of
2785 // all_referenced_protocol_iterator since we are walking all categories.
2786 for (auto *Proto : OI->all_referenced_protocols()) {
2787 CollectInheritedProtocols(Proto, Protocols);
2788 }
2789
2790 // Categories of this Interface.
2791 for (const auto *Cat : OI->visible_categories())
2792 CollectInheritedProtocols(Cat, Protocols);
2793
2794 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2795 while (SD) {
2796 CollectInheritedProtocols(SD, Protocols);
2797 SD = SD->getSuperClass();
2798 }
2799 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2800 for (auto *Proto : OC->protocols()) {
2801 CollectInheritedProtocols(Proto, Protocols);
2802 }
2803 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2804 // Insert the protocol.
2805 if (!Protocols.insert(
2806 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2807 return;
2808
2809 for (auto *Proto : OP->protocols())
2810 CollectInheritedProtocols(Proto, Protocols);
2811 }
2812}
2813
2815 const RecordDecl *RD,
2816 bool CheckIfTriviallyCopyable) {
2817 assert(RD->isUnion() && "Must be union type");
2818 CharUnits UnionSize =
2819 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2820
2821 for (const auto *Field : RD->fields()) {
2822 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2823 CheckIfTriviallyCopyable))
2824 return false;
2825 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2826 if (FieldSize != UnionSize)
2827 return false;
2828 }
2829 return !RD->field_empty();
2830}
2831
2832static int64_t getSubobjectOffset(const FieldDecl *Field,
2833 const ASTContext &Context,
2834 const clang::ASTRecordLayout & /*Layout*/) {
2835 return Context.getFieldOffset(Field);
2836}
2837
2838static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2839 const ASTContext &Context,
2840 const clang::ASTRecordLayout &Layout) {
2841 return Context.toBits(Layout.getBaseClassOffset(RD));
2842}
2843
2844static std::optional<int64_t>
2846 const RecordDecl *RD,
2847 bool CheckIfTriviallyCopyable);
2848
2849static std::optional<int64_t>
2850getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2851 bool CheckIfTriviallyCopyable) {
2852 if (const auto *RD = Field->getType()->getAsRecordDecl();
2853 RD && !RD->isUnion())
2854 return structHasUniqueObjectRepresentations(Context, RD,
2855 CheckIfTriviallyCopyable);
2856
2857 // A _BitInt type may not be unique if it has padding bits
2858 // but if it is a bitfield the padding bits are not used.
2859 bool IsBitIntType = Field->getType()->isBitIntType();
2860 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2861 !Context.hasUniqueObjectRepresentations(Field->getType(),
2862 CheckIfTriviallyCopyable))
2863 return std::nullopt;
2864
2865 int64_t FieldSizeInBits =
2866 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2867 if (Field->isBitField()) {
2868 // If we have explicit padding bits, they don't contribute bits
2869 // to the actual object representation, so return 0.
2870 if (Field->isUnnamedBitField())
2871 return 0;
2872
2873 int64_t BitfieldSize = Field->getBitWidthValue();
2874 if (IsBitIntType) {
2875 if ((unsigned)BitfieldSize >
2876 cast<BitIntType>(Field->getType())->getNumBits())
2877 return std::nullopt;
2878 } else if (BitfieldSize > FieldSizeInBits) {
2879 return std::nullopt;
2880 }
2881 FieldSizeInBits = BitfieldSize;
2882 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2883 Field->getType(), CheckIfTriviallyCopyable)) {
2884 return std::nullopt;
2885 }
2886 return FieldSizeInBits;
2887}
2888
2889static std::optional<int64_t>
2891 bool CheckIfTriviallyCopyable) {
2892 return structHasUniqueObjectRepresentations(Context, RD,
2893 CheckIfTriviallyCopyable);
2894}
2895
2896template <typename RangeT>
2898 const RangeT &Subobjects, int64_t CurOffsetInBits,
2899 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2900 bool CheckIfTriviallyCopyable) {
2901 for (const auto *Subobject : Subobjects) {
2902 std::optional<int64_t> SizeInBits =
2903 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2904 if (!SizeInBits)
2905 return std::nullopt;
2906 if (*SizeInBits != 0) {
2907 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2908 if (Offset != CurOffsetInBits)
2909 return std::nullopt;
2910 CurOffsetInBits += *SizeInBits;
2911 }
2912 }
2913 return CurOffsetInBits;
2914}
2915
2916static std::optional<int64_t>
2918 const RecordDecl *RD,
2919 bool CheckIfTriviallyCopyable) {
2920 assert(!RD->isUnion() && "Must be struct/class type");
2921 const auto &Layout = Context.getASTRecordLayout(RD);
2922
2923 int64_t CurOffsetInBits = 0;
2924 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2925 if (ClassDecl->isDynamicClass())
2926 return std::nullopt;
2927
2929 for (const auto &Base : ClassDecl->bases()) {
2930 // Empty types can be inherited from, and non-empty types can potentially
2931 // have tail padding, so just make sure there isn't an error.
2932 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2933 }
2934
2935 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2936 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2937 });
2938
2939 std::optional<int64_t> OffsetAfterBases =
2941 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2942 if (!OffsetAfterBases)
2943 return std::nullopt;
2944 CurOffsetInBits = *OffsetAfterBases;
2945 }
2946
2947 std::optional<int64_t> OffsetAfterFields =
2949 RD->fields(), CurOffsetInBits, Context, Layout,
2950 CheckIfTriviallyCopyable);
2951 if (!OffsetAfterFields)
2952 return std::nullopt;
2953 CurOffsetInBits = *OffsetAfterFields;
2954
2955 return CurOffsetInBits;
2956}
2957
2959 QualType Ty, bool CheckIfTriviallyCopyable) const {
2960 // C++17 [meta.unary.prop]:
2961 // The predicate condition for a template specialization
2962 // has_unique_object_representations<T> shall be satisfied if and only if:
2963 // (9.1) - T is trivially copyable, and
2964 // (9.2) - any two objects of type T with the same value have the same
2965 // object representation, where:
2966 // - two objects of array or non-union class type are considered to have
2967 // the same value if their respective sequences of direct subobjects
2968 // have the same values, and
2969 // - two objects of union type are considered to have the same value if
2970 // they have the same active member and the corresponding members have
2971 // the same value.
2972 // The set of scalar types for which this condition holds is
2973 // implementation-defined. [ Note: If a type has padding bits, the condition
2974 // does not hold; otherwise, the condition holds true for unsigned integral
2975 // types. -- end note ]
2976 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2977
2978 // Arrays are unique only if their element type is unique.
2979 if (Ty->isArrayType())
2981 CheckIfTriviallyCopyable);
2982
2983 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2984 "hasUniqueObjectRepresentations should not be called with an "
2985 "incomplete type");
2986
2987 // (9.1) - T is trivially copyable...
2988 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2989 return false;
2990
2991 // All integrals and enums are unique.
2992 if (Ty->isIntegralOrEnumerationType()) {
2993 // Address discriminated integer types are not unique.
2995 return false;
2996 // Except _BitInt types that have padding bits.
2997 if (const auto *BIT = Ty->getAs<BitIntType>())
2998 return getTypeSize(BIT) == BIT->getNumBits();
2999
3000 return true;
3001 }
3002
3003 // All other pointers are unique.
3004 if (Ty->isPointerType())
3006
3007 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3008 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3009
3010 if (const auto *Record = Ty->getAsRecordDecl()) {
3011 if (Record->isInvalidDecl())
3012 return false;
3013
3014 if (Record->isUnion())
3016 CheckIfTriviallyCopyable);
3017
3018 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3019 *this, Record, CheckIfTriviallyCopyable);
3020
3021 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3022 }
3023
3024 // FIXME: More cases to handle here (list by rsmith):
3025 // vectors (careful about, eg, vector of 3 foo)
3026 // _Complex int and friends
3027 // _Atomic T
3028 // Obj-C block pointers
3029 // Obj-C object pointers
3030 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3031 // clk_event_t, queue_t, reserve_id_t)
3032 // There're also Obj-C class types and the Obj-C selector type, but I think it
3033 // makes sense for those to return false here.
3034
3035 return false;
3036}
3037
3039 unsigned count = 0;
3040 // Count ivars declared in class extension.
3041 for (const auto *Ext : OI->known_extensions())
3042 count += Ext->ivar_size();
3043
3044 // Count ivar defined in this class's implementation. This
3045 // includes synthesized ivars.
3046 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3047 count += ImplDecl->ivar_size();
3048
3049 return count;
3050}
3051
3053 if (!E)
3054 return false;
3055
3056 // nullptr_t is always treated as null.
3057 if (E->getType()->isNullPtrType()) return true;
3058
3059 if (E->getType()->isAnyPointerType() &&
3062 return true;
3063
3064 // Unfortunately, __null has type 'int'.
3065 if (isa<GNUNullExpr>(E)) return true;
3066
3067 return false;
3068}
3069
3070/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3071/// exists.
3073 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3074 I = ObjCImpls.find(D);
3075 if (I != ObjCImpls.end())
3076 return cast<ObjCImplementationDecl>(I->second);
3077 return nullptr;
3078}
3079
3080/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3081/// exists.
3083 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3084 I = ObjCImpls.find(D);
3085 if (I != ObjCImpls.end())
3086 return cast<ObjCCategoryImplDecl>(I->second);
3087 return nullptr;
3088}
3089
3090/// Set the implementation of ObjCInterfaceDecl.
3092 ObjCImplementationDecl *ImplD) {
3093 assert(IFaceD && ImplD && "Passed null params");
3094 ObjCImpls[IFaceD] = ImplD;
3095}
3096
3097/// Set the implementation of ObjCCategoryDecl.
3099 ObjCCategoryImplDecl *ImplD) {
3100 assert(CatD && ImplD && "Passed null params");
3101 ObjCImpls[CatD] = ImplD;
3102}
3103
3104const ObjCMethodDecl *
3106 return ObjCMethodRedecls.lookup(MD);
3107}
3108
3110 const ObjCMethodDecl *Redecl) {
3111 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3112 ObjCMethodRedecls[MD] = Redecl;
3113}
3114
3116 const NamedDecl *ND) const {
3117 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3118 return ID;
3119 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3120 return CD->getClassInterface();
3121 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3122 return IMD->getClassInterface();
3123
3124 return nullptr;
3125}
3126
3127/// Get the copy initialization expression of VarDecl, or nullptr if
3128/// none exists.
3130 assert(VD && "Passed null params");
3131 assert(VD->hasAttr<BlocksAttr>() &&
3132 "getBlockVarCopyInits - not __block var");
3133 auto I = BlockVarCopyInits.find(VD);
3134 if (I != BlockVarCopyInits.end())
3135 return I->second;
3136 return {nullptr, false};
3137}
3138
3139/// Set the copy initialization expression of a block var decl.
3141 bool CanThrow) {
3142 assert(VD && CopyExpr && "Passed null params");
3143 assert(VD->hasAttr<BlocksAttr>() &&
3144 "setBlockVarCopyInits - not __block var");
3145 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3146}
3147
3149 unsigned DataSize) const {
3150 if (!DataSize)
3151 DataSize = TypeLoc::getFullDataSizeForType(T);
3152 else
3153 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3154 "incorrect data size provided to CreateTypeSourceInfo!");
3155
3156 auto *TInfo =
3157 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3158 new (TInfo) TypeSourceInfo(T, DataSize);
3159 return TInfo;
3160}
3161
3163 SourceLocation L) const {
3165 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3166 return TSI;
3167}
3168
3169const ASTRecordLayout &
3171 return getObjCLayout(D);
3172}
3173
3176 bool &AnyNonCanonArgs) {
3177 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3178 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3179 return CanonArgs;
3180}
3181
3184 bool AnyNonCanonArgs = false;
3185 for (auto &Arg : Args) {
3186 TemplateArgument OrigArg = Arg;
3188 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3189 }
3190 return AnyNonCanonArgs;
3191}
3192
3193//===----------------------------------------------------------------------===//
3194// Type creation/memoization methods
3195//===----------------------------------------------------------------------===//
3196
3198ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3199 unsigned fastQuals = quals.getFastQualifiers();
3200 quals.removeFastQualifiers();
3201
3202 // Check if we've already instantiated this type.
3203 llvm::FoldingSetNodeID ID;
3204 ExtQuals::Profile(ID, baseType, quals);
3205 void *insertPos = nullptr;
3206 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3207 assert(eq->getQualifiers() == quals);
3208 return QualType(eq, fastQuals);
3209 }
3210
3211 // If the base type is not canonical, make the appropriate canonical type.
3212 QualType canon;
3213 if (!baseType->isCanonicalUnqualified()) {
3214 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3215 canonSplit.Quals.addConsistentQualifiers(quals);
3216 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3217
3218 // Re-find the insert position.
3219 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3220 }
3221
3222 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3223 ExtQualNodes.InsertNode(eq, insertPos);
3224 return QualType(eq, fastQuals);
3225}
3226
3228 LangAS AddressSpace) const {
3229 QualType CanT = getCanonicalType(T);
3230 if (CanT.getAddressSpace() == AddressSpace)
3231 return T;
3232
3233 // If we are composing extended qualifiers together, merge together
3234 // into one ExtQuals node.
3235 QualifierCollector Quals;
3236 const Type *TypeNode = Quals.strip(T);
3237
3238 // If this type already has an address space specified, it cannot get
3239 // another one.
3240 assert(!Quals.hasAddressSpace() &&
3241 "Type cannot be in multiple addr spaces!");
3242 Quals.addAddressSpace(AddressSpace);
3243
3244 return getExtQualType(TypeNode, Quals);
3245}
3246
3248 // If the type is not qualified with an address space, just return it
3249 // immediately.
3250 if (!T.hasAddressSpace())
3251 return T;
3252
3253 QualifierCollector Quals;
3254 const Type *TypeNode;
3255 // For arrays, strip the qualifier off the element type, then reconstruct the
3256 // array type
3257 if (T.getTypePtr()->isArrayType()) {
3258 T = getUnqualifiedArrayType(T, Quals);
3259 TypeNode = T.getTypePtr();
3260 } else {
3261 // If we are composing extended qualifiers together, merge together
3262 // into one ExtQuals node.
3263 while (T.hasAddressSpace()) {
3264 TypeNode = Quals.strip(T);
3265
3266 // If the type no longer has an address space after stripping qualifiers,
3267 // jump out.
3268 if (!QualType(TypeNode, 0).hasAddressSpace())
3269 break;
3270
3271 // There might be sugar in the way. Strip it and try again.
3272 T = T.getSingleStepDesugaredType(*this);
3273 }
3274 }
3275
3276 Quals.removeAddressSpace();
3277
3278 // Removal of the address space can mean there are no longer any
3279 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3280 // or required.
3281 if (Quals.hasNonFastQualifiers())
3282 return getExtQualType(TypeNode, Quals);
3283 else
3284 return QualType(TypeNode, Quals.getFastQualifiers());
3285}
3286
3287uint16_t
3289 assert(RD->isPolymorphic() &&
3290 "Attempted to get vtable pointer discriminator on a monomorphic type");
3291 std::unique_ptr<MangleContext> MC(createMangleContext());
3292 SmallString<256> Str;
3293 llvm::raw_svector_ostream Out(Str);
3294 MC->mangleCXXVTable(RD, Out);
3295 return llvm::getPointerAuthStableSipHash(Str);
3296}
3297
3298/// Encode a function type for use in the discriminator of a function pointer
3299/// type. We can't use the itanium scheme for this since C has quite permissive
3300/// rules for type compatibility that we need to be compatible with.
3301///
3302/// Formally, this function associates every function pointer type T with an
3303/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3304/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3305/// compatibility requires equivalent treatment under the ABI, so
3306/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3307/// a subset of ~. Crucially, however, it must be a proper subset because
3308/// CCompatible is not an equivalence relation: for example, int[] is compatible
3309/// with both int[1] and int[2], but the latter are not compatible with each
3310/// other. Therefore this encoding function must be careful to only distinguish
3311/// types if there is no third type with which they are both required to be
3312/// compatible.
3314 raw_ostream &OS, QualType QT) {
3315 // FIXME: Consider address space qualifiers.
3316 const Type *T = QT.getCanonicalType().getTypePtr();
3317
3318 // FIXME: Consider using the C++ type mangling when we encounter a construct
3319 // that is incompatible with C.
3320
3321 switch (T->getTypeClass()) {
3322 case Type::Atomic:
3324 Ctx, OS, cast<AtomicType>(T)->getValueType());
3325
3326 case Type::LValueReference:
3327 OS << "R";
3330 return;
3331 case Type::RValueReference:
3332 OS << "O";
3335 return;
3336
3337 case Type::Pointer:
3338 // C11 6.7.6.1p2:
3339 // For two pointer types to be compatible, both shall be identically
3340 // qualified and both shall be pointers to compatible types.
3341 // FIXME: we should also consider pointee types.
3342 OS << "P";
3343 return;
3344
3345 case Type::ObjCObjectPointer:
3346 case Type::BlockPointer:
3347 OS << "P";
3348 return;
3349
3350 case Type::Complex:
3351 OS << "C";
3353 Ctx, OS, cast<ComplexType>(T)->getElementType());
3354
3355 case Type::VariableArray:
3356 case Type::ConstantArray:
3357 case Type::IncompleteArray:
3358 case Type::ArrayParameter:
3359 // C11 6.7.6.2p6:
3360 // For two array types to be compatible, both shall have compatible
3361 // element types, and if both size specifiers are present, and are integer
3362 // constant expressions, then both size specifiers shall have the same
3363 // constant value [...]
3364 //
3365 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3366 // width of the array.
3367 OS << "A";
3369 Ctx, OS, cast<ArrayType>(T)->getElementType());
3370
3371 case Type::ObjCInterface:
3372 case Type::ObjCObject:
3373 OS << "<objc_object>";
3374 return;
3375
3376 case Type::Enum: {
3377 // C11 6.7.2.2p4:
3378 // Each enumerated type shall be compatible with char, a signed integer
3379 // type, or an unsigned integer type.
3380 //
3381 // So we have to treat enum types as integers.
3382 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3384 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3385 }
3386
3387 case Type::FunctionNoProto:
3388 case Type::FunctionProto: {
3389 // C11 6.7.6.3p15:
3390 // For two function types to be compatible, both shall specify compatible
3391 // return types. Moreover, the parameter type lists, if both are present,
3392 // shall agree in the number of parameters and in the use of the ellipsis
3393 // terminator; corresponding parameters shall have compatible types.
3394 //
3395 // That paragraph goes on to describe how unprototyped functions are to be
3396 // handled, which we ignore here. Unprototyped function pointers are hashed
3397 // as though they were prototyped nullary functions since thats probably
3398 // what the user meant. This behavior is non-conforming.
3399 // FIXME: If we add a "custom discriminator" function type attribute we
3400 // should encode functions as their discriminators.
3401 OS << "F";
3402 const auto *FuncType = cast<FunctionType>(T);
3403 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3404 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3405 for (QualType Param : FPT->param_types()) {
3406 Param = Ctx.getSignatureParameterType(Param);
3407 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3408 }
3409 if (FPT->isVariadic())
3410 OS << "z";
3411 }
3412 OS << "E";
3413 return;
3414 }
3415
3416 case Type::MemberPointer: {
3417 OS << "M";
3418 const auto *MPT = T->castAs<MemberPointerType>();
3420 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3421 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3422 return;
3423 }
3424 case Type::ExtVector:
3425 case Type::Vector:
3426 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3427 break;
3428
3429 // Don't bother discriminating based on these types.
3430 case Type::Pipe:
3431 case Type::BitInt:
3432 case Type::ConstantMatrix:
3433 OS << "?";
3434 return;
3435
3436 case Type::Builtin: {
3437 const auto *BTy = T->castAs<BuiltinType>();
3438 switch (BTy->getKind()) {
3439#define SIGNED_TYPE(Id, SingletonId) \
3440 case BuiltinType::Id: \
3441 OS << "i"; \
3442 return;
3443#define UNSIGNED_TYPE(Id, SingletonId) \
3444 case BuiltinType::Id: \
3445 OS << "i"; \
3446 return;
3447#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3448#define BUILTIN_TYPE(Id, SingletonId)
3449#include "clang/AST/BuiltinTypes.def"
3450 llvm_unreachable("placeholder types should not appear here.");
3451
3452 case BuiltinType::Half:
3453 OS << "Dh";
3454 return;
3455 case BuiltinType::Float:
3456 OS << "f";
3457 return;
3458 case BuiltinType::Double:
3459 OS << "d";
3460 return;
3461 case BuiltinType::LongDouble:
3462 OS << "e";
3463 return;
3464 case BuiltinType::Float16:
3465 OS << "DF16_";
3466 return;
3467 case BuiltinType::Float128:
3468 OS << "g";
3469 return;
3470
3471 case BuiltinType::Void:
3472 OS << "v";
3473 return;
3474
3475 case BuiltinType::ObjCId:
3476 case BuiltinType::ObjCClass:
3477 case BuiltinType::ObjCSel:
3478 case BuiltinType::NullPtr:
3479 OS << "P";
3480 return;
3481
3482 // Don't bother discriminating based on OpenCL types.
3483 case BuiltinType::OCLSampler:
3484 case BuiltinType::OCLEvent:
3485 case BuiltinType::OCLClkEvent:
3486 case BuiltinType::OCLQueue:
3487 case BuiltinType::OCLReserveID:
3488 case BuiltinType::BFloat16:
3489 case BuiltinType::VectorQuad:
3490 case BuiltinType::VectorPair:
3491 case BuiltinType::DMR1024:
3492 case BuiltinType::DMR2048:
3493 OS << "?";
3494 return;
3495
3496 // Don't bother discriminating based on these seldom-used types.
3497 case BuiltinType::Ibm128:
3498 return;
3499#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3500 case BuiltinType::Id: \
3501 return;
3502#include "clang/Basic/OpenCLImageTypes.def"
3503#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3504 case BuiltinType::Id: \
3505 return;
3506#include "clang/Basic/OpenCLExtensionTypes.def"
3507#define SVE_TYPE(Name, Id, SingletonId) \
3508 case BuiltinType::Id: \
3509 return;
3510#include "clang/Basic/AArch64ACLETypes.def"
3511#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3512 case BuiltinType::Id: \
3513 return;
3514#include "clang/Basic/HLSLIntangibleTypes.def"
3515 case BuiltinType::Dependent:
3516 llvm_unreachable("should never get here");
3517#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3518#include "clang/Basic/AMDGPUTypes.def"
3519 case BuiltinType::WasmExternRef:
3520#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3521#include "clang/Basic/RISCVVTypes.def"
3522 llvm_unreachable("not yet implemented");
3523 }
3524 llvm_unreachable("should never get here");
3525 }
3526 case Type::Record: {
3527 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3528 const IdentifierInfo *II = RD->getIdentifier();
3529
3530 // In C++, an immediate typedef of an anonymous struct or union
3531 // is considered to name it for ODR purposes, but C's specification
3532 // of type compatibility does not have a similar rule. Using the typedef
3533 // name in function type discriminators anyway, as we do here,
3534 // therefore technically violates the C standard: two function pointer
3535 // types defined in terms of two typedef'd anonymous structs with
3536 // different names are formally still compatible, but we are assigning
3537 // them different discriminators and therefore incompatible ABIs.
3538 //
3539 // This is a relatively minor violation that significantly improves
3540 // discrimination in some cases and has not caused problems in
3541 // practice. Regardless, it is now part of the ABI in places where
3542 // function type discrimination is used, and it can no longer be
3543 // changed except on new platforms.
3544
3545 if (!II)
3546 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3547 II = Typedef->getDeclName().getAsIdentifierInfo();
3548
3549 if (!II) {
3550 OS << "<anonymous_record>";
3551 return;
3552 }
3553 OS << II->getLength() << II->getName();
3554 return;
3555 }
3556 case Type::HLSLAttributedResource:
3557 case Type::HLSLInlineSpirv:
3558 llvm_unreachable("should never get here");
3559 break;
3560 case Type::OverflowBehavior:
3561 llvm_unreachable("should never get here");
3562 break;
3563 case Type::DeducedTemplateSpecialization:
3564 case Type::Auto:
3565#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3567#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3568#define ABSTRACT_TYPE(Class, Base)
3569#define TYPE(Class, Base)
3570#include "clang/AST/TypeNodes.inc"
3571 llvm_unreachable("unexpected non-canonical or dependent type!");
3572 return;
3573 }
3574}
3575
3577 assert(!T->isDependentType() &&
3578 "cannot compute type discriminator of a dependent type");
3579 SmallString<256> Str;
3580 llvm::raw_svector_ostream Out(Str);
3581
3582 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3583 T = T->getPointeeType();
3584
3585 if (T->isFunctionType()) {
3586 encodeTypeForFunctionPointerAuth(*this, Out, T);
3587 } else {
3588 T = T.getUnqualifiedType();
3589 // Calls to member function pointers don't need to worry about
3590 // language interop or the laxness of the C type compatibility rules.
3591 // We just mangle the member pointer type directly, which is
3592 // implicitly much stricter about type matching. However, we do
3593 // strip any top-level exception specification before this mangling.
3594 // C++23 requires calls to work when the function type is convertible
3595 // to the pointer type by a function pointer conversion, which can
3596 // change the exception specification. This does not technically
3597 // require the exception specification to not affect representation,
3598 // because the function pointer conversion is still always a direct
3599 // value conversion and therefore an opportunity to resign the
3600 // pointer. (This is in contrast to e.g. qualification conversions,
3601 // which can be applied in nested pointer positions, effectively
3602 // requiring qualified and unqualified representations to match.)
3603 // However, it is pragmatic to ignore exception specifications
3604 // because it allows a certain amount of `noexcept` mismatching
3605 // to not become a visible ODR problem. This also leaves some
3606 // room for the committee to add laxness to function pointer
3607 // conversions in future standards.
3608 if (auto *MPT = T->getAs<MemberPointerType>())
3609 if (MPT->isMemberFunctionPointer()) {
3610 QualType PointeeType = MPT->getPointeeType();
3611 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3612 EST_None) {
3614 T = getMemberPointerType(FT, MPT->getQualifier(),
3615 MPT->getMostRecentCXXRecordDecl());
3616 }
3617 }
3618 std::unique_ptr<MangleContext> MC(createMangleContext());
3619 MC->mangleCanonicalTypeName(T, Out);
3620 }
3621
3622 return llvm::getPointerAuthStableSipHash(Str);
3623}
3624
3626 Qualifiers::GC GCAttr) const {
3627 QualType CanT = getCanonicalType(T);
3628 if (CanT.getObjCGCAttr() == GCAttr)
3629 return T;
3630
3631 if (const auto *ptr = T->getAs<PointerType>()) {
3632 QualType Pointee = ptr->getPointeeType();
3633 if (Pointee->isAnyPointerType()) {
3634 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3635 return getPointerType(ResultType);
3636 }
3637 }
3638
3639 // If we are composing extended qualifiers together, merge together
3640 // into one ExtQuals node.
3641 QualifierCollector Quals;
3642 const Type *TypeNode = Quals.strip(T);
3643
3644 // If this type already has an ObjCGC specified, it cannot get
3645 // another one.
3646 assert(!Quals.hasObjCGCAttr() &&
3647 "Type cannot have multiple ObjCGCs!");
3648 Quals.addObjCGCAttr(GCAttr);
3649
3650 return getExtQualType(TypeNode, Quals);
3651}
3652
3654 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3655 QualType Pointee = Ptr->getPointeeType();
3656 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3657 return getPointerType(removeAddrSpaceQualType(Pointee));
3658 }
3659 }
3660 return T;
3661}
3662
3664 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3665 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3666 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3667
3668 llvm::FoldingSetNodeID ID;
3669 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3670
3671 void *InsertPos = nullptr;
3672 CountAttributedType *CATy =
3673 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3674 if (CATy)
3675 return QualType(CATy, 0);
3676
3677 QualType CanonTy = getCanonicalType(WrappedTy);
3678 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3679 DependentDecls.size());
3681 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3682 OrNull, DependentDecls);
3683 Types.push_back(CATy);
3684 CountAttributedTypes.InsertNode(CATy, InsertPos);
3685
3686 return QualType(CATy, 0);
3687}
3688
3691 llvm::function_ref<QualType(QualType)> Adjust) const {
3692 switch (Orig->getTypeClass()) {
3693 case Type::Attributed: {
3694 const auto *AT = cast<AttributedType>(Orig);
3695 return getAttributedType(AT->getAttrKind(),
3696 adjustType(AT->getModifiedType(), Adjust),
3697 adjustType(AT->getEquivalentType(), Adjust),
3698 AT->getAttr());
3699 }
3700
3701 case Type::BTFTagAttributed: {
3702 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3703 return getBTFTagAttributedType(BTFT->getAttr(),
3704 adjustType(BTFT->getWrappedType(), Adjust));
3705 }
3706
3707 case Type::OverflowBehavior: {
3708 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3709 return getOverflowBehaviorType(OB->getBehaviorKind(),
3710 adjustType(OB->getUnderlyingType(), Adjust));
3711 }
3712
3713 case Type::Paren:
3714 return getParenType(
3715 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3716
3717 case Type::Adjusted: {
3718 const auto *AT = cast<AdjustedType>(Orig);
3719 return getAdjustedType(AT->getOriginalType(),
3720 adjustType(AT->getAdjustedType(), Adjust));
3721 }
3722
3723 case Type::MacroQualified: {
3724 const auto *MQT = cast<MacroQualifiedType>(Orig);
3725 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3726 MQT->getMacroIdentifier());
3727 }
3728
3729 default:
3730 return Adjust(Orig);
3731 }
3732}
3733
3735 FunctionType::ExtInfo Info) {
3736 if (T->getExtInfo() == Info)
3737 return T;
3738
3740 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3741 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3742 } else {
3743 const auto *FPT = cast<FunctionProtoType>(T);
3744 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3745 EPI.ExtInfo = Info;
3746 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3747 }
3748
3749 return cast<FunctionType>(Result.getTypePtr());
3750}
3751
3753 QualType ResultType) {
3754 return adjustType(FunctionType, [&](QualType Orig) {
3755 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3756 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3757
3758 const auto *FPT = Orig->castAs<FunctionProtoType>();
3759 return getFunctionType(ResultType, FPT->getParamTypes(),
3760 FPT->getExtProtoInfo());
3761 });
3762}
3763
3765 QualType ResultType) {
3766 FD = FD->getMostRecentDecl();
3767 while (true) {
3768 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3769 if (FunctionDecl *Next = FD->getPreviousDecl())
3770 FD = Next;
3771 else
3772 break;
3773 }
3775 L->DeducedReturnType(FD, ResultType);
3776}
3777
3778/// Get a function type and produce the equivalent function type with the
3779/// specified exception specification. Type sugar that can be present on a
3780/// declaration of a function with an exception specification is permitted
3781/// and preserved. Other type sugar (for instance, typedefs) is not.
3783 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3784 return adjustType(Orig, [&](QualType Ty) {
3785 const auto *Proto = Ty->castAs<FunctionProtoType>();
3786 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3787 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3788 });
3789}
3790
3798
3800 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3801 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3802 SmallVector<QualType, 16> Args(Proto->param_types().size());
3803 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3804 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3805 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3806 }
3807
3808 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3809 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3810 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3811 }
3812
3813 return T;
3814}
3815
3821
3823 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3824 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3825 EPI.ExtParameterInfos = nullptr;
3826 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3827 }
3828 return T;
3829}
3830
3836
3839 bool AsWritten) {
3840 // Update the type.
3841 QualType Updated =
3843 FD->setType(Updated);
3844
3845 if (!AsWritten)
3846 return;
3847
3848 // Update the type in the type source information too.
3849 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3850 // If the type and the type-as-written differ, we may need to update
3851 // the type-as-written too.
3852 if (TSInfo->getType() != FD->getType())
3853 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3854
3855 // FIXME: When we get proper type location information for exceptions,
3856 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3857 // up the TypeSourceInfo;
3858 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3859 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3860 "TypeLoc size mismatch from updating exception specification");
3861 TSInfo->overrideType(Updated);
3862 }
3863}
3864
3865/// getComplexType - Return the uniqued reference to the type for a complex
3866/// number with the specified element type.
3868 // Unique pointers, to guarantee there is only one pointer of a particular
3869 // structure.
3870 llvm::FoldingSetNodeID ID;
3871 ComplexType::Profile(ID, T);
3872
3873 void *InsertPos = nullptr;
3874 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3875 return QualType(CT, 0);
3876
3877 // If the pointee type isn't canonical, this won't be a canonical type either,
3878 // so fill in the canonical type field.
3879 QualType Canonical;
3880 if (!T.isCanonical()) {
3881 Canonical = getComplexType(getCanonicalType(T));
3882
3883 // Get the new insert position for the node we care about.
3884 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3885 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3886 }
3887 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3888 Types.push_back(New);
3889 ComplexTypes.InsertNode(New, InsertPos);
3890 return QualType(New, 0);
3891}
3892
3893/// getPointerType - Return the uniqued reference to the type for a pointer to
3894/// the specified type.
3896 // Unique pointers, to guarantee there is only one pointer of a particular
3897 // structure.
3898 llvm::FoldingSetNodeID ID;
3899 PointerType::Profile(ID, T);
3900
3901 void *InsertPos = nullptr;
3902 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3903 return QualType(PT, 0);
3904
3905 // If the pointee type isn't canonical, this won't be a canonical type either,
3906 // so fill in the canonical type field.
3907 QualType Canonical;
3908 if (!T.isCanonical()) {
3909 Canonical = getPointerType(getCanonicalType(T));
3910
3911 // Get the new insert position for the node we care about.
3912 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3913 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3914 }
3915 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3916 Types.push_back(New);
3917 PointerTypes.InsertNode(New, InsertPos);
3918 return QualType(New, 0);
3919}
3920
3922 llvm::FoldingSetNodeID ID;
3923 AdjustedType::Profile(ID, Orig, New);
3924 void *InsertPos = nullptr;
3925 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3926 if (AT)
3927 return QualType(AT, 0);
3928
3929 QualType Canonical = getCanonicalType(New);
3930
3931 // Get the new insert position for the node we care about.
3932 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3933 assert(!AT && "Shouldn't be in the map!");
3934
3935 AT = new (*this, alignof(AdjustedType))
3936 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3937 Types.push_back(AT);
3938 AdjustedTypes.InsertNode(AT, InsertPos);
3939 return QualType(AT, 0);
3940}
3941
3943 llvm::FoldingSetNodeID ID;
3944 AdjustedType::Profile(ID, Orig, Decayed);
3945 void *InsertPos = nullptr;
3946 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3947 if (AT)
3948 return QualType(AT, 0);
3949
3950 QualType Canonical = getCanonicalType(Decayed);
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(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3957 Types.push_back(AT);
3958 AdjustedTypes.InsertNode(AT, InsertPos);
3959 return QualType(AT, 0);
3960}
3961
3963 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3964
3965 QualType Decayed;
3966
3967 // C99 6.7.5.3p7:
3968 // A declaration of a parameter as "array of type" shall be
3969 // adjusted to "qualified pointer to type", where the type
3970 // qualifiers (if any) are those specified within the [ and ] of
3971 // the array type derivation.
3972 if (T->isArrayType())
3973 Decayed = getArrayDecayedType(T);
3974
3975 // C99 6.7.5.3p8:
3976 // A declaration of a parameter as "function returning type"
3977 // shall be adjusted to "pointer to function returning type", as
3978 // in 6.3.2.1.
3979 if (T->isFunctionType())
3980 Decayed = getPointerType(T);
3981
3982 return getDecayedType(T, Decayed);
3983}
3984
3986 if (Ty->isArrayParameterType())
3987 return Ty;
3988 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3989 QualType DTy = Ty.getDesugaredType(*this);
3990 const auto *ATy = cast<ConstantArrayType>(DTy);
3991 llvm::FoldingSetNodeID ID;
3992 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3993 ATy->getSizeExpr(), ATy->getSizeModifier(),
3994 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3995 void *InsertPos = nullptr;
3996 ArrayParameterType *AT =
3997 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3998 if (AT)
3999 return QualType(AT, 0);
4000
4001 QualType Canonical;
4002 if (!DTy.isCanonical()) {
4003 Canonical = getArrayParameterType(getCanonicalType(Ty));
4004
4005 // Get the new insert position for the node we care about.
4006 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4007 assert(!AT && "Shouldn't be in the map!");
4008 }
4009
4010 AT = new (*this, alignof(ArrayParameterType))
4011 ArrayParameterType(ATy, Canonical);
4012 Types.push_back(AT);
4013 ArrayParameterTypes.InsertNode(AT, InsertPos);
4014 return QualType(AT, 0);
4015}
4016
4017/// getBlockPointerType - Return the uniqued reference to the type for
4018/// a pointer to the specified block.
4020 assert(T->isFunctionType() && "block of function types only");
4021 // Unique pointers, to guarantee there is only one block of a particular
4022 // structure.
4023 llvm::FoldingSetNodeID ID;
4025
4026 void *InsertPos = nullptr;
4027 if (BlockPointerType *PT =
4028 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4029 return QualType(PT, 0);
4030
4031 // If the block pointee type isn't canonical, this won't be a canonical
4032 // type either so fill in the canonical type field.
4033 QualType Canonical;
4034 if (!T.isCanonical()) {
4035 Canonical = getBlockPointerType(getCanonicalType(T));
4036
4037 // Get the new insert position for the node we care about.
4038 BlockPointerType *NewIP =
4039 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4040 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4041 }
4042 auto *New =
4043 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4044 Types.push_back(New);
4045 BlockPointerTypes.InsertNode(New, InsertPos);
4046 return QualType(New, 0);
4047}
4048
4049/// getLValueReferenceType - Return the uniqued reference to the type for an
4050/// lvalue reference to the specified type.
4052ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4053 assert((!T->isPlaceholderType() ||
4054 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4055 "Unresolved placeholder type");
4056
4057 // Unique pointers, to guarantee there is only one pointer of a particular
4058 // structure.
4059 llvm::FoldingSetNodeID ID;
4060 ReferenceType::Profile(ID, T, SpelledAsLValue);
4061
4062 void *InsertPos = nullptr;
4063 if (LValueReferenceType *RT =
4064 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4065 return QualType(RT, 0);
4066
4067 const auto *InnerRef = T->getAs<ReferenceType>();
4068
4069 // If the referencee type isn't canonical, this won't be a canonical type
4070 // either, so fill in the canonical type field.
4071 QualType Canonical;
4072 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4073 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4074 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4075
4076 // Get the new insert position for the node we care about.
4077 LValueReferenceType *NewIP =
4078 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4079 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4080 }
4081
4082 auto *New = new (*this, alignof(LValueReferenceType))
4083 LValueReferenceType(T, Canonical, SpelledAsLValue);
4084 Types.push_back(New);
4085 LValueReferenceTypes.InsertNode(New, InsertPos);
4086
4087 return QualType(New, 0);
4088}
4089
4090/// getRValueReferenceType - Return the uniqued reference to the type for an
4091/// rvalue reference to the specified type.
4093 assert((!T->isPlaceholderType() ||
4094 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4095 "Unresolved placeholder type");
4096
4097 // Unique pointers, to guarantee there is only one pointer of a particular
4098 // structure.
4099 llvm::FoldingSetNodeID ID;
4100 ReferenceType::Profile(ID, T, false);
4101
4102 void *InsertPos = nullptr;
4103 if (RValueReferenceType *RT =
4104 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4105 return QualType(RT, 0);
4106
4107 const auto *InnerRef = T->getAs<ReferenceType>();
4108
4109 // If the referencee type isn't canonical, this won't be a canonical type
4110 // either, so fill in the canonical type field.
4111 QualType Canonical;
4112 if (InnerRef || !T.isCanonical()) {
4113 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4114 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4115
4116 // Get the new insert position for the node we care about.
4117 RValueReferenceType *NewIP =
4118 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4119 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4120 }
4121
4122 auto *New = new (*this, alignof(RValueReferenceType))
4123 RValueReferenceType(T, Canonical);
4124 Types.push_back(New);
4125 RValueReferenceTypes.InsertNode(New, InsertPos);
4126 return QualType(New, 0);
4127}
4128
4130 NestedNameSpecifier Qualifier,
4131 const CXXRecordDecl *Cls) const {
4132 if (!Qualifier) {
4133 assert(Cls && "At least one of Qualifier or Cls must be provided");
4134 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4135 } else if (!Cls) {
4136 Cls = Qualifier.getAsRecordDecl();
4137 }
4138 // Unique pointers, to guarantee there is only one pointer of a particular
4139 // structure.
4140 llvm::FoldingSetNodeID ID;
4141 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4142
4143 void *InsertPos = nullptr;
4144 if (MemberPointerType *PT =
4145 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4146 return QualType(PT, 0);
4147
4148 NestedNameSpecifier CanonicalQualifier = [&] {
4149 if (!Cls)
4150 return Qualifier.getCanonical();
4151 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4152 assert(R.isCanonical());
4153 return R;
4154 }();
4155 // If the pointee or class type isn't canonical, this won't be a canonical
4156 // type either, so fill in the canonical type field.
4157 QualType Canonical;
4158 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4159 Canonical =
4160 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4161 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4162 // Get the new insert position for the node we care about.
4163 [[maybe_unused]] MemberPointerType *NewIP =
4164 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4165 assert(!NewIP && "Shouldn't be in the map!");
4166 }
4167 auto *New = new (*this, alignof(MemberPointerType))
4168 MemberPointerType(T, Qualifier, Canonical);
4169 Types.push_back(New);
4170 MemberPointerTypes.InsertNode(New, InsertPos);
4171 return QualType(New, 0);
4172}
4173
4174/// getConstantArrayType - Return the unique reference to the type for an
4175/// array of the specified element type.
4177 const llvm::APInt &ArySizeIn,
4178 const Expr *SizeExpr,
4180 unsigned IndexTypeQuals) const {
4181 assert((EltTy->isDependentType() ||
4182 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4183 "Constant array of VLAs is illegal!");
4184
4185 // We only need the size as part of the type if it's instantiation-dependent.
4186 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4187 SizeExpr = nullptr;
4188
4189 // Convert the array size into a canonical width matching the pointer size for
4190 // the target.
4191 llvm::APInt ArySize(ArySizeIn);
4192 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4193
4194 llvm::FoldingSetNodeID ID;
4195 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4196 ASM, IndexTypeQuals);
4197
4198 void *InsertPos = nullptr;
4199 if (ConstantArrayType *ATP =
4200 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4201 return QualType(ATP, 0);
4202
4203 // If the element type isn't canonical or has qualifiers, or the array bound
4204 // is instantiation-dependent, this won't be a canonical type either, so fill
4205 // in the canonical type field.
4206 QualType Canon;
4207 // FIXME: Check below should look for qualifiers behind sugar.
4208 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4209 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4210 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4211 ASM, IndexTypeQuals);
4212 Canon = getQualifiedType(Canon, canonSplit.Quals);
4213
4214 // Get the new insert position for the node we care about.
4215 ConstantArrayType *NewIP =
4216 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4217 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4218 }
4219
4220 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4221 ASM, IndexTypeQuals);
4222 ConstantArrayTypes.InsertNode(New, InsertPos);
4223 Types.push_back(New);
4224 return QualType(New, 0);
4225}
4226
4227/// getVariableArrayDecayedType - Turns the given type, which may be
4228/// variably-modified, into the corresponding type with all the known
4229/// sizes replaced with [*].
4231 // Vastly most common case.
4232 if (!type->isVariablyModifiedType()) return type;
4233
4234 QualType result;
4235
4236 SplitQualType split = type.getSplitDesugaredType();
4237 const Type *ty = split.Ty;
4238 switch (ty->getTypeClass()) {
4239#define TYPE(Class, Base)
4240#define ABSTRACT_TYPE(Class, Base)
4241#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4242#include "clang/AST/TypeNodes.inc"
4243 llvm_unreachable("didn't desugar past all non-canonical types?");
4244
4245 // These types should never be variably-modified.
4246 case Type::Builtin:
4247 case Type::Complex:
4248 case Type::Vector:
4249 case Type::DependentVector:
4250 case Type::ExtVector:
4251 case Type::DependentSizedExtVector:
4252 case Type::ConstantMatrix:
4253 case Type::DependentSizedMatrix:
4254 case Type::DependentAddressSpace:
4255 case Type::ObjCObject:
4256 case Type::ObjCInterface:
4257 case Type::ObjCObjectPointer:
4258 case Type::Record:
4259 case Type::Enum:
4260 case Type::UnresolvedUsing:
4261 case Type::TypeOfExpr:
4262 case Type::TypeOf:
4263 case Type::Decltype:
4264 case Type::UnaryTransform:
4265 case Type::DependentName:
4266 case Type::InjectedClassName:
4267 case Type::TemplateSpecialization:
4268 case Type::TemplateTypeParm:
4269 case Type::SubstTemplateTypeParmPack:
4270 case Type::SubstBuiltinTemplatePack:
4271 case Type::Auto:
4272 case Type::DeducedTemplateSpecialization:
4273 case Type::PackExpansion:
4274 case Type::PackIndexing:
4275 case Type::BitInt:
4276 case Type::DependentBitInt:
4277 case Type::ArrayParameter:
4278 case Type::HLSLAttributedResource:
4279 case Type::HLSLInlineSpirv:
4280 case Type::OverflowBehavior:
4281 llvm_unreachable("type should never be variably-modified");
4282
4283 // These types can be variably-modified but should never need to
4284 // further decay.
4285 case Type::FunctionNoProto:
4286 case Type::FunctionProto:
4287 case Type::BlockPointer:
4288 case Type::MemberPointer:
4289 case Type::Pipe:
4290 return type;
4291
4292 // These types can be variably-modified. All these modifications
4293 // preserve structure except as noted by comments.
4294 // TODO: if we ever care about optimizing VLAs, there are no-op
4295 // optimizations available here.
4296 case Type::Pointer:
4299 break;
4300
4301 case Type::LValueReference: {
4302 const auto *lv = cast<LValueReferenceType>(ty);
4303 result = getLValueReferenceType(
4304 getVariableArrayDecayedType(lv->getPointeeType()),
4305 lv->isSpelledAsLValue());
4306 break;
4307 }
4308
4309 case Type::RValueReference: {
4310 const auto *lv = cast<RValueReferenceType>(ty);
4311 result = getRValueReferenceType(
4312 getVariableArrayDecayedType(lv->getPointeeType()));
4313 break;
4314 }
4315
4316 case Type::Atomic: {
4317 const auto *at = cast<AtomicType>(ty);
4318 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4319 break;
4320 }
4321
4322 case Type::ConstantArray: {
4323 const auto *cat = cast<ConstantArrayType>(ty);
4324 result = getConstantArrayType(
4325 getVariableArrayDecayedType(cat->getElementType()),
4326 cat->getSize(),
4327 cat->getSizeExpr(),
4328 cat->getSizeModifier(),
4329 cat->getIndexTypeCVRQualifiers());
4330 break;
4331 }
4332
4333 case Type::DependentSizedArray: {
4334 const auto *dat = cast<DependentSizedArrayType>(ty);
4336 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4337 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4338 break;
4339 }
4340
4341 // Turn incomplete types into [*] types.
4342 case Type::IncompleteArray: {
4343 const auto *iat = cast<IncompleteArrayType>(ty);
4344 result =
4346 /*size*/ nullptr, ArraySizeModifier::Normal,
4347 iat->getIndexTypeCVRQualifiers());
4348 break;
4349 }
4350
4351 // Turn VLA types into [*] types.
4352 case Type::VariableArray: {
4353 const auto *vat = cast<VariableArrayType>(ty);
4354 result =
4356 /*size*/ nullptr, ArraySizeModifier::Star,
4357 vat->getIndexTypeCVRQualifiers());
4358 break;
4359 }
4360 }
4361
4362 // Apply the top-level qualifiers from the original.
4363 return getQualifiedType(result, split.Quals);
4364}
4365
4366/// getVariableArrayType - Returns a non-unique reference to the type for a
4367/// variable array of the specified element type.
4370 unsigned IndexTypeQuals) const {
4371 // Since we don't unique expressions, it isn't possible to unique VLA's
4372 // that have an expression provided for their size.
4373 QualType Canon;
4374
4375 // Be sure to pull qualifiers off the element type.
4376 // FIXME: Check below should look for qualifiers behind sugar.
4377 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4378 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4379 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4380 IndexTypeQuals);
4381 Canon = getQualifiedType(Canon, canonSplit.Quals);
4382 }
4383
4384 auto *New = new (*this, alignof(VariableArrayType))
4385 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4386
4387 VariableArrayTypes.push_back(New);
4388 Types.push_back(New);
4389 return QualType(New, 0);
4390}
4391
4392/// getDependentSizedArrayType - Returns a non-unique reference to
4393/// the type for a dependently-sized array of the specified element
4394/// type.
4398 unsigned elementTypeQuals) const {
4399 assert((!numElements || numElements->isTypeDependent() ||
4400 numElements->isValueDependent()) &&
4401 "Size must be type- or value-dependent!");
4402
4403 SplitQualType canonElementType = getCanonicalType(elementType).split();
4404
4405 void *insertPos = nullptr;
4406 llvm::FoldingSetNodeID ID;
4408 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4409 ASM, elementTypeQuals, numElements);
4410
4411 // Look for an existing type with these properties.
4412 DependentSizedArrayType *canonTy =
4413 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4414
4415 // Dependently-sized array types that do not have a specified number
4416 // of elements will have their sizes deduced from a dependent
4417 // initializer.
4418 if (!numElements) {
4419 if (canonTy)
4420 return QualType(canonTy, 0);
4421
4422 auto *newType = new (*this, alignof(DependentSizedArrayType))
4423 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4424 elementTypeQuals);
4425 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4426 Types.push_back(newType);
4427 return QualType(newType, 0);
4428 }
4429
4430 // If we don't have one, build one.
4431 if (!canonTy) {
4432 canonTy = new (*this, alignof(DependentSizedArrayType))
4433 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4434 numElements, ASM, elementTypeQuals);
4435 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4436 Types.push_back(canonTy);
4437 }
4438
4439 // Apply qualifiers from the element type to the array.
4440 QualType canon = getQualifiedType(QualType(canonTy,0),
4441 canonElementType.Quals);
4442
4443 // If we didn't need extra canonicalization for the element type or the size
4444 // expression, then just use that as our result.
4445 if (QualType(canonElementType.Ty, 0) == elementType &&
4446 canonTy->getSizeExpr() == numElements)
4447 return canon;
4448
4449 // Otherwise, we need to build a type which follows the spelling
4450 // of the element type.
4451 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4452 DependentSizedArrayType(elementType, canon, numElements, ASM,
4453 elementTypeQuals);
4454 Types.push_back(sugaredType);
4455 return QualType(sugaredType, 0);
4456}
4457
4460 unsigned elementTypeQuals) const {
4461 llvm::FoldingSetNodeID ID;
4462 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4463
4464 void *insertPos = nullptr;
4465 if (IncompleteArrayType *iat =
4466 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4467 return QualType(iat, 0);
4468
4469 // If the element type isn't canonical, this won't be a canonical type
4470 // either, so fill in the canonical type field. We also have to pull
4471 // qualifiers off the element type.
4472 QualType canon;
4473
4474 // FIXME: Check below should look for qualifiers behind sugar.
4475 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4476 SplitQualType canonSplit = getCanonicalType(elementType).split();
4477 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4478 ASM, elementTypeQuals);
4479 canon = getQualifiedType(canon, canonSplit.Quals);
4480
4481 // Get the new insert position for the node we care about.
4482 IncompleteArrayType *existing =
4483 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4484 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4485 }
4486
4487 auto *newType = new (*this, alignof(IncompleteArrayType))
4488 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4489
4490 IncompleteArrayTypes.InsertNode(newType, insertPos);
4491 Types.push_back(newType);
4492 return QualType(newType, 0);
4493}
4494
4497#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4498 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4499 NUMVECTORS};
4500
4501#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4502 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4503
4504 switch (Ty->getKind()) {
4505 default:
4506 llvm_unreachable("Unsupported builtin vector type");
4507
4508#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4509 ElBits, NF, IsSigned) \
4510 case BuiltinType::Id: \
4511 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4512 llvm::ElementCount::getScalable(NumEls), NF};
4513#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4514 ElBits, NF) \
4515 case BuiltinType::Id: \
4516 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4517 llvm::ElementCount::getScalable(NumEls), NF};
4518#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4519 ElBits, NF) \
4520 case BuiltinType::Id: \
4521 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4522#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4523 ElBits, NF) \
4524 case BuiltinType::Id: \
4525 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4526#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4527 case BuiltinType::Id: \
4528 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4529#include "clang/Basic/AArch64ACLETypes.def"
4530
4531#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4532 IsSigned) \
4533 case BuiltinType::Id: \
4534 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4535 llvm::ElementCount::getScalable(NumEls), NF};
4536#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4537 case BuiltinType::Id: \
4538 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4539 llvm::ElementCount::getScalable(NumEls), NF};
4540#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4541 case BuiltinType::Id: \
4542 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4543#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4544 case BuiltinType::Id: \
4545 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4546#include "clang/Basic/RISCVVTypes.def"
4547 }
4548}
4549
4550/// getExternrefType - Return a WebAssembly externref type, which represents an
4551/// opaque reference to a host value.
4553 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4554#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4555 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4556 return SingletonId;
4557#include "clang/Basic/WebAssemblyReferenceTypes.def"
4558 }
4559 llvm_unreachable(
4560 "shouldn't try to generate type externref outside WebAssembly target");
4561}
4562
4563/// getScalableVectorType - Return the unique reference to a scalable vector
4564/// type of the specified element type and size. VectorType must be a built-in
4565/// type.
4567 unsigned NumFields) const {
4568 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4569 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4570 return It->second;
4571
4572 if (Target->hasAArch64ACLETypes()) {
4573 uint64_t EltTySize = getTypeSize(EltTy);
4574
4575#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4576 ElBits, NF, IsSigned) \
4577 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4578 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4579 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4580 return ScalableVecTyMap[K] = SingletonId; \
4581 }
4582#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4583 ElBits, NF) \
4584 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4585 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4586 return ScalableVecTyMap[K] = SingletonId; \
4587 }
4588#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4589 ElBits, NF) \
4590 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4591 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4592 return ScalableVecTyMap[K] = SingletonId; \
4593 }
4594#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4595 ElBits, NF) \
4596 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4597 NumElts == (NumEls * NF) && NumFields == 1) { \
4598 return ScalableVecTyMap[K] = SingletonId; \
4599 }
4600#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4601 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4602 return ScalableVecTyMap[K] = SingletonId;
4603#include "clang/Basic/AArch64ACLETypes.def"
4604 } else if (Target->hasRISCVVTypes()) {
4605 uint64_t EltTySize = getTypeSize(EltTy);
4606#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4607 IsFP, IsBF) \
4608 if (!EltTy->isBooleanType() && \
4609 ((EltTy->hasIntegerRepresentation() && \
4610 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4611 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4612 IsFP && !IsBF) || \
4613 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4614 IsBF && !IsFP)) && \
4615 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4616 return ScalableVecTyMap[K] = SingletonId;
4617#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4618 if (EltTy->isBooleanType() && NumElts == NumEls) \
4619 return ScalableVecTyMap[K] = SingletonId;
4620#include "clang/Basic/RISCVVTypes.def"
4621 }
4622 return QualType();
4623}
4624
4625/// getVectorType - Return the unique reference to a vector type of
4626/// the specified element type and size. VectorType must be a built-in type.
4628 VectorKind VecKind) const {
4629 assert(vecType->isBuiltinType() ||
4630 (vecType->isBitIntType() &&
4631 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4632 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4633
4634 // Check if we've already instantiated a vector of this type.
4635 llvm::FoldingSetNodeID ID;
4636 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4637
4638 void *InsertPos = nullptr;
4639 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4640 return QualType(VTP, 0);
4641
4642 // If the element type isn't canonical, this won't be a canonical type either,
4643 // so fill in the canonical type field.
4644 QualType Canonical;
4645 if (!vecType.isCanonical()) {
4646 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4647
4648 // Get the new insert position for the node we care about.
4649 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4650 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4651 }
4652 auto *New = new (*this, alignof(VectorType))
4653 VectorType(vecType, NumElts, Canonical, VecKind);
4654 VectorTypes.InsertNode(New, InsertPos);
4655 Types.push_back(New);
4656 return QualType(New, 0);
4657}
4658
4660 SourceLocation AttrLoc,
4661 VectorKind VecKind) const {
4662 llvm::FoldingSetNodeID ID;
4663 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4664 VecKind);
4665 void *InsertPos = nullptr;
4666 DependentVectorType *Canon =
4667 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4669
4670 if (Canon) {
4671 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4672 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4673 } else {
4674 QualType CanonVecTy = getCanonicalType(VecType);
4675 if (CanonVecTy == VecType) {
4676 New = new (*this, alignof(DependentVectorType))
4677 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4678
4679 DependentVectorType *CanonCheck =
4680 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4681 assert(!CanonCheck &&
4682 "Dependent-sized vector_size canonical type broken");
4683 (void)CanonCheck;
4684 DependentVectorTypes.InsertNode(New, InsertPos);
4685 } else {
4686 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4687 SourceLocation(), VecKind);
4688 New = new (*this, alignof(DependentVectorType))
4689 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4690 }
4691 }
4692
4693 Types.push_back(New);
4694 return QualType(New, 0);
4695}
4696
4697/// getExtVectorType - Return the unique reference to an extended vector type of
4698/// the specified element type and size. VectorType must be a built-in type.
4700 unsigned NumElts) const {
4701 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4702 (vecType->isBitIntType() &&
4703 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4704 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4705
4706 // Check if we've already instantiated a vector of this type.
4707 llvm::FoldingSetNodeID ID;
4708 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4710 void *InsertPos = nullptr;
4711 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4712 return QualType(VTP, 0);
4713
4714 // If the element type isn't canonical, this won't be a canonical type either,
4715 // so fill in the canonical type field.
4716 QualType Canonical;
4717 if (!vecType.isCanonical()) {
4718 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4719
4720 // Get the new insert position for the node we care about.
4721 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4722 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4723 }
4724 auto *New = new (*this, alignof(ExtVectorType))
4725 ExtVectorType(vecType, NumElts, Canonical);
4726 VectorTypes.InsertNode(New, InsertPos);
4727 Types.push_back(New);
4728 return QualType(New, 0);
4729}
4730
4733 Expr *SizeExpr,
4734 SourceLocation AttrLoc) const {
4735 llvm::FoldingSetNodeID ID;
4737 SizeExpr);
4738
4739 void *InsertPos = nullptr;
4741 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4743 if (Canon) {
4744 // We already have a canonical version of this array type; use it as
4745 // the canonical type for a newly-built type.
4746 New = new (*this, alignof(DependentSizedExtVectorType))
4747 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4748 AttrLoc);
4749 } else {
4750 QualType CanonVecTy = getCanonicalType(vecType);
4751 if (CanonVecTy == vecType) {
4752 New = new (*this, alignof(DependentSizedExtVectorType))
4753 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4754
4755 DependentSizedExtVectorType *CanonCheck
4756 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4757 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4758 (void)CanonCheck;
4759 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4760 } else {
4761 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4762 SourceLocation());
4763 New = new (*this, alignof(DependentSizedExtVectorType))
4764 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4765 }
4766 }
4767
4768 Types.push_back(New);
4769 return QualType(New, 0);
4770}
4771
4773 unsigned NumColumns) const {
4774 llvm::FoldingSetNodeID ID;
4775 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4776 Type::ConstantMatrix);
4777
4778 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4779 "need a valid element type");
4780 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4781 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4782 "need valid matrix dimensions");
4783 void *InsertPos = nullptr;
4784 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4785 return QualType(MTP, 0);
4786
4787 QualType Canonical;
4788 if (!ElementTy.isCanonical()) {
4789 Canonical =
4790 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4791
4792 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4793 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4794 (void)NewIP;
4795 }
4796
4797 auto *New = new (*this, alignof(ConstantMatrixType))
4798 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4799 MatrixTypes.InsertNode(New, InsertPos);
4800 Types.push_back(New);
4801 return QualType(New, 0);
4802}
4803
4805 Expr *RowExpr,
4806 Expr *ColumnExpr,
4807 SourceLocation AttrLoc) const {
4808 QualType CanonElementTy = getCanonicalType(ElementTy);
4809 llvm::FoldingSetNodeID ID;
4810 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4811 ColumnExpr);
4812
4813 void *InsertPos = nullptr;
4815 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4816
4817 if (!Canon) {
4818 Canon = new (*this, alignof(DependentSizedMatrixType))
4819 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4820 ColumnExpr, AttrLoc);
4821#ifndef NDEBUG
4822 DependentSizedMatrixType *CanonCheck =
4823 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4824 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4825#endif
4826 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4827 Types.push_back(Canon);
4828 }
4829
4830 // Already have a canonical version of the matrix type
4831 //
4832 // If it exactly matches the requested type, use it directly.
4833 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4834 Canon->getRowExpr() == ColumnExpr)
4835 return QualType(Canon, 0);
4836
4837 // Use Canon as the canonical type for newly-built type.
4839 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4840 ColumnExpr, AttrLoc);
4841 Types.push_back(New);
4842 return QualType(New, 0);
4843}
4844
4846 Expr *AddrSpaceExpr,
4847 SourceLocation AttrLoc) const {
4848 assert(AddrSpaceExpr->isInstantiationDependent());
4849
4850 QualType canonPointeeType = getCanonicalType(PointeeType);
4851
4852 void *insertPos = nullptr;
4853 llvm::FoldingSetNodeID ID;
4854 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4855 AddrSpaceExpr);
4856
4857 DependentAddressSpaceType *canonTy =
4858 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4859
4860 if (!canonTy) {
4861 canonTy = new (*this, alignof(DependentAddressSpaceType))
4862 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4863 AttrLoc);
4864 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4865 Types.push_back(canonTy);
4866 }
4867
4868 if (canonPointeeType == PointeeType &&
4869 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4870 return QualType(canonTy, 0);
4871
4872 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4873 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4874 AddrSpaceExpr, AttrLoc);
4875 Types.push_back(sugaredType);
4876 return QualType(sugaredType, 0);
4877}
4878
4879/// Determine whether \p T is canonical as the result type of a function.
4881 return T.isCanonical() &&
4882 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4883 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4884}
4885
4886/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4887QualType
4889 const FunctionType::ExtInfo &Info) const {
4890 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4891 // functionality creates a function without a prototype regardless of
4892 // language mode (so it makes them even in C++). Once the rewriter has been
4893 // fixed, this assertion can be enabled again.
4894 //assert(!LangOpts.requiresStrictPrototypes() &&
4895 // "strict prototypes are disabled");
4896
4897 // Unique functions, to guarantee there is only one function of a particular
4898 // structure.
4899 llvm::FoldingSetNodeID ID;
4900 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4901
4902 void *InsertPos = nullptr;
4903 if (FunctionNoProtoType *FT =
4904 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4905 return QualType(FT, 0);
4906
4907 QualType Canonical;
4908 if (!isCanonicalResultType(ResultTy)) {
4909 Canonical =
4911
4912 // Get the new insert position for the node we care about.
4913 FunctionNoProtoType *NewIP =
4914 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4915 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4916 }
4917
4918 auto *New = new (*this, alignof(FunctionNoProtoType))
4919 FunctionNoProtoType(ResultTy, Canonical, Info);
4920 Types.push_back(New);
4921 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4922 return QualType(New, 0);
4923}
4924
4927 CanQualType CanResultType = getCanonicalType(ResultType);
4928
4929 // Canonical result types do not have ARC lifetime qualifiers.
4930 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4931 Qualifiers Qs = CanResultType.getQualifiers();
4932 Qs.removeObjCLifetime();
4934 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4935 }
4936
4937 return CanResultType;
4938}
4939
4941 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4942 if (ESI.Type == EST_None)
4943 return true;
4944 if (!NoexceptInType)
4945 return false;
4946
4947 // C++17 onwards: exception specification is part of the type, as a simple
4948 // boolean "can this function type throw".
4949 if (ESI.Type == EST_BasicNoexcept)
4950 return true;
4951
4952 // A noexcept(expr) specification is (possibly) canonical if expr is
4953 // value-dependent.
4954 if (ESI.Type == EST_DependentNoexcept)
4955 return true;
4956
4957 // A dynamic exception specification is canonical if it only contains pack
4958 // expansions (so we can't tell whether it's non-throwing) and all its
4959 // contained types are canonical.
4960 if (ESI.Type == EST_Dynamic) {
4961 bool AnyPackExpansions = false;
4962 for (QualType ET : ESI.Exceptions) {
4963 if (!ET.isCanonical())
4964 return false;
4965 if (ET->getAs<PackExpansionType>())
4966 AnyPackExpansions = true;
4967 }
4968 return AnyPackExpansions;
4969 }
4970
4971 return false;
4972}
4973
4974QualType ASTContext::getFunctionTypeInternal(
4975 QualType ResultTy, ArrayRef<QualType> ArgArray,
4976 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4977 size_t NumArgs = ArgArray.size();
4978
4979 // Unique functions, to guarantee there is only one function of a particular
4980 // structure.
4981 llvm::FoldingSetNodeID ID;
4982 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4983 *this, true);
4984
4985 QualType Canonical;
4986 bool Unique = false;
4987
4988 void *InsertPos = nullptr;
4989 if (FunctionProtoType *FPT =
4990 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4991 QualType Existing = QualType(FPT, 0);
4992
4993 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4994 // it so long as our exception specification doesn't contain a dependent
4995 // noexcept expression, or we're just looking for a canonical type.
4996 // Otherwise, we're going to need to create a type
4997 // sugar node to hold the concrete expression.
4998 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4999 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5000 return Existing;
5001
5002 // We need a new type sugar node for this one, to hold the new noexcept
5003 // expression. We do no canonicalization here, but that's OK since we don't
5004 // expect to see the same noexcept expression much more than once.
5005 Canonical = getCanonicalType(Existing);
5006 Unique = true;
5007 }
5008
5009 bool NoexceptInType = getLangOpts().CPlusPlus17;
5010 bool IsCanonicalExceptionSpec =
5012
5013 // Determine whether the type being created is already canonical or not.
5014 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5015 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5016 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5017 if (!ArgArray[i].isCanonicalAsParam())
5018 isCanonical = false;
5019
5020 if (OnlyWantCanonical)
5021 assert(isCanonical &&
5022 "given non-canonical parameters constructing canonical type");
5023
5024 // If this type isn't canonical, get the canonical version of it if we don't
5025 // already have it. The exception spec is only partially part of the
5026 // canonical type, and only in C++17 onwards.
5027 if (!isCanonical && Canonical.isNull()) {
5028 SmallVector<QualType, 16> CanonicalArgs;
5029 CanonicalArgs.reserve(NumArgs);
5030 for (unsigned i = 0; i != NumArgs; ++i)
5031 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5032
5033 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5034 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5035 CanonicalEPI.HasTrailingReturn = false;
5036
5037 if (IsCanonicalExceptionSpec) {
5038 // Exception spec is already OK.
5039 } else if (NoexceptInType) {
5040 switch (EPI.ExceptionSpec.Type) {
5042 // We don't know yet. It shouldn't matter what we pick here; no-one
5043 // should ever look at this.
5044 [[fallthrough]];
5045 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5046 CanonicalEPI.ExceptionSpec.Type = EST_None;
5047 break;
5048
5049 // A dynamic exception specification is almost always "not noexcept",
5050 // with the exception that a pack expansion might expand to no types.
5051 case EST_Dynamic: {
5052 bool AnyPacks = false;
5053 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5054 if (ET->getAs<PackExpansionType>())
5055 AnyPacks = true;
5056 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5057 }
5058 if (!AnyPacks)
5059 CanonicalEPI.ExceptionSpec.Type = EST_None;
5060 else {
5061 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5062 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5063 }
5064 break;
5065 }
5066
5067 case EST_DynamicNone:
5068 case EST_BasicNoexcept:
5069 case EST_NoexceptTrue:
5070 case EST_NoThrow:
5071 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5072 break;
5073
5075 llvm_unreachable("dependent noexcept is already canonical");
5076 }
5077 } else {
5078 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5079 }
5080
5081 // Adjust the canonical function result type.
5082 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5083 Canonical =
5084 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5085
5086 // Get the new insert position for the node we care about.
5087 FunctionProtoType *NewIP =
5088 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5089 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5090 }
5091
5092 // Compute the needed size to hold this FunctionProtoType and the
5093 // various trailing objects.
5094 auto ESH = FunctionProtoType::getExceptionSpecSize(
5095 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5096 size_t Size = FunctionProtoType::totalSizeToAlloc<
5097 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5098 FunctionType::FunctionTypeExtraAttributeInfo,
5099 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5100 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5101 FunctionEffect, EffectConditionExpr>(
5104 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5105 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5106 EPI.ExtParameterInfos ? NumArgs : 0,
5108 EPI.FunctionEffects.conditions().size());
5109
5110 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5111 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5112 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5113 Types.push_back(FTP);
5114 if (!Unique)
5115 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5116 if (!EPI.FunctionEffects.empty())
5117 AnyFunctionEffects = true;
5118 return QualType(FTP, 0);
5119}
5120
5121QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5122 llvm::FoldingSetNodeID ID;
5123 PipeType::Profile(ID, T, ReadOnly);
5124
5125 void *InsertPos = nullptr;
5126 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5127 return QualType(PT, 0);
5128
5129 // If the pipe element type isn't canonical, this won't be a canonical type
5130 // either, so fill in the canonical type field.
5131 QualType Canonical;
5132 if (!T.isCanonical()) {
5133 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5134
5135 // Get the new insert position for the node we care about.
5136 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5137 assert(!NewIP && "Shouldn't be in the map!");
5138 (void)NewIP;
5139 }
5140 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5141 Types.push_back(New);
5142 PipeTypes.InsertNode(New, InsertPos);
5143 return QualType(New, 0);
5144}
5145
5147 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5148 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5149 : Ty;
5150}
5151
5153 return getPipeType(T, true);
5154}
5155
5157 return getPipeType(T, false);
5158}
5159
5160QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5161 llvm::FoldingSetNodeID ID;
5162 BitIntType::Profile(ID, IsUnsigned, NumBits);
5163
5164 void *InsertPos = nullptr;
5165 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5166 return QualType(EIT, 0);
5167
5168 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5169 BitIntTypes.InsertNode(New, InsertPos);
5170 Types.push_back(New);
5171 return QualType(New, 0);
5172}
5173
5175 Expr *NumBitsExpr) const {
5176 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5177 llvm::FoldingSetNodeID ID;
5178 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5179
5180 void *InsertPos = nullptr;
5181 if (DependentBitIntType *Existing =
5182 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5183 return QualType(Existing, 0);
5184
5185 auto *New = new (*this, alignof(DependentBitIntType))
5186 DependentBitIntType(IsUnsigned, NumBitsExpr);
5187 DependentBitIntTypes.InsertNode(New, InsertPos);
5188
5189 Types.push_back(New);
5190 return QualType(New, 0);
5191}
5192
5195 using Kind = PredefinedSugarType::Kind;
5196
5197 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5198 Target != nullptr)
5199 return QualType(Target, 0);
5200
5201 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5202 switch (KDI) {
5203 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5204 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5205 // are part of the core language and are widely used. Using
5206 // PredefinedSugarType makes these types as named sugar types rather than
5207 // standard integer types, enabling better hints and diagnostics.
5208 case Kind::SizeT:
5209 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5210 case Kind::SignedSizeT:
5211 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5212 case Kind::PtrdiffT:
5213 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5214 }
5215 llvm_unreachable("unexpected kind");
5216 };
5217 auto *New = new (*this, alignof(PredefinedSugarType))
5218 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5219 getCanonicalType(*this, static_cast<Kind>(KD)));
5220 Types.push_back(New);
5221 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5222 return QualType(New, 0);
5223}
5224
5226 NestedNameSpecifier Qualifier,
5227 const TypeDecl *Decl) const {
5228 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5229 return getTagType(Keyword, Qualifier, Tag,
5230 /*OwnsTag=*/false);
5231 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5232 return getTypedefType(Keyword, Qualifier, Typedef);
5233 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5234 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5235
5237 assert(!Qualifier);
5238 return QualType(Decl->TypeForDecl, 0);
5239}
5240
5242 if (auto *Tag = dyn_cast<TagDecl>(TD))
5243 return getCanonicalTagType(Tag);
5244 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5245 return getCanonicalType(TN->getUnderlyingType());
5246 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5248 assert(TD->TypeForDecl);
5249 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5250}
5251
5253 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5254 return getCanonicalTagType(TD);
5255 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5256 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5258 /*Qualifier=*/std::nullopt, TD);
5259 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5260 return getCanonicalUnresolvedUsingType(Using);
5261
5262 assert(Decl->TypeForDecl);
5263 return QualType(Decl->TypeForDecl, 0);
5264}
5265
5266/// getTypedefType - Return the unique reference to the type for the
5267/// specified typedef name decl.
5270 NestedNameSpecifier Qualifier,
5271 const TypedefNameDecl *Decl, QualType UnderlyingType,
5272 std::optional<bool> TypeMatchesDeclOrNone) const {
5273 if (!TypeMatchesDeclOrNone) {
5274 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5275 assert(!DeclUnderlyingType.isNull());
5276 if (UnderlyingType.isNull())
5277 UnderlyingType = DeclUnderlyingType;
5278 else
5279 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5280 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5281 } else {
5282 // FIXME: This is a workaround for a serialization cycle: assume the decl
5283 // underlying type is not available; don't touch it.
5284 assert(!UnderlyingType.isNull());
5285 }
5286
5287 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5288 *TypeMatchesDeclOrNone) {
5289 if (Decl->TypeForDecl)
5290 return QualType(Decl->TypeForDecl, 0);
5291
5292 auto *NewType = new (*this, alignof(TypedefType))
5293 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5294 !*TypeMatchesDeclOrNone);
5295
5296 Types.push_back(NewType);
5297 Decl->TypeForDecl = NewType;
5298 return QualType(NewType, 0);
5299 }
5300
5301 llvm::FoldingSetNodeID ID;
5302 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5303 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5304
5305 void *InsertPos = nullptr;
5306 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5307 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5308 return QualType(Placeholder->getType(), 0);
5309
5310 void *Mem =
5311 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5313 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5314 alignof(TypedefType));
5315 auto *NewType =
5316 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5317 UnderlyingType, !*TypeMatchesDeclOrNone);
5318 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5320 TypedefTypes.InsertNode(Placeholder, InsertPos);
5321 Types.push_back(NewType);
5322 return QualType(NewType, 0);
5323}
5324
5326 NestedNameSpecifier Qualifier,
5327 const UsingShadowDecl *D,
5328 QualType UnderlyingType) const {
5329 // FIXME: This is expensive to compute every time!
5330 if (UnderlyingType.isNull()) {
5331 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5332 UnderlyingType =
5335 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5336 }
5337
5338 llvm::FoldingSetNodeID ID;
5339 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5340
5341 void *InsertPos = nullptr;
5342 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5343 return QualType(T, 0);
5344
5345 assert(!UnderlyingType.hasLocalQualifiers());
5346
5347 assert(
5349 UnderlyingType));
5350
5351 void *Mem =
5352 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5353 alignof(UsingType));
5354 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5355 Types.push_back(T);
5356 UsingTypes.InsertNode(T, InsertPos);
5357 return QualType(T, 0);
5358}
5359
5360TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5361 NestedNameSpecifier Qualifier,
5362 const TagDecl *TD, bool OwnsTag,
5363 bool IsInjected,
5364 const Type *CanonicalType,
5365 bool WithFoldingSetNode) const {
5366 auto [TC, Size] = [&] {
5367 switch (TD->getDeclKind()) {
5368 case Decl::Enum:
5369 static_assert(alignof(EnumType) == alignof(TagType));
5370 return std::make_tuple(Type::Enum, sizeof(EnumType));
5371 case Decl::ClassTemplatePartialSpecialization:
5372 case Decl::ClassTemplateSpecialization:
5373 case Decl::CXXRecord:
5374 static_assert(alignof(RecordType) == alignof(TagType));
5375 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5376 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5377 return std::make_tuple(Type::InjectedClassName,
5378 sizeof(InjectedClassNameType));
5379 [[fallthrough]];
5380 case Decl::Record:
5381 return std::make_tuple(Type::Record, sizeof(RecordType));
5382 default:
5383 llvm_unreachable("unexpected decl kind");
5384 }
5385 }();
5386
5387 if (Qualifier) {
5388 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5389 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5390 sizeof(NestedNameSpecifier);
5391 }
5392 void *Mem;
5393 if (WithFoldingSetNode) {
5394 // FIXME: It would be more profitable to tail allocate the folding set node
5395 // from the type, instead of the other way around, due to the greater
5396 // alignment requirements of the type. But this makes it harder to deal with
5397 // the different type node sizes. This would require either uniquing from
5398 // different folding sets, or having the folding setaccept a
5399 // contextual parameter which is not fixed at construction.
5400 Mem = Allocate(
5401 sizeof(TagTypeFoldingSetPlaceholder) +
5402 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5403 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5404 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5405 Mem = T->getTagType();
5406 } else {
5407 Mem = Allocate(Size, alignof(TagType));
5408 }
5409
5410 auto *T = [&, TC = TC]() -> TagType * {
5411 switch (TC) {
5412 case Type::Enum: {
5413 assert(isa<EnumDecl>(TD));
5414 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5415 IsInjected, CanonicalType);
5416 assert(reinterpret_cast<void *>(T) ==
5417 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5418 "TagType must be the first base of EnumType");
5419 return T;
5420 }
5421 case Type::Record: {
5422 assert(isa<RecordDecl>(TD));
5423 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5424 IsInjected, CanonicalType);
5425 assert(reinterpret_cast<void *>(T) ==
5426 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5427 "TagType must be the first base of RecordType");
5428 return T;
5429 }
5430 case Type::InjectedClassName: {
5431 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
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 InjectedClassNameType");
5436 return T;
5437 }
5438 default:
5439 llvm_unreachable("unexpected type class");
5440 }
5441 }();
5442 assert(T->getKeyword() == Keyword);
5443 assert(T->getQualifier() == Qualifier);
5444 assert(T->getDecl() == TD);
5445 assert(T->isInjected() == IsInjected);
5446 assert(T->isTagOwned() == OwnsTag);
5447 assert((T->isCanonicalUnqualified()
5448 ? QualType()
5449 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5450 Types.push_back(T);
5451 return T;
5452}
5453
5454static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5455 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5456 RD && RD->isInjectedClassName())
5457 return cast<TagDecl>(RD->getDeclContext());
5458 return TD;
5459}
5460
5463 if (TD->TypeForDecl)
5464 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5465
5466 const Type *CanonicalType = getTagTypeInternal(
5468 /*Qualifier=*/std::nullopt, TD,
5469 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5470 /*WithFoldingSetNode=*/false);
5471 TD->TypeForDecl = CanonicalType;
5472 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5473}
5474
5476 NestedNameSpecifier Qualifier,
5477 const TagDecl *TD, bool OwnsTag) const {
5478
5479 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5480 bool IsInjected = TD != NonInjectedTD;
5481
5482 ElaboratedTypeKeyword PreferredKeyword =
5485 NonInjectedTD->getTagKind());
5486
5487 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5488 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5489 return QualType(T, 0);
5490
5491 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5492 const Type *T =
5493 getTagTypeInternal(Keyword,
5494 /*Qualifier=*/std::nullopt, NonInjectedTD,
5495 /*OwnsTag=*/false, IsInjected, CanonicalType,
5496 /*WithFoldingSetNode=*/false);
5497 TD->TypeForDecl = T;
5498 return QualType(T, 0);
5499 }
5500
5501 llvm::FoldingSetNodeID ID;
5502 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5503 OwnsTag, IsInjected);
5504
5505 void *InsertPos = nullptr;
5506 if (TagTypeFoldingSetPlaceholder *T =
5507 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5508 return QualType(T->getTagType(), 0);
5509
5510 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5511 TagType *T =
5512 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5513 CanonicalType, /*WithFoldingSetNode=*/true);
5514 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5515 return QualType(T, 0);
5516}
5517
5518bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5519 unsigned NumPositiveBits,
5520 QualType &BestType,
5521 QualType &BestPromotionType) {
5522 unsigned IntWidth = Target->getIntWidth();
5523 unsigned CharWidth = Target->getCharWidth();
5524 unsigned ShortWidth = Target->getShortWidth();
5525 bool EnumTooLarge = false;
5526 unsigned BestWidth;
5527 if (NumNegativeBits) {
5528 // If there is a negative value, figure out the smallest integer type (of
5529 // int/long/longlong) that fits.
5530 // If it's packed, check also if it fits a char or a short.
5531 if (IsPacked && NumNegativeBits <= CharWidth &&
5532 NumPositiveBits < CharWidth) {
5533 BestType = SignedCharTy;
5534 BestWidth = CharWidth;
5535 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5536 NumPositiveBits < ShortWidth) {
5537 BestType = ShortTy;
5538 BestWidth = ShortWidth;
5539 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5540 BestType = IntTy;
5541 BestWidth = IntWidth;
5542 } else {
5543 BestWidth = Target->getLongWidth();
5544
5545 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5546 BestType = LongTy;
5547 } else {
5548 BestWidth = Target->getLongLongWidth();
5549
5550 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5551 EnumTooLarge = true;
5552 BestType = LongLongTy;
5553 }
5554 }
5555 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5556 } else {
5557 // If there is no negative value, figure out the smallest type that fits
5558 // all of the enumerator values.
5559 // If it's packed, check also if it fits a char or a short.
5560 if (IsPacked && NumPositiveBits <= CharWidth) {
5561 BestType = UnsignedCharTy;
5562 BestPromotionType = IntTy;
5563 BestWidth = CharWidth;
5564 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5565 BestType = UnsignedShortTy;
5566 BestPromotionType = IntTy;
5567 BestWidth = ShortWidth;
5568 } else if (NumPositiveBits <= IntWidth) {
5569 BestType = UnsignedIntTy;
5570 BestWidth = IntWidth;
5571 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5573 : IntTy;
5574 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5575 BestType = UnsignedLongTy;
5576 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5578 : LongTy;
5579 } else {
5580 BestWidth = Target->getLongLongWidth();
5581 if (NumPositiveBits > BestWidth) {
5582 // This can happen with bit-precise integer types, but those are not
5583 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5584 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5585 // a 128-bit integer, we should consider doing the same.
5586 EnumTooLarge = true;
5587 }
5588 BestType = UnsignedLongLongTy;
5589 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5591 : LongLongTy;
5592 }
5593 }
5594 return EnumTooLarge;
5595}
5596
5598 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5599 "Integral type required!");
5600 unsigned BitWidth = getIntWidth(T);
5601
5602 if (Value.isUnsigned() || Value.isNonNegative()) {
5603 if (T->isSignedIntegerOrEnumerationType())
5604 --BitWidth;
5605 return Value.getActiveBits() <= BitWidth;
5606 }
5607 return Value.getSignificantBits() <= BitWidth;
5608}
5609
5610UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5612 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5613 const Type *CanonicalType) const {
5614 void *Mem = Allocate(
5615 UnresolvedUsingType::totalSizeToAlloc<
5617 !!InsertPos, !!Qualifier),
5618 alignof(UnresolvedUsingType));
5619 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5620 if (InsertPos) {
5621 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5623 TypedefTypes.InsertNode(Placeholder, InsertPos);
5624 }
5625 Types.push_back(T);
5626 return T;
5627}
5628
5630 const UnresolvedUsingTypenameDecl *D) const {
5631 D = D->getCanonicalDecl();
5632 if (D->TypeForDecl)
5633 return D->TypeForDecl->getCanonicalTypeUnqualified();
5634
5635 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5637 /*Qualifier=*/std::nullopt, D,
5638 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5639 D->TypeForDecl = CanonicalType;
5640 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5641}
5642
5645 NestedNameSpecifier Qualifier,
5646 const UnresolvedUsingTypenameDecl *D) const {
5647 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5648 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5649 return QualType(T, 0);
5650
5651 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5652 const Type *T =
5653 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5654 /*Qualifier=*/std::nullopt, D,
5655 /*InsertPos=*/nullptr, CanonicalType);
5656 D->TypeForDecl = T;
5657 return QualType(T, 0);
5658 }
5659
5660 llvm::FoldingSetNodeID ID;
5661 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5662
5663 void *InsertPos = nullptr;
5665 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5666 return QualType(Placeholder->getType(), 0);
5667 assert(InsertPos);
5668
5669 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5670 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5671 InsertPos, CanonicalType);
5672 return QualType(T, 0);
5673}
5674
5676 QualType modifiedType,
5677 QualType equivalentType,
5678 const Attr *attr) const {
5679 llvm::FoldingSetNodeID id;
5680 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5681
5682 void *insertPos = nullptr;
5683 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5684 if (type) return QualType(type, 0);
5685
5686 assert(!attr || attr->getKind() == attrKind);
5687
5688 QualType canon = getCanonicalType(equivalentType);
5689 type = new (*this, alignof(AttributedType))
5690 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5691
5692 Types.push_back(type);
5693 AttributedTypes.InsertNode(type, insertPos);
5694
5695 return QualType(type, 0);
5696}
5697
5699 QualType equivalentType) const {
5700 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5701}
5702
5704 QualType modifiedType,
5705 QualType equivalentType) {
5706 switch (nullability) {
5708 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5709
5711 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5712
5714 return getAttributedType(attr::TypeNullableResult, modifiedType,
5715 equivalentType);
5716
5718 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5719 equivalentType);
5720 }
5721
5722 llvm_unreachable("Unknown nullability kind");
5723}
5724
5725QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5726 QualType Wrapped) const {
5727 llvm::FoldingSetNodeID ID;
5728 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5729
5730 void *InsertPos = nullptr;
5731 BTFTagAttributedType *Ty =
5732 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5733 if (Ty)
5734 return QualType(Ty, 0);
5735
5736 QualType Canon = getCanonicalType(Wrapped);
5737 Ty = new (*this, alignof(BTFTagAttributedType))
5738 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5739
5740 Types.push_back(Ty);
5741 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5742
5743 return QualType(Ty, 0);
5744}
5745
5747 QualType Underlying) const {
5748 const IdentifierInfo *II = Attr->getBehaviorKind();
5749 StringRef IdentName = II->getName();
5750 OverflowBehaviorType::OverflowBehaviorKind Kind;
5751 if (IdentName == "wrap") {
5752 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5753 } else if (IdentName == "trap") {
5754 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5755 } else {
5756 return Underlying;
5757 }
5758
5759 return getOverflowBehaviorType(Kind, Underlying);
5760}
5761
5763 OverflowBehaviorType::OverflowBehaviorKind Kind,
5764 QualType Underlying) const {
5765 assert(!Underlying->isOverflowBehaviorType() &&
5766 "Cannot have underlying types that are themselves OBTs");
5767 llvm::FoldingSetNodeID ID;
5768 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5769 void *InsertPos = nullptr;
5770
5771 if (OverflowBehaviorType *OBT =
5772 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5773 return QualType(OBT, 0);
5774 }
5775
5776 QualType Canonical;
5777 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5778 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5779 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5780 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5781 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5782 "Shouldn't be in the map");
5783 }
5784
5785 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5786 OverflowBehaviorType(Canonical, Underlying, Kind);
5787
5788 Types.push_back(Ty);
5789 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5790 return QualType(Ty, 0);
5791}
5792
5794 QualType Wrapped, QualType Contained,
5795 const HLSLAttributedResourceType::Attributes &Attrs) {
5796
5797 llvm::FoldingSetNodeID ID;
5798 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5799
5800 void *InsertPos = nullptr;
5801 HLSLAttributedResourceType *Ty =
5802 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5803 if (Ty)
5804 return QualType(Ty, 0);
5805
5806 Ty = new (*this, alignof(HLSLAttributedResourceType))
5807 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5808
5809 Types.push_back(Ty);
5810 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5811
5812 return QualType(Ty, 0);
5813}
5814
5815QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5816 uint32_t Alignment,
5817 ArrayRef<SpirvOperand> Operands) {
5818 llvm::FoldingSetNodeID ID;
5819 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5820
5821 void *InsertPos = nullptr;
5822 HLSLInlineSpirvType *Ty =
5823 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5824 if (Ty)
5825 return QualType(Ty, 0);
5826
5827 void *Mem = Allocate(
5828 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5829 alignof(HLSLInlineSpirvType));
5830
5831 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5832
5833 Types.push_back(Ty);
5834 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5835
5836 return QualType(Ty, 0);
5837}
5838
5839/// Retrieve a substitution-result type.
5841 Decl *AssociatedDecl,
5842 unsigned Index,
5843 UnsignedOrNone PackIndex,
5844 bool Final) const {
5845 llvm::FoldingSetNodeID ID;
5846 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5847 PackIndex, Final);
5848 void *InsertPos = nullptr;
5849 SubstTemplateTypeParmType *SubstParm =
5850 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5851
5852 if (!SubstParm) {
5853 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5854 !Replacement.isCanonical()),
5855 alignof(SubstTemplateTypeParmType));
5856 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5857 Index, PackIndex, Final);
5858 Types.push_back(SubstParm);
5859 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5860 }
5861
5862 return QualType(SubstParm, 0);
5863}
5864
5867 unsigned Index, bool Final,
5868 const TemplateArgument &ArgPack) {
5869#ifndef NDEBUG
5870 for (const auto &P : ArgPack.pack_elements())
5871 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5872#endif
5873
5874 llvm::FoldingSetNodeID ID;
5875 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5876 ArgPack);
5877 void *InsertPos = nullptr;
5878 if (SubstTemplateTypeParmPackType *SubstParm =
5879 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5880 return QualType(SubstParm, 0);
5881
5882 QualType Canon;
5883 {
5884 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5885 if (!AssociatedDecl->isCanonicalDecl() ||
5886 !CanonArgPack.structurallyEquals(ArgPack)) {
5888 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5889 [[maybe_unused]] const auto *Nothing =
5890 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5891 assert(!Nothing);
5892 }
5893 }
5894
5895 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5896 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5897 ArgPack);
5898 Types.push_back(SubstParm);
5899 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5900 return QualType(SubstParm, 0);
5901}
5902
5905 assert(llvm::all_of(ArgPack.pack_elements(),
5906 [](const auto &P) {
5907 return P.getKind() == TemplateArgument::Type;
5908 }) &&
5909 "Pack contains a non-type");
5910
5911 llvm::FoldingSetNodeID ID;
5912 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5913
5914 void *InsertPos = nullptr;
5915 if (auto *T =
5916 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5917 return QualType(T, 0);
5918
5919 QualType Canon;
5920 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5921 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5922 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5923 // Refresh InsertPos, in case the recursive call above caused rehashing,
5924 // which would invalidate the bucket pointer.
5925 [[maybe_unused]] const auto *Nothing =
5926 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5927 assert(!Nothing);
5928 }
5929
5930 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5931 SubstBuiltinTemplatePackType(Canon, ArgPack);
5932 Types.push_back(PackType);
5933 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5934 return QualType(PackType, 0);
5935}
5936
5937/// Retrieve the template type parameter type for a template
5938/// parameter or parameter pack with the given depth, index, and (optionally)
5939/// name.
5940QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5941 bool ParameterPack,
5942 TemplateTypeParmDecl *TTPDecl) const {
5943 llvm::FoldingSetNodeID ID;
5944 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5945 void *InsertPos = nullptr;
5946 TemplateTypeParmType *TypeParm
5947 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5948
5949 if (TypeParm)
5950 return QualType(TypeParm, 0);
5951
5952 if (TTPDecl) {
5953 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5954 TypeParm = new (*this, alignof(TemplateTypeParmType))
5955 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5956
5957 TemplateTypeParmType *TypeCheck
5958 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5959 assert(!TypeCheck && "Template type parameter canonical type broken");
5960 (void)TypeCheck;
5961 } else
5962 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5963 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5964
5965 Types.push_back(TypeParm);
5966 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5967
5968 return QualType(TypeParm, 0);
5969}
5970
5973 switch (Keyword) {
5974 // These are just themselves.
5980 return Keyword;
5981
5982 // These are equivalent.
5985
5986 // These are functionally equivalent, so relying on their equivalence is
5987 // IFNDR. By making them equivalent, we disallow overloading, which at least
5988 // can produce a diagnostic.
5991 }
5992 llvm_unreachable("unexpected keyword kind");
5993}
5994
5996 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5997 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5998 TemplateName Name, SourceLocation NameLoc,
5999 const TemplateArgumentListInfo &SpecifiedArgs,
6000 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6002 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6003
6006 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6007 SpecifiedArgs);
6008 return TSI;
6009}
6010
6013 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6014 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6015 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6016 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6017 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6018 SpecifiedArgVec.push_back(Arg.getArgument());
6019
6020 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6021 CanonicalArgs, Underlying);
6022}
6023
6024[[maybe_unused]] static bool
6026 for (const TemplateArgument &Arg : Args)
6027 if (Arg.isPackExpansion())
6028 return true;
6029 return false;
6030}
6031
6034 ArrayRef<TemplateArgument> Args) const {
6035 assert(Template ==
6036 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6038 Template.getAsDependentTemplateName()));
6039#ifndef NDEBUG
6040 for (const auto &Arg : Args)
6041 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6042#endif
6043
6044 llvm::FoldingSetNodeID ID;
6045 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6046 *this);
6047 void *InsertPos = nullptr;
6048 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6049 return QualType(T, 0);
6050
6051 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6052 sizeof(TemplateArgument) * Args.size(),
6053 alignof(TemplateSpecializationType));
6054 auto *Spec =
6055 new (Mem) TemplateSpecializationType(Keyword, Template,
6056 /*IsAlias=*/false, Args, QualType());
6057 assert(Spec->isDependentType() &&
6058 "canonical template specialization must be dependent");
6059 Types.push_back(Spec);
6060 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6061 return QualType(Spec, 0);
6062}
6063
6066 ArrayRef<TemplateArgument> SpecifiedArgs,
6067 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6068 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6069 bool IsTypeAlias = TD && TD->isTypeAlias();
6070 if (Underlying.isNull()) {
6071 TemplateName CanonTemplate =
6072 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6073 ElaboratedTypeKeyword CanonKeyword =
6074 CanonTemplate.getAsDependentTemplateName()
6077 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6079 if (CanonicalArgs.empty()) {
6080 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6081 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6082 CanonicalArgs = CanonArgsVec;
6083 } else {
6084 NonCanonical |= !llvm::equal(
6085 SpecifiedArgs, CanonicalArgs,
6086 [](const TemplateArgument &A, const TemplateArgument &B) {
6087 return A.structurallyEquals(B);
6088 });
6089 }
6090
6091 // We can get here with an alias template when the specialization
6092 // contains a pack expansion that does not match up with a parameter
6093 // pack, or a builtin template which cannot be resolved due to dependency.
6094 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6095 hasAnyPackExpansions(CanonicalArgs)) &&
6096 "Caller must compute aliased type");
6097 IsTypeAlias = false;
6098
6100 CanonKeyword, CanonTemplate, CanonicalArgs);
6101 if (!NonCanonical)
6102 return Underlying;
6103 }
6104 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6105 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6106 (IsTypeAlias ? sizeof(QualType) : 0),
6107 alignof(TemplateSpecializationType));
6108 auto *Spec = new (Mem) TemplateSpecializationType(
6109 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6110 Types.push_back(Spec);
6111 return QualType(Spec, 0);
6112}
6113
6116 llvm::FoldingSetNodeID ID;
6117 ParenType::Profile(ID, InnerType);
6118
6119 void *InsertPos = nullptr;
6120 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6121 if (T)
6122 return QualType(T, 0);
6123
6124 QualType Canon = InnerType;
6125 if (!Canon.isCanonical()) {
6126 Canon = getCanonicalType(InnerType);
6127 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6128 assert(!CheckT && "Paren canonical type broken");
6129 (void)CheckT;
6130 }
6131
6132 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6133 Types.push_back(T);
6134 ParenTypes.InsertNode(T, InsertPos);
6135 return QualType(T, 0);
6136}
6137
6140 const IdentifierInfo *MacroII) const {
6141 QualType Canon = UnderlyingTy;
6142 if (!Canon.isCanonical())
6143 Canon = getCanonicalType(UnderlyingTy);
6144
6145 auto *newType = new (*this, alignof(MacroQualifiedType))
6146 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6147 Types.push_back(newType);
6148 return QualType(newType, 0);
6149}
6150
6153 const IdentifierInfo *Name) const {
6154 llvm::FoldingSetNodeID ID;
6155 DependentNameType::Profile(ID, Keyword, NNS, Name);
6156
6157 void *InsertPos = nullptr;
6158 if (DependentNameType *T =
6159 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6160 return QualType(T, 0);
6161
6162 ElaboratedTypeKeyword CanonKeyword =
6164 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6165
6166 QualType Canon;
6167 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6168 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6169 [[maybe_unused]] DependentNameType *T =
6170 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6171 assert(!T && "broken canonicalization");
6172 assert(Canon.isCanonical());
6173 }
6174
6175 DependentNameType *T = new (*this, alignof(DependentNameType))
6176 DependentNameType(Keyword, NNS, Name, Canon);
6177 Types.push_back(T);
6178 DependentNameTypes.InsertNode(T, InsertPos);
6179 return QualType(T, 0);
6180}
6181
6183 TemplateArgument Arg;
6184 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6186 if (TTP->isParameterPack())
6187 ArgType = getPackExpansionType(ArgType, std::nullopt);
6188
6190 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6191 QualType T =
6192 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6193 // For class NTTPs, ensure we include the 'const' so the type matches that
6194 // of a real template argument.
6195 // FIXME: It would be more faithful to model this as something like an
6196 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6198 if (T->isRecordType()) {
6199 // C++ [temp.param]p8: An id-expression naming a non-type
6200 // template-parameter of class type T denotes a static storage duration
6201 // object of type const T.
6202 T.addConst();
6203 VK = VK_LValue;
6204 } else {
6205 VK = Expr::getValueKindForType(NTTP->getType());
6206 }
6207 Expr *E = new (*this)
6208 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6209 T, VK, NTTP->getLocation());
6210
6211 if (NTTP->isParameterPack())
6212 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6213 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6214 } else {
6215 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6217 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6218 TemplateName(TTP));
6219 if (TTP->isParameterPack())
6220 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6221 else
6222 Arg = TemplateArgument(Name);
6223 }
6224
6225 if (Param->isTemplateParameterPack())
6226 Arg =
6227 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6228
6229 return Arg;
6230}
6231
6233 UnsignedOrNone NumExpansions,
6234 bool ExpectPackInType) const {
6235 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6236 "Pack expansions must expand one or more parameter packs");
6237
6238 llvm::FoldingSetNodeID ID;
6239 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6240
6241 void *InsertPos = nullptr;
6242 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6243 if (T)
6244 return QualType(T, 0);
6245
6246 QualType Canon;
6247 if (!Pattern.isCanonical()) {
6248 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6249 /*ExpectPackInType=*/false);
6250
6251 // Find the insert position again, in case we inserted an element into
6252 // PackExpansionTypes and invalidated our insert position.
6253 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6254 }
6255
6256 T = new (*this, alignof(PackExpansionType))
6257 PackExpansionType(Pattern, Canon, NumExpansions);
6258 Types.push_back(T);
6259 PackExpansionTypes.InsertNode(T, InsertPos);
6260 return QualType(T, 0);
6261}
6262
6263/// CmpProtocolNames - Comparison predicate for sorting protocols
6264/// alphabetically.
6265static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6266 ObjCProtocolDecl *const *RHS) {
6267 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6268}
6269
6271 if (Protocols.empty()) return true;
6272
6273 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6274 return false;
6275
6276 for (unsigned i = 1; i != Protocols.size(); ++i)
6277 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6278 Protocols[i]->getCanonicalDecl() != Protocols[i])
6279 return false;
6280 return true;
6281}
6282
6283static void
6285 // Sort protocols, keyed by name.
6286 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6287
6288 // Canonicalize.
6289 for (ObjCProtocolDecl *&P : Protocols)
6290 P = P->getCanonicalDecl();
6291
6292 // Remove duplicates.
6293 auto ProtocolsEnd = llvm::unique(Protocols);
6294 Protocols.erase(ProtocolsEnd, Protocols.end());
6295}
6296
6298 ObjCProtocolDecl * const *Protocols,
6299 unsigned NumProtocols) const {
6300 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6301 /*isKindOf=*/false);
6302}
6303
6305 QualType baseType,
6306 ArrayRef<QualType> typeArgs,
6308 bool isKindOf) const {
6309 // If the base type is an interface and there aren't any protocols or
6310 // type arguments to add, then the interface type will do just fine.
6311 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6312 isa<ObjCInterfaceType>(baseType))
6313 return baseType;
6314
6315 // Look in the folding set for an existing type.
6316 llvm::FoldingSetNodeID ID;
6317 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6318 void *InsertPos = nullptr;
6319 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6320 return QualType(QT, 0);
6321
6322 // Determine the type arguments to be used for canonicalization,
6323 // which may be explicitly specified here or written on the base
6324 // type.
6325 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6326 if (effectiveTypeArgs.empty()) {
6327 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6328 effectiveTypeArgs = baseObject->getTypeArgs();
6329 }
6330
6331 // Build the canonical type, which has the canonical base type and a
6332 // sorted-and-uniqued list of protocols and the type arguments
6333 // canonicalized.
6334 QualType canonical;
6335 bool typeArgsAreCanonical = llvm::all_of(
6336 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6337 bool protocolsSorted = areSortedAndUniqued(protocols);
6338 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6339 // Determine the canonical type arguments.
6340 ArrayRef<QualType> canonTypeArgs;
6341 SmallVector<QualType, 4> canonTypeArgsVec;
6342 if (!typeArgsAreCanonical) {
6343 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6344 for (auto typeArg : effectiveTypeArgs)
6345 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6346 canonTypeArgs = canonTypeArgsVec;
6347 } else {
6348 canonTypeArgs = effectiveTypeArgs;
6349 }
6350
6351 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6352 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6353 if (!protocolsSorted) {
6354 canonProtocolsVec.append(protocols.begin(), protocols.end());
6355 SortAndUniqueProtocols(canonProtocolsVec);
6356 canonProtocols = canonProtocolsVec;
6357 } else {
6358 canonProtocols = protocols;
6359 }
6360
6361 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6362 canonProtocols, isKindOf);
6363
6364 // Regenerate InsertPos.
6365 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6366 }
6367
6368 unsigned size = sizeof(ObjCObjectTypeImpl);
6369 size += typeArgs.size() * sizeof(QualType);
6370 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6371 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6372 auto *T =
6373 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6374 isKindOf);
6375
6376 Types.push_back(T);
6377 ObjCObjectTypes.InsertNode(T, InsertPos);
6378 return QualType(T, 0);
6379}
6380
6381/// Apply Objective-C protocol qualifiers to the given type.
6382/// If this is for the canonical type of a type parameter, we can apply
6383/// protocol qualifiers on the ObjCObjectPointerType.
6386 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6387 bool allowOnPointerType) const {
6388 hasError = false;
6389
6390 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6391 return getObjCTypeParamType(objT->getDecl(), protocols);
6392 }
6393
6394 // Apply protocol qualifiers to ObjCObjectPointerType.
6395 if (allowOnPointerType) {
6396 if (const auto *objPtr =
6397 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6398 const ObjCObjectType *objT = objPtr->getObjectType();
6399 // Merge protocol lists and construct ObjCObjectType.
6401 protocolsVec.append(objT->qual_begin(),
6402 objT->qual_end());
6403 protocolsVec.append(protocols.begin(), protocols.end());
6404 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6406 objT->getBaseType(),
6407 objT->getTypeArgsAsWritten(),
6408 protocols,
6409 objT->isKindOfTypeAsWritten());
6411 }
6412 }
6413
6414 // Apply protocol qualifiers to ObjCObjectType.
6415 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6416 // FIXME: Check for protocols to which the class type is already
6417 // known to conform.
6418
6419 return getObjCObjectType(objT->getBaseType(),
6420 objT->getTypeArgsAsWritten(),
6421 protocols,
6422 objT->isKindOfTypeAsWritten());
6423 }
6424
6425 // If the canonical type is ObjCObjectType, ...
6426 if (type->isObjCObjectType()) {
6427 // Silently overwrite any existing protocol qualifiers.
6428 // TODO: determine whether that's the right thing to do.
6429
6430 // FIXME: Check for protocols to which the class type is already
6431 // known to conform.
6432 return getObjCObjectType(type, {}, protocols, false);
6433 }
6434
6435 // id<protocol-list>
6436 if (type->isObjCIdType()) {
6437 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6438 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6439 objPtr->isKindOfType());
6441 }
6442
6443 // Class<protocol-list>
6444 if (type->isObjCClassType()) {
6445 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6446 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6447 objPtr->isKindOfType());
6449 }
6450
6451 hasError = true;
6452 return type;
6453}
6454
6457 ArrayRef<ObjCProtocolDecl *> protocols) const {
6458 // Look in the folding set for an existing type.
6459 llvm::FoldingSetNodeID ID;
6460 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6461 void *InsertPos = nullptr;
6462 if (ObjCTypeParamType *TypeParam =
6463 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6464 return QualType(TypeParam, 0);
6465
6466 // We canonicalize to the underlying type.
6467 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6468 if (!protocols.empty()) {
6469 // Apply the protocol qualifers.
6470 bool hasError;
6472 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6473 assert(!hasError && "Error when apply protocol qualifier to bound type");
6474 }
6475
6476 unsigned size = sizeof(ObjCTypeParamType);
6477 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6478 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6479 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6480
6481 Types.push_back(newType);
6482 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6483 return QualType(newType, 0);
6484}
6485
6487 ObjCTypeParamDecl *New) const {
6488 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6489 // Update TypeForDecl after updating TypeSourceInfo.
6490 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6492 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6493 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6494 New->TypeForDecl = UpdatedTy.getTypePtr();
6495}
6496
6497/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6498/// protocol list adopt all protocols in QT's qualified-id protocol
6499/// list.
6501 ObjCInterfaceDecl *IC) {
6502 if (!QT->isObjCQualifiedIdType())
6503 return false;
6504
6505 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6506 // If both the right and left sides have qualifiers.
6507 for (auto *Proto : OPT->quals()) {
6508 if (!IC->ClassImplementsProtocol(Proto, false))
6509 return false;
6510 }
6511 return true;
6512 }
6513 return false;
6514}
6515
6516/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6517/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6518/// of protocols.
6520 ObjCInterfaceDecl *IDecl) {
6521 if (!QT->isObjCQualifiedIdType())
6522 return false;
6523 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6524 if (!OPT)
6525 return false;
6526 if (!IDecl->hasDefinition())
6527 return false;
6529 CollectInheritedProtocols(IDecl, InheritedProtocols);
6530 if (InheritedProtocols.empty())
6531 return false;
6532 // Check that if every protocol in list of id<plist> conforms to a protocol
6533 // of IDecl's, then bridge casting is ok.
6534 bool Conforms = false;
6535 for (auto *Proto : OPT->quals()) {
6536 Conforms = false;
6537 for (auto *PI : InheritedProtocols) {
6538 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6539 Conforms = true;
6540 break;
6541 }
6542 }
6543 if (!Conforms)
6544 break;
6545 }
6546 if (Conforms)
6547 return true;
6548
6549 for (auto *PI : InheritedProtocols) {
6550 // If both the right and left sides have qualifiers.
6551 bool Adopts = false;
6552 for (auto *Proto : OPT->quals()) {
6553 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6554 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6555 break;
6556 }
6557 if (!Adopts)
6558 return false;
6559 }
6560 return true;
6561}
6562
6563/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6564/// the given object type.
6566 llvm::FoldingSetNodeID ID;
6567 ObjCObjectPointerType::Profile(ID, ObjectT);
6568
6569 void *InsertPos = nullptr;
6570 if (ObjCObjectPointerType *QT =
6571 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6572 return QualType(QT, 0);
6573
6574 // Find the canonical object type.
6575 QualType Canonical;
6576 if (!ObjectT.isCanonical()) {
6577 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6578
6579 // Regenerate InsertPos.
6580 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6581 }
6582
6583 // No match.
6584 void *Mem =
6586 auto *QType =
6587 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6588
6589 Types.push_back(QType);
6590 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6591 return QualType(QType, 0);
6592}
6593
6594/// getObjCInterfaceType - Return the unique reference to the type for the
6595/// specified ObjC interface decl. The list of protocols is optional.
6597 ObjCInterfaceDecl *PrevDecl) const {
6598 if (Decl->TypeForDecl)
6599 return QualType(Decl->TypeForDecl, 0);
6600
6601 if (PrevDecl) {
6602 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6603 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6604 return QualType(PrevDecl->TypeForDecl, 0);
6605 }
6606
6607 // Prefer the definition, if there is one.
6608 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6609 Decl = Def;
6610
6611 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6612 auto *T = new (Mem) ObjCInterfaceType(Decl);
6613 Decl->TypeForDecl = T;
6614 Types.push_back(T);
6615 return QualType(T, 0);
6616}
6617
6618/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6619/// TypeOfExprType AST's (since expression's are never shared). For example,
6620/// multiple declarations that refer to "typeof(x)" all contain different
6621/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6622/// on canonical type's (which are always unique).
6624 TypeOfExprType *toe;
6625 if (tofExpr->isTypeDependent()) {
6626 llvm::FoldingSetNodeID ID;
6627 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6628 Kind == TypeOfKind::Unqualified);
6629
6630 void *InsertPos = nullptr;
6632 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6633 if (Canon) {
6634 // We already have a "canonical" version of an identical, dependent
6635 // typeof(expr) type. Use that as our canonical type.
6636 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6637 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6638 } else {
6639 // Build a new, canonical typeof(expr) type.
6640 Canon = new (*this, alignof(DependentTypeOfExprType))
6641 DependentTypeOfExprType(*this, tofExpr, Kind);
6642 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6643 toe = Canon;
6644 }
6645 } else {
6646 QualType Canonical = getCanonicalType(tofExpr->getType());
6647 toe = new (*this, alignof(TypeOfExprType))
6648 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6649 }
6650 Types.push_back(toe);
6651 return QualType(toe, 0);
6652}
6653
6654/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6655/// TypeOfType nodes. The only motivation to unique these nodes would be
6656/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6657/// an issue. This doesn't affect the type checker, since it operates
6658/// on canonical types (which are always unique).
6660 QualType Canonical = getCanonicalType(tofType);
6661 auto *tot = new (*this, alignof(TypeOfType))
6662 TypeOfType(*this, tofType, Canonical, Kind);
6663 Types.push_back(tot);
6664 return QualType(tot, 0);
6665}
6666
6667/// getReferenceQualifiedType - Given an expr, will return the type for
6668/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6669/// and class member access into account.
6671 // C++11 [dcl.type.simple]p4:
6672 // [...]
6673 QualType T = E->getType();
6674 switch (E->getValueKind()) {
6675 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6676 // type of e;
6677 case VK_XValue:
6678 return getRValueReferenceType(T);
6679 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6680 // type of e;
6681 case VK_LValue:
6682 return getLValueReferenceType(T);
6683 // - otherwise, decltype(e) is the type of e.
6684 case VK_PRValue:
6685 return T;
6686 }
6687 llvm_unreachable("Unknown value kind");
6688}
6689
6690/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6691/// nodes. This would never be helpful, since each such type has its own
6692/// expression, and would not give a significant memory saving, since there
6693/// is an Expr tree under each such type.
6695 // C++11 [temp.type]p2:
6696 // If an expression e involves a template parameter, decltype(e) denotes a
6697 // unique dependent type. Two such decltype-specifiers refer to the same
6698 // type only if their expressions are equivalent (14.5.6.1).
6699 QualType CanonType;
6700 if (!E->isInstantiationDependent()) {
6701 CanonType = getCanonicalType(UnderlyingType);
6702 } else if (!UnderlyingType.isNull()) {
6703 CanonType = getDecltypeType(E, QualType());
6704 } else {
6705 llvm::FoldingSetNodeID ID;
6706 DependentDecltypeType::Profile(ID, *this, E);
6707
6708 void *InsertPos = nullptr;
6709 if (DependentDecltypeType *Canon =
6710 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6711 return QualType(Canon, 0);
6712
6713 // Build a new, canonical decltype(expr) type.
6714 auto *DT =
6715 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6716 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6717 Types.push_back(DT);
6718 return QualType(DT, 0);
6719 }
6720 auto *DT = new (*this, alignof(DecltypeType))
6721 DecltypeType(E, UnderlyingType, CanonType);
6722 Types.push_back(DT);
6723 return QualType(DT, 0);
6724}
6725
6727 bool FullySubstituted,
6728 ArrayRef<QualType> Expansions,
6729 UnsignedOrNone Index) const {
6730 QualType Canonical;
6731 if (FullySubstituted && Index) {
6732 Canonical = getCanonicalType(Expansions[*Index]);
6733 } else {
6734 llvm::FoldingSetNodeID ID;
6735 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6736 FullySubstituted, Expansions);
6737 void *InsertPos = nullptr;
6738 PackIndexingType *Canon =
6739 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6740 if (!Canon) {
6741 void *Mem = Allocate(
6742 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6744 Canon =
6745 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6746 IndexExpr, FullySubstituted, Expansions);
6747 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6748 }
6749 Canonical = QualType(Canon, 0);
6750 }
6751
6752 void *Mem =
6753 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6755 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6756 FullySubstituted, Expansions);
6757 Types.push_back(T);
6758 return QualType(T, 0);
6759}
6760
6761/// getUnaryTransformationType - We don't unique these, since the memory
6762/// savings are minimal and these are rare.
6765 UnaryTransformType::UTTKind Kind) const {
6766
6767 llvm::FoldingSetNodeID ID;
6768 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6769
6770 void *InsertPos = nullptr;
6771 if (UnaryTransformType *UT =
6772 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6773 return QualType(UT, 0);
6774
6775 QualType CanonType;
6776 if (!BaseType->isDependentType()) {
6777 CanonType = UnderlyingType.getCanonicalType();
6778 } else {
6779 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6780 UnderlyingType = QualType();
6781 if (QualType CanonBase = BaseType.getCanonicalType();
6782 BaseType != CanonBase) {
6783 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6784 assert(CanonType.isCanonical());
6785
6786 // Find the insertion position again.
6787 [[maybe_unused]] UnaryTransformType *UT =
6788 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6789 assert(!UT && "broken canonicalization");
6790 }
6791 }
6792
6793 auto *UT = new (*this, alignof(UnaryTransformType))
6794 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6795 UnaryTransformTypes.InsertNode(UT, InsertPos);
6796 Types.push_back(UT);
6797 return QualType(UT, 0);
6798}
6799
6800/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6801/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6802/// canonical deduced-but-dependent 'auto' type.
6806 TemplateDecl *TypeConstraintConcept,
6807 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6809 !TypeConstraintConcept) {
6810 assert(DeducedAsType.isNull() && "");
6811 assert(TypeConstraintArgs.empty() && "");
6812 return getAutoDeductType();
6813 }
6814
6815 // Look in the folding set for an existing type.
6816 llvm::FoldingSetNodeID ID;
6817 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6818 TypeConstraintConcept, TypeConstraintArgs);
6819 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6820 return QualType(AT_iter->getSecond(), 0);
6821
6822 if (DK == DeducedKind::Deduced) {
6823 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6824 } else {
6825 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6826 if (TypeConstraintConcept) {
6827 bool AnyNonCanonArgs = false;
6828 auto *CanonicalConcept =
6829 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6830 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6831 *this, TypeConstraintArgs, AnyNonCanonArgs);
6832 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6833 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6834 CanonicalConceptArgs);
6835 }
6836 }
6837
6838 void *Mem = Allocate(sizeof(AutoType) +
6839 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6840 alignof(AutoType));
6841 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6842 TypeConstraintConcept, TypeConstraintArgs);
6843#ifndef NDEBUG
6844 llvm::FoldingSetNodeID InsertedID;
6845 AT->Profile(InsertedID, *this);
6846 assert(InsertedID == ID && "ID does not match");
6847#endif
6848 Types.push_back(AT);
6849 AutoTypes.try_emplace(ID, AT);
6850 return QualType(AT, 0);
6851}
6852
6855
6856 // Remove a type-constraint from a top-level auto or decltype(auto).
6857 if (auto *AT = CanonT->getAs<AutoType>()) {
6858 if (!AT->isConstrained())
6859 return T;
6860 return getQualifiedType(
6861 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6862 T.getQualifiers());
6863 }
6864
6865 // FIXME: We only support constrained auto at the top level in the type of a
6866 // non-type template parameter at the moment. Once we lift that restriction,
6867 // we'll need to recursively build types containing auto here.
6868 assert(!CanonT->getContainedAutoType() ||
6869 !CanonT->getContainedAutoType()->isConstrained());
6870 return T;
6871}
6872
6873/// Return the uniqued reference to the deduced template specialization type
6874/// which has been deduced to the given type, or to the canonical undeduced
6875/// such type, or the canonical deduced-but-dependent such type.
6878 TemplateName Template) const {
6879 // DeducedAsPack only ever occurs for lambda init-capture pack, which always
6880 // use AutoType.
6881 assert(DK != DeducedKind::DeducedAsPack &&
6882 "unexpected DeducedAsPack for DeducedTemplateSpecializationType");
6883
6884 // Look in the folding set for an existing type.
6885 void *InsertPos = nullptr;
6886 llvm::FoldingSetNodeID ID;
6887 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6888 Template);
6889 if (DeducedTemplateSpecializationType *DTST =
6890 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6891 return QualType(DTST, 0);
6892
6893 if (DK == DeducedKind::Deduced) {
6894 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6895 } else {
6896 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6897 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6898 // FIXME: Can this be formed from a DependentTemplateName, such that the
6899 // keyword should be part of the canonical type?
6901 Template != CanonTemplateName) {
6903 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6904 // Find the insertion position again.
6905 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6906 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
6907 assert(!DTST && "broken canonicalization");
6908 }
6909 }
6910
6911 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6912 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6913
6914#ifndef NDEBUG
6915 llvm::FoldingSetNodeID TempID;
6916 DTST->Profile(TempID);
6917 assert(ID == TempID && "ID does not match");
6918#endif
6919 Types.push_back(DTST);
6920 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6921 return QualType(DTST, 0);
6922}
6923
6924/// getAtomicType - Return the uniqued reference to the atomic type for
6925/// the given value type.
6927 // Unique pointers, to guarantee there is only one pointer of a particular
6928 // structure.
6929 llvm::FoldingSetNodeID ID;
6930 AtomicType::Profile(ID, T);
6931
6932 void *InsertPos = nullptr;
6933 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6934 return QualType(AT, 0);
6935
6936 // If the atomic value type isn't canonical, this won't be a canonical type
6937 // either, so fill in the canonical type field.
6938 QualType Canonical;
6939 if (!T.isCanonical()) {
6940 Canonical = getAtomicType(getCanonicalType(T));
6941
6942 // Get the new insert position for the node we care about.
6943 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6944 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6945 }
6946 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6947 Types.push_back(New);
6948 AtomicTypes.InsertNode(New, InsertPos);
6949 return QualType(New, 0);
6950}
6951
6952/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6954 if (AutoDeductTy.isNull())
6955 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6956 AutoType(DeducedKind::Undeduced, QualType(),
6958 /*TypeConstraintConcept=*/nullptr,
6959 /*TypeConstraintArgs=*/{}),
6960 0);
6961 return AutoDeductTy;
6962}
6963
6964/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6966 if (AutoRRefDeductTy.isNull())
6968 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6969 return AutoRRefDeductTy;
6970}
6971
6972/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6973/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6974/// needs to agree with the definition in <stddef.h>.
6978
6980 return getFromTargetType(Target->getSizeType());
6981}
6982
6983/// Return the unique signed counterpart of the integer type
6984/// corresponding to size_t.
6988
6989/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6990/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6994
6995/// Return the unique unsigned counterpart of "ptrdiff_t"
6996/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6997/// in the definition of %tu format specifier.
6999 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7000}
7001
7002/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7004 return getFromTargetType(Target->getIntMaxType());
7005}
7006
7007/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7009 return getFromTargetType(Target->getUIntMaxType());
7010}
7011
7012/// getSignedWCharType - Return the type of "signed wchar_t".
7013/// Used when in C++, as a GCC extension.
7015 // FIXME: derive from "Target" ?
7016 return WCharTy;
7017}
7018
7019/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7020/// Used when in C++, as a GCC extension.
7022 // FIXME: derive from "Target" ?
7023 return UnsignedIntTy;
7024}
7025
7027 return getFromTargetType(Target->getIntPtrType());
7028}
7029
7033
7034/// Return the unique type for "pid_t" defined in
7035/// <sys/types.h>. We need this to compute the correct type for vfork().
7037 return getFromTargetType(Target->getProcessIDType());
7038}
7039
7040//===----------------------------------------------------------------------===//
7041// Type Operators
7042//===----------------------------------------------------------------------===//
7043
7045 // Push qualifiers into arrays, and then discard any remaining
7046 // qualifiers.
7047 T = getCanonicalType(T);
7049 const Type *Ty = T.getTypePtr();
7053 } else if (isa<ArrayType>(Ty)) {
7055 } else if (isa<FunctionType>(Ty)) {
7056 Result = getPointerType(QualType(Ty, 0));
7057 } else {
7058 Result = QualType(Ty, 0);
7059 }
7060
7062}
7063
7065 Qualifiers &quals) const {
7066 SplitQualType splitType = type.getSplitUnqualifiedType();
7067
7068 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7069 // the unqualified desugared type and then drops it on the floor.
7070 // We then have to strip that sugar back off with
7071 // getUnqualifiedDesugaredType(), which is silly.
7072 const auto *AT =
7073 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7074
7075 // If we don't have an array, just use the results in splitType.
7076 if (!AT) {
7077 quals = splitType.Quals;
7078 return QualType(splitType.Ty, 0);
7079 }
7080
7081 // Otherwise, recurse on the array's element type.
7082 QualType elementType = AT->getElementType();
7083 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7084
7085 // If that didn't change the element type, AT has no qualifiers, so we
7086 // can just use the results in splitType.
7087 if (elementType == unqualElementType) {
7088 assert(quals.empty()); // from the recursive call
7089 quals = splitType.Quals;
7090 return QualType(splitType.Ty, 0);
7091 }
7092
7093 // Otherwise, add in the qualifiers from the outermost type, then
7094 // build the type back up.
7095 quals.addConsistentQualifiers(splitType.Quals);
7096
7097 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7098 return getConstantArrayType(unqualElementType, CAT->getSize(),
7099 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7100 }
7101
7102 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7103 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7104 }
7105
7106 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7107 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7108 VAT->getSizeModifier(),
7109 VAT->getIndexTypeCVRQualifiers());
7110 }
7111
7112 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7113 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7114 DSAT->getSizeModifier(), 0);
7115}
7116
7117/// Attempt to unwrap two types that may both be array types with the same bound
7118/// (or both be array types of unknown bound) for the purpose of comparing the
7119/// cv-decomposition of two types per C++ [conv.qual].
7120///
7121/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7122/// C++20 [conv.qual], if permitted by the current language mode.
7124 bool AllowPiMismatch) const {
7125 while (true) {
7126 auto *AT1 = getAsArrayType(T1);
7127 if (!AT1)
7128 return;
7129
7130 auto *AT2 = getAsArrayType(T2);
7131 if (!AT2)
7132 return;
7133
7134 // If we don't have two array types with the same constant bound nor two
7135 // incomplete array types, we've unwrapped everything we can.
7136 // C++20 also permits one type to be a constant array type and the other
7137 // to be an incomplete array type.
7138 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7139 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7140 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7141 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7142 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7144 return;
7145 } else if (isa<IncompleteArrayType>(AT1)) {
7146 if (!(isa<IncompleteArrayType>(AT2) ||
7147 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7149 return;
7150 } else {
7151 return;
7152 }
7153
7154 T1 = AT1->getElementType();
7155 T2 = AT2->getElementType();
7156 }
7157}
7158
7159/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7160///
7161/// If T1 and T2 are both pointer types of the same kind, or both array types
7162/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7163/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7164///
7165/// This function will typically be called in a loop that successively
7166/// "unwraps" pointer and pointer-to-member types to compare them at each
7167/// level.
7168///
7169/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7170/// C++20 [conv.qual], if permitted by the current language mode.
7171///
7172/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7173/// pair of types that can't be unwrapped further.
7175 bool AllowPiMismatch) const {
7176 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7177
7178 const auto *T1PtrType = T1->getAs<PointerType>();
7179 const auto *T2PtrType = T2->getAs<PointerType>();
7180 if (T1PtrType && T2PtrType) {
7181 T1 = T1PtrType->getPointeeType();
7182 T2 = T2PtrType->getPointeeType();
7183 return true;
7184 }
7185
7186 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7187 *T2MPType = T2->getAs<MemberPointerType>();
7188 T1MPType && T2MPType) {
7189 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7190 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7191 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7192 return false;
7193 if (T1MPType->getQualifier().getCanonical() !=
7194 T2MPType->getQualifier().getCanonical())
7195 return false;
7196 T1 = T1MPType->getPointeeType();
7197 T2 = T2MPType->getPointeeType();
7198 return true;
7199 }
7200
7201 if (getLangOpts().ObjC) {
7202 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7203 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7204 if (T1OPType && T2OPType) {
7205 T1 = T1OPType->getPointeeType();
7206 T2 = T2OPType->getPointeeType();
7207 return true;
7208 }
7209 }
7210
7211 // FIXME: Block pointers, too?
7212
7213 return false;
7214}
7215
7217 while (true) {
7218 Qualifiers Quals;
7219 T1 = getUnqualifiedArrayType(T1, Quals);
7220 T2 = getUnqualifiedArrayType(T2, Quals);
7221 if (hasSameType(T1, T2))
7222 return true;
7223 if (!UnwrapSimilarTypes(T1, T2))
7224 return false;
7225 }
7226}
7227
7229 while (true) {
7230 Qualifiers Quals1, Quals2;
7231 T1 = getUnqualifiedArrayType(T1, Quals1);
7232 T2 = getUnqualifiedArrayType(T2, Quals2);
7233
7234 Quals1.removeCVRQualifiers();
7235 Quals2.removeCVRQualifiers();
7236 if (Quals1 != Quals2)
7237 return false;
7238
7239 if (hasSameType(T1, T2))
7240 return true;
7241
7242 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7243 return false;
7244 }
7245}
7246
7249 SourceLocation NameLoc) const {
7250 switch (Name.getKind()) {
7253 // DNInfo work in progress: CHECKME: what about DNLoc?
7255 NameLoc);
7256
7259 // DNInfo work in progress: CHECKME: what about DNLoc?
7260 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7261 }
7262
7265 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7266 }
7267
7271 DeclarationName DName;
7272 if (const IdentifierInfo *II = TN.getIdentifier()) {
7273 DName = DeclarationNames.getIdentifier(II);
7274 return DeclarationNameInfo(DName, NameLoc);
7275 } else {
7276 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7277 // DNInfo work in progress: FIXME: source locations?
7278 DeclarationNameLoc DNLoc =
7280 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7281 }
7282 }
7283
7287 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7288 NameLoc);
7289 }
7290
7295 NameLoc);
7296 }
7299 NameLoc);
7302 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7303 }
7304 }
7305
7306 llvm_unreachable("bad template name kind!");
7307}
7308
7309const TemplateArgument *
7311 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7312 if (!TP->hasDefaultArgument())
7313 return nullptr;
7314 return &TP->getDefaultArgument().getArgument();
7315 };
7316 switch (P->getKind()) {
7317 case NamedDecl::TemplateTypeParm:
7318 return handleParam(cast<TemplateTypeParmDecl>(P));
7319 case NamedDecl::NonTypeTemplateParm:
7320 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7321 case NamedDecl::TemplateTemplateParm:
7322 return handleParam(cast<TemplateTemplateParmDecl>(P));
7323 default:
7324 llvm_unreachable("Unexpected template parameter kind");
7325 }
7326}
7327
7329 bool IgnoreDeduced) const {
7330 while (std::optional<TemplateName> UnderlyingOrNone =
7331 Name.desugar(IgnoreDeduced))
7332 Name = *UnderlyingOrNone;
7333
7334 switch (Name.getKind()) {
7337 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7339
7340 // The canonical template name is the canonical template declaration.
7341 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7342 }
7343
7345 // An assumed template is just a name, so it is already canonical.
7346 return Name;
7347
7349 llvm_unreachable("cannot canonicalize overloaded template");
7350
7353 assert(DTN && "Non-dependent template names must refer to template decls.");
7354 NestedNameSpecifier Qualifier = DTN->getQualifier();
7355 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7356 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7357 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7358 /*HasTemplateKeyword=*/true});
7359 return Name;
7360 }
7361
7365 TemplateArgument canonArgPack =
7368 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7369 subst->getIndex(), subst->getFinal());
7370 }
7372 assert(IgnoreDeduced == false);
7374 DefaultArguments DefArgs = DTS->getDefaultArguments();
7375 TemplateName Underlying = DTS->getUnderlying();
7376
7377 TemplateName CanonUnderlying =
7378 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7379 bool NonCanonical = CanonUnderlying != Underlying;
7380 auto CanonArgs =
7381 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7382
7383 ArrayRef<NamedDecl *> Params =
7384 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7385 assert(CanonArgs.size() <= Params.size());
7386 // A deduced template name which deduces the same default arguments already
7387 // declared in the underlying template is the same template as the
7388 // underlying template. We need need to note any arguments which differ from
7389 // the corresponding declaration. If any argument differs, we must build a
7390 // deduced template name.
7391 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7393 if (!A)
7394 break;
7395 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7396 TemplateArgument &CanonDefArg = CanonArgs[I];
7397 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7398 continue;
7399 // Keep popping from the back any deault arguments which are the same.
7400 if (I == int(CanonArgs.size() - 1))
7401 CanonArgs.pop_back();
7402 NonCanonical = true;
7403 }
7404 return NonCanonical ? getDeducedTemplateName(
7405 CanonUnderlying,
7406 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7407 : Name;
7408 }
7412 llvm_unreachable("always sugar node");
7413 }
7414
7415 llvm_unreachable("bad template name!");
7416}
7417
7419 const TemplateName &Y,
7420 bool IgnoreDeduced) const {
7421 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7422 getCanonicalTemplateName(Y, IgnoreDeduced);
7423}
7424
7426 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7427 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7428 return false;
7430 return false;
7431 return true;
7432}
7433
7434bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7435 if (!XCE != !YCE)
7436 return false;
7437
7438 if (!XCE)
7439 return true;
7440
7441 llvm::FoldingSetNodeID XCEID, YCEID;
7442 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7443 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7444 return XCEID == YCEID;
7445}
7446
7448 const TypeConstraint *YTC) const {
7449 if (!XTC != !YTC)
7450 return false;
7451
7452 if (!XTC)
7453 return true;
7454
7455 auto *NCX = XTC->getNamedConcept();
7456 auto *NCY = YTC->getNamedConcept();
7457 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7458 return false;
7461 return false;
7463 if (XTC->getConceptReference()
7465 ->NumTemplateArgs !=
7467 return false;
7468
7469 // Compare slowly by profiling.
7470 //
7471 // We couldn't compare the profiling result for the template
7472 // args here. Consider the following example in different modules:
7473 //
7474 // template <__integer_like _Tp, C<_Tp> Sentinel>
7475 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7476 // return __t;
7477 // }
7478 //
7479 // When we compare the profiling result for `C<_Tp>` in different
7480 // modules, it will compare the type of `_Tp` in different modules.
7481 // However, the type of `_Tp` in different modules refer to different
7482 // types here naturally. So we couldn't compare the profiling result
7483 // for the template args directly.
7486}
7487
7489 const NamedDecl *Y) const {
7490 if (X->getKind() != Y->getKind())
7491 return false;
7492
7493 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7494 auto *TY = cast<TemplateTypeParmDecl>(Y);
7495 if (TX->isParameterPack() != TY->isParameterPack())
7496 return false;
7497 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7498 return false;
7499 return isSameTypeConstraint(TX->getTypeConstraint(),
7500 TY->getTypeConstraint());
7501 }
7502
7503 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7504 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7505 return TX->isParameterPack() == TY->isParameterPack() &&
7506 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7507 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7508 TY->getPlaceholderTypeConstraint());
7509 }
7510
7512 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7513 return TX->isParameterPack() == TY->isParameterPack() &&
7514 isSameTemplateParameterList(TX->getTemplateParameters(),
7515 TY->getTemplateParameters());
7516}
7517
7519 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7520 if (X->size() != Y->size())
7521 return false;
7522
7523 for (unsigned I = 0, N = X->size(); I != N; ++I)
7524 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7525 return false;
7526
7527 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7528}
7529
7531 const NamedDecl *Y) const {
7532 // If the type parameter isn't the same already, we don't need to check the
7533 // default argument further.
7534 if (!isSameTemplateParameter(X, Y))
7535 return false;
7536
7537 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7538 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7539 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7540 return false;
7541
7542 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7543 TTPY->getDefaultArgument().getArgument().getAsType());
7544 }
7545
7546 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7547 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7548 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7549 return false;
7550
7551 Expr *DefaultArgumentX =
7552 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7553 Expr *DefaultArgumentY =
7554 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7555 llvm::FoldingSetNodeID XID, YID;
7556 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7557 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7558 return XID == YID;
7559 }
7560
7561 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7562 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7563
7564 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7565 return false;
7566
7567 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7568 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7569 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7570}
7571
7573 const NestedNameSpecifier Y) {
7574 if (X == Y)
7575 return true;
7576 if (!X || !Y)
7577 return false;
7578
7579 auto Kind = X.getKind();
7580 if (Kind != Y.getKind())
7581 return false;
7582
7583 // FIXME: For namespaces and types, we're permitted to check that the entity
7584 // is named via the same tokens. We should probably do so.
7585 switch (Kind) {
7587 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7588 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7589 if (!declaresSameEntity(NamespaceX->getNamespace(),
7590 NamespaceY->getNamespace()))
7591 return false;
7592 return isSameQualifier(PrefixX, PrefixY);
7593 }
7595 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7596 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7597 return false;
7598 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7599 }
7603 return true;
7604 }
7605 llvm_unreachable("unhandled qualifier kind");
7606}
7607
7608static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7609 if (!A->getASTContext().getLangOpts().CUDA)
7610 return true; // Target attributes are overloadable in CUDA compilation only.
7611 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7612 return false;
7613 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7614 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7615 return true; // unattributed and __host__ functions are the same.
7616}
7617
7618/// Determine whether the attributes we can overload on are identical for A and
7619/// B. Will ignore any overloadable attrs represented in the type of A and B.
7621 const FunctionDecl *B) {
7622 // Note that pass_object_size attributes are represented in the function's
7623 // ExtParameterInfo, so we don't need to check them here.
7624
7625 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7626 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7627 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7628
7629 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7630 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7631 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7632
7633 // Return false if the number of enable_if attributes is different.
7634 if (!Cand1A || !Cand2A)
7635 return false;
7636
7637 Cand1ID.clear();
7638 Cand2ID.clear();
7639
7640 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7641 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7642
7643 // Return false if any of the enable_if expressions of A and B are
7644 // different.
7645 if (Cand1ID != Cand2ID)
7646 return false;
7647 }
7648 return hasSameCudaAttrs(A, B);
7649}
7650
7651bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7652 // Caution: this function is called by the AST reader during deserialization,
7653 // so it cannot rely on AST invariants being met. Non-trivial accessors
7654 // should be avoided, along with any traversal of redeclaration chains.
7655
7656 if (X == Y)
7657 return true;
7658
7659 if (X->getDeclName() != Y->getDeclName())
7660 return false;
7661
7662 // Must be in the same context.
7663 //
7664 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7665 // could be two different declarations of the same function. (We will fix the
7666 // semantic DC to refer to the primary definition after merging.)
7667 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7669 return false;
7670
7671 // If either X or Y are local to the owning module, they are only possible to
7672 // be the same entity if they are in the same module.
7673 if (X->isModuleLocal() || Y->isModuleLocal())
7674 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7675 return false;
7676
7677 // Two typedefs refer to the same entity if they have the same underlying
7678 // type.
7679 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7680 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7681 return hasSameType(TypedefX->getUnderlyingType(),
7682 TypedefY->getUnderlyingType());
7683
7684 // Must have the same kind.
7685 if (X->getKind() != Y->getKind())
7686 return false;
7687
7688 // Objective-C classes and protocols with the same name always match.
7690 return true;
7691
7693 // No need to handle these here: we merge them when adding them to the
7694 // template.
7695 return false;
7696 }
7697
7698 // Compatible tags match.
7699 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7700 const auto *TagY = cast<TagDecl>(Y);
7701 return (TagX->getTagKind() == TagY->getTagKind()) ||
7702 ((TagX->getTagKind() == TagTypeKind::Struct ||
7703 TagX->getTagKind() == TagTypeKind::Class ||
7704 TagX->getTagKind() == TagTypeKind::Interface) &&
7705 (TagY->getTagKind() == TagTypeKind::Struct ||
7706 TagY->getTagKind() == TagTypeKind::Class ||
7707 TagY->getTagKind() == TagTypeKind::Interface));
7708 }
7709
7710 // Functions with the same type and linkage match.
7711 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7712 // functions, etc.
7713 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7714 const auto *FuncY = cast<FunctionDecl>(Y);
7715 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7716 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7717 if (CtorX->getInheritedConstructor() &&
7718 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7719 CtorY->getInheritedConstructor().getConstructor()))
7720 return false;
7721 }
7722
7723 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7724 return false;
7725
7726 // Multiversioned functions with different feature strings are represented
7727 // as separate declarations.
7728 if (FuncX->isMultiVersion()) {
7729 const auto *TAX = FuncX->getAttr<TargetAttr>();
7730 const auto *TAY = FuncY->getAttr<TargetAttr>();
7731 assert(TAX && TAY && "Multiversion Function without target attribute");
7732
7733 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7734 return false;
7735 }
7736
7737 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7738 // not the same entity if they are constrained.
7739 if ((FuncX->isMemberLikeConstrainedFriend() ||
7740 FuncY->isMemberLikeConstrainedFriend()) &&
7741 !FuncX->getLexicalDeclContext()->Equals(
7742 FuncY->getLexicalDeclContext())) {
7743 return false;
7744 }
7745
7746 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7747 FuncY->getTrailingRequiresClause()))
7748 return false;
7749
7750 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7751 // Map to the first declaration that we've already merged into this one.
7752 // The TSI of redeclarations might not match (due to calling conventions
7753 // being inherited onto the type but not the TSI), but the TSI type of
7754 // the first declaration of the function should match across modules.
7755 FD = FD->getCanonicalDecl();
7756 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7757 : FD->getType();
7758 };
7759 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7760 if (!hasSameType(XT, YT)) {
7761 // We can get functions with different types on the redecl chain in C++17
7762 // if they have differing exception specifications and at least one of
7763 // the excpetion specs is unresolved.
7764 auto *XFPT = XT->getAs<FunctionProtoType>();
7765 auto *YFPT = YT->getAs<FunctionProtoType>();
7766 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7767 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7770 return true;
7771 return false;
7772 }
7773
7774 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7775 hasSameOverloadableAttrs(FuncX, FuncY);
7776 }
7777
7778 // Variables with the same type and linkage match.
7779 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7780 const auto *VarY = cast<VarDecl>(Y);
7781 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7782 // During deserialization, we might compare variables before we load
7783 // their types. Assume the types will end up being the same.
7784 if (VarX->getType().isNull() || VarY->getType().isNull())
7785 return true;
7786
7787 if (hasSameType(VarX->getType(), VarY->getType()))
7788 return true;
7789
7790 // We can get decls with different types on the redecl chain. Eg.
7791 // template <typename T> struct S { static T Var[]; }; // #1
7792 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7793 // Only? happens when completing an incomplete array type. In this case
7794 // when comparing #1 and #2 we should go through their element type.
7795 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7796 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7797 if (!VarXTy || !VarYTy)
7798 return false;
7799 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7800 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7801 }
7802 return false;
7803 }
7804
7805 // Namespaces with the same name and inlinedness match.
7806 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7807 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7808 return NamespaceX->isInline() == NamespaceY->isInline();
7809 }
7810
7811 // Identical template names and kinds match if their template parameter lists
7812 // and patterns match.
7813 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7814 const auto *TemplateY = cast<TemplateDecl>(Y);
7815
7816 // ConceptDecl wouldn't be the same if their constraint expression differs.
7817 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7818 const auto *ConceptY = cast<ConceptDecl>(Y);
7819 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7820 ConceptY->getConstraintExpr()))
7821 return false;
7822 }
7823
7824 return isSameEntity(TemplateX->getTemplatedDecl(),
7825 TemplateY->getTemplatedDecl()) &&
7826 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7827 TemplateY->getTemplateParameters());
7828 }
7829
7830 // Fields with the same name and the same type match.
7831 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7832 const auto *FDY = cast<FieldDecl>(Y);
7833 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7834 return hasSameType(FDX->getType(), FDY->getType());
7835 }
7836
7837 // Indirect fields with the same target field match.
7838 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7839 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7840 return IFDX->getAnonField()->getCanonicalDecl() ==
7841 IFDY->getAnonField()->getCanonicalDecl();
7842 }
7843
7844 // Enumerators with the same name match.
7846 // FIXME: Also check the value is odr-equivalent.
7847 return true;
7848
7849 // Using shadow declarations with the same target match.
7850 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7851 const auto *USY = cast<UsingShadowDecl>(Y);
7852 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7853 }
7854
7855 // Using declarations with the same qualifier match. (We already know that
7856 // the name matches.)
7857 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7858 const auto *UY = cast<UsingDecl>(Y);
7859 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7860 UX->hasTypename() == UY->hasTypename() &&
7861 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7862 }
7863 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7864 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7865 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7866 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7867 }
7868 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7869 return isSameQualifier(
7870 UX->getQualifier(),
7871 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7872 }
7873
7874 // Using-pack declarations are only created by instantiation, and match if
7875 // they're instantiated from matching UnresolvedUsing...Decls.
7876 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7877 return declaresSameEntity(
7878 UX->getInstantiatedFromUsingDecl(),
7879 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7880 }
7881
7882 // Namespace alias definitions with the same target match.
7883 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7884 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7885 return NAX->getNamespace()->Equals(NAY->getNamespace());
7886 }
7887
7888 return false;
7889}
7890
7893 switch (Arg.getKind()) {
7895 return Arg;
7896
7898 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7899 Arg.getIsDefaulted());
7900
7902 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7904 Arg.getIsDefaulted());
7905 }
7906
7909 /*isNullPtr*/ true, Arg.getIsDefaulted());
7910
7913 Arg.getIsDefaulted());
7914
7916 return TemplateArgument(
7919
7922
7924 return TemplateArgument(*this,
7927
7930 /*isNullPtr*/ false, Arg.getIsDefaulted());
7931
7933 bool AnyNonCanonArgs = false;
7934 auto CanonArgs = ::getCanonicalTemplateArguments(
7935 *this, Arg.pack_elements(), AnyNonCanonArgs);
7936 if (!AnyNonCanonArgs)
7937 return Arg;
7939 const_cast<ASTContext &>(*this), CanonArgs);
7940 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7941 return NewArg;
7942 }
7943 }
7944
7945 // Silence GCC warning
7946 llvm_unreachable("Unhandled template argument kind");
7947}
7948
7950 const TemplateArgument &Arg2) const {
7951 if (Arg1.getKind() != Arg2.getKind())
7952 return false;
7953
7954 switch (Arg1.getKind()) {
7956 llvm_unreachable("Comparing NULL template argument");
7957
7959 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7960
7962 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7964
7966 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7967
7972
7974 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7975 Arg2.getAsIntegral());
7976
7978 return Arg1.structurallyEquals(Arg2);
7979
7981 llvm::FoldingSetNodeID ID1, ID2;
7982 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7983 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7984 return ID1 == ID2;
7985 }
7986
7988 return llvm::equal(
7989 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7990 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7991 return isSameTemplateArgument(Arg1, Arg2);
7992 });
7993 }
7994
7995 llvm_unreachable("Unhandled template argument kind");
7996}
7997
7999 // Handle the non-qualified case efficiently.
8000 if (!T.hasLocalQualifiers()) {
8001 // Handle the common positive case fast.
8002 if (const auto *AT = dyn_cast<ArrayType>(T))
8003 return AT;
8004 }
8005
8006 // Handle the common negative case fast.
8007 if (!isa<ArrayType>(T.getCanonicalType()))
8008 return nullptr;
8009
8010 // Apply any qualifiers from the array type to the element type. This
8011 // implements C99 6.7.3p8: "If the specification of an array type includes
8012 // any type qualifiers, the element type is so qualified, not the array type."
8013
8014 // If we get here, we either have type qualifiers on the type, or we have
8015 // sugar such as a typedef in the way. If we have type qualifiers on the type
8016 // we must propagate them down into the element type.
8017
8018 SplitQualType split = T.getSplitDesugaredType();
8019 Qualifiers qs = split.Quals;
8020
8021 // If we have a simple case, just return now.
8022 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8023 if (!ATy || qs.empty())
8024 return ATy;
8025
8026 // Otherwise, we have an array and we have qualifiers on it. Push the
8027 // qualifiers into the array element type and return a new array type.
8028 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8029
8030 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8031 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8032 CAT->getSizeExpr(),
8033 CAT->getSizeModifier(),
8034 CAT->getIndexTypeCVRQualifiers()));
8035 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8037 IAT->getSizeModifier(),
8038 IAT->getIndexTypeCVRQualifiers()));
8039
8040 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8042 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8043 DSAT->getIndexTypeCVRQualifiers()));
8044
8045 const auto *VAT = cast<VariableArrayType>(ATy);
8046 return cast<ArrayType>(
8047 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8048 VAT->getIndexTypeCVRQualifiers()));
8049}
8050
8052 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8053 return getLValueReferenceType(T);
8054 if (getLangOpts().HLSL && T->isConstantArrayType())
8055 return getArrayParameterType(T);
8056 if (T->isArrayType() || T->isFunctionType())
8057 return getDecayedType(T);
8058 return T;
8059}
8060
8064 return T.getUnqualifiedType();
8065}
8066
8068 // C++ [except.throw]p3:
8069 // A throw-expression initializes a temporary object, called the exception
8070 // object, the type of which is determined by removing any top-level
8071 // cv-qualifiers from the static type of the operand of throw and adjusting
8072 // the type from "array of T" or "function returning T" to "pointer to T"
8073 // or "pointer to function returning T", [...]
8075 if (T->isArrayType() || T->isFunctionType())
8076 T = getDecayedType(T);
8077 return T.getUnqualifiedType();
8078}
8079
8080/// getArrayDecayedType - Return the properly qualified result of decaying the
8081/// specified array type to a pointer. This operation is non-trivial when
8082/// handling typedefs etc. The canonical type of "T" must be an array type,
8083/// this returns a pointer to a properly qualified element of the array.
8084///
8085/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8087 // Get the element type with 'getAsArrayType' so that we don't lose any
8088 // typedefs in the element type of the array. This also handles propagation
8089 // of type qualifiers from the array type into the element type if present
8090 // (C99 6.7.3p8).
8091 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8092 assert(PrettyArrayType && "Not an array type!");
8093
8094 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8095
8096 // int x[restrict 4] -> int *restrict
8098 PrettyArrayType->getIndexTypeQualifiers());
8099
8100 // int x[_Nullable] -> int * _Nullable
8101 if (auto Nullability = Ty->getNullability()) {
8102 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8103 Result, Result);
8104 }
8105 return Result;
8106}
8107
8109 return getBaseElementType(array->getElementType());
8110}
8111
8113 Qualifiers qs;
8114 while (true) {
8115 SplitQualType split = type.getSplitDesugaredType();
8116 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8117 if (!array) break;
8118
8119 type = array->getElementType();
8121 }
8122
8123 return getQualifiedType(type, qs);
8124}
8125
8126/// getConstantArrayElementCount - Returns number of constant array elements.
8127uint64_t
8129 uint64_t ElementCount = 1;
8130 do {
8131 ElementCount *= CA->getZExtSize();
8132 CA = dyn_cast_or_null<ConstantArrayType>(
8134 } while (CA);
8135 return ElementCount;
8136}
8137
8139 const ArrayInitLoopExpr *AILE) const {
8140 if (!AILE)
8141 return 0;
8142
8143 uint64_t ElementCount = 1;
8144
8145 do {
8146 ElementCount *= AILE->getArraySize().getZExtValue();
8147 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8148 } while (AILE);
8149
8150 return ElementCount;
8151}
8152
8153/// getFloatingRank - Return a relative rank for floating point types.
8154/// This routine will assert if passed a built-in type that isn't a float.
8156 if (const auto *CT = T->getAs<ComplexType>())
8157 return getFloatingRank(CT->getElementType());
8158
8159 switch (T->castAs<BuiltinType>()->getKind()) {
8160 default: llvm_unreachable("getFloatingRank(): not a floating type");
8161 case BuiltinType::Float16: return Float16Rank;
8162 case BuiltinType::Half: return HalfRank;
8163 case BuiltinType::Float: return FloatRank;
8164 case BuiltinType::Double: return DoubleRank;
8165 case BuiltinType::LongDouble: return LongDoubleRank;
8166 case BuiltinType::Float128: return Float128Rank;
8167 case BuiltinType::BFloat16: return BFloat16Rank;
8168 case BuiltinType::Ibm128: return Ibm128Rank;
8169 }
8170}
8171
8172/// getFloatingTypeOrder - Compare the rank of the two specified floating
8173/// point types, ignoring the domain of the type (i.e. 'double' ==
8174/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8175/// LHS < RHS, return -1.
8177 FloatingRank LHSR = getFloatingRank(LHS);
8178 FloatingRank RHSR = getFloatingRank(RHS);
8179
8180 if (LHSR == RHSR)
8181 return 0;
8182 if (LHSR > RHSR)
8183 return 1;
8184 return -1;
8185}
8186
8189 return 0;
8190 return getFloatingTypeOrder(LHS, RHS);
8191}
8192
8193/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8194/// routine will assert if passed a built-in type that isn't an integer or enum,
8195/// or if it is not canonicalized.
8196unsigned ASTContext::getIntegerRank(const Type *T) const {
8197 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8198
8199 // Results in this 'losing' to any type of the same size, but winning if
8200 // larger.
8201 if (const auto *EIT = dyn_cast<BitIntType>(T))
8202 return 0 + (EIT->getNumBits() << 3);
8203
8204 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8205 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8206
8207 switch (cast<BuiltinType>(T)->getKind()) {
8208 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8209 case BuiltinType::Bool:
8210 return 1 + (getIntWidth(BoolTy) << 3);
8211 case BuiltinType::Char_S:
8212 case BuiltinType::Char_U:
8213 case BuiltinType::SChar:
8214 case BuiltinType::UChar:
8215 return 2 + (getIntWidth(CharTy) << 3);
8216 case BuiltinType::Short:
8217 case BuiltinType::UShort:
8218 return 3 + (getIntWidth(ShortTy) << 3);
8219 case BuiltinType::Int:
8220 case BuiltinType::UInt:
8221 return 4 + (getIntWidth(IntTy) << 3);
8222 case BuiltinType::Long:
8223 case BuiltinType::ULong:
8224 return 5 + (getIntWidth(LongTy) << 3);
8225 case BuiltinType::LongLong:
8226 case BuiltinType::ULongLong:
8227 return 6 + (getIntWidth(LongLongTy) << 3);
8228 case BuiltinType::Int128:
8229 case BuiltinType::UInt128:
8230 return 7 + (getIntWidth(Int128Ty) << 3);
8231
8232 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8233 // their underlying types" [c++20 conv.rank]
8234 case BuiltinType::Char8:
8235 return getIntegerRank(UnsignedCharTy.getTypePtr());
8236 case BuiltinType::Char16:
8237 return getIntegerRank(
8238 getFromTargetType(Target->getChar16Type()).getTypePtr());
8239 case BuiltinType::Char32:
8240 return getIntegerRank(
8241 getFromTargetType(Target->getChar32Type()).getTypePtr());
8242 case BuiltinType::WChar_S:
8243 case BuiltinType::WChar_U:
8244 return getIntegerRank(
8245 getFromTargetType(Target->getWCharType()).getTypePtr());
8246 }
8247}
8248
8249/// Whether this is a promotable bitfield reference according
8250/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8251///
8252/// \returns the type this bit-field will promote to, or NULL if no
8253/// promotion occurs.
8255 if (E->isTypeDependent() || E->isValueDependent())
8256 return {};
8257
8258 // C++ [conv.prom]p5:
8259 // If the bit-field has an enumerated type, it is treated as any other
8260 // value of that type for promotion purposes.
8262 return {};
8263
8264 // FIXME: We should not do this unless E->refersToBitField() is true. This
8265 // matters in C where getSourceBitField() will find bit-fields for various
8266 // cases where the source expression is not a bit-field designator.
8267
8268 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8269 if (!Field)
8270 return {};
8271
8272 QualType FT = Field->getType();
8273
8274 uint64_t BitWidth = Field->getBitWidthValue();
8275 uint64_t IntSize = getTypeSize(IntTy);
8276 // C++ [conv.prom]p5:
8277 // A prvalue for an integral bit-field can be converted to a prvalue of type
8278 // int if int can represent all the values of the bit-field; otherwise, it
8279 // can be converted to unsigned int if unsigned int can represent all the
8280 // values of the bit-field. If the bit-field is larger yet, no integral
8281 // promotion applies to it.
8282 // C11 6.3.1.1/2:
8283 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8284 // If an int can represent all values of the original type (as restricted by
8285 // the width, for a bit-field), the value is converted to an int; otherwise,
8286 // it is converted to an unsigned int.
8287 //
8288 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8289 // We perform that promotion here to match GCC and C++.
8290 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8291 // greater than that of 'int'. We perform that promotion to match GCC.
8292 //
8293 // C23 6.3.1.1p2:
8294 // The value from a bit-field of a bit-precise integer type is converted to
8295 // the corresponding bit-precise integer type. (The rest is the same as in
8296 // C11.)
8297 if (QualType QT = Field->getType(); QT->isBitIntType())
8298 return QT;
8299
8300 if (BitWidth < IntSize)
8301 return IntTy;
8302
8303 if (BitWidth == IntSize)
8304 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8305
8306 // Bit-fields wider than int are not subject to promotions, and therefore act
8307 // like the base type. GCC has some weird bugs in this area that we
8308 // deliberately do not follow (GCC follows a pre-standard resolution to
8309 // C's DR315 which treats bit-width as being part of the type, and this leaks
8310 // into their semantics in some cases).
8311 return {};
8312}
8313
8314/// getPromotedIntegerType - Returns the type that Promotable will
8315/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8316/// integer type.
8318 assert(!Promotable.isNull());
8319 assert(isPromotableIntegerType(Promotable));
8320 if (const auto *ED = Promotable->getAsEnumDecl())
8321 return ED->getPromotionType();
8322
8323 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8324 // qualifier.
8325 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8326 QualType PromotedUnderlying =
8327 getPromotedIntegerType(OBT->getUnderlyingType());
8328 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8329 }
8330
8331 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8332 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8333 // (3.9.1) can be converted to a prvalue of the first of the following
8334 // types that can represent all the values of its underlying type:
8335 // int, unsigned int, long int, unsigned long int, long long int, or
8336 // unsigned long long int [...]
8337 // FIXME: Is there some better way to compute this?
8338 if (BT->getKind() == BuiltinType::WChar_S ||
8339 BT->getKind() == BuiltinType::WChar_U ||
8340 BT->getKind() == BuiltinType::Char8 ||
8341 BT->getKind() == BuiltinType::Char16 ||
8342 BT->getKind() == BuiltinType::Char32) {
8343 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8344 uint64_t FromSize = getTypeSize(BT);
8345 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8347 for (const auto &PT : PromoteTypes) {
8348 uint64_t ToSize = getTypeSize(PT);
8349 if (FromSize < ToSize ||
8350 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8351 return PT;
8352 }
8353 llvm_unreachable("char type should fit into long long");
8354 }
8355 }
8356
8357 // At this point, we should have a signed or unsigned integer type.
8358 if (Promotable->isSignedIntegerType())
8359 return IntTy;
8360 uint64_t PromotableSize = getIntWidth(Promotable);
8361 uint64_t IntSize = getIntWidth(IntTy);
8362 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8363 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8364}
8365
8366/// Recurses in pointer/array types until it finds an objc retainable
8367/// type and returns its ownership.
8369 while (!T.isNull()) {
8370 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8371 return T.getObjCLifetime();
8372 if (T->isArrayType())
8373 T = getBaseElementType(T);
8374 else if (const auto *PT = T->getAs<PointerType>())
8375 T = PT->getPointeeType();
8376 else if (const auto *RT = T->getAs<ReferenceType>())
8377 T = RT->getPointeeType();
8378 else
8379 break;
8380 }
8381
8382 return Qualifiers::OCL_None;
8383}
8384
8385static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8386 // Incomplete enum types are not treated as integer types.
8387 // FIXME: In C++, enum types are never integer types.
8388 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8389 if (ED->isComplete() && !ED->isScoped())
8390 return ED->getIntegerType().getTypePtr();
8391 return nullptr;
8392}
8393
8394/// getIntegerTypeOrder - Returns the highest ranked integer type:
8395/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8396/// LHS < RHS, return -1.
8398 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8399 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8400
8401 // Unwrap enums to their underlying type.
8402 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8403 LHSC = getIntegerTypeForEnum(ET);
8404 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8405 RHSC = getIntegerTypeForEnum(ET);
8406
8407 if (LHSC == RHSC) return 0;
8408
8409 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8410 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8411
8412 unsigned LHSRank = getIntegerRank(LHSC);
8413 unsigned RHSRank = getIntegerRank(RHSC);
8414
8415 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8416 if (LHSRank == RHSRank) return 0;
8417 return LHSRank > RHSRank ? 1 : -1;
8418 }
8419
8420 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8421 if (LHSUnsigned) {
8422 // If the unsigned [LHS] type is larger, return it.
8423 if (LHSRank >= RHSRank)
8424 return 1;
8425
8426 // If the signed type can represent all values of the unsigned type, it
8427 // wins. Because we are dealing with 2's complement and types that are
8428 // powers of two larger than each other, this is always safe.
8429 return -1;
8430 }
8431
8432 // If the unsigned [RHS] type is larger, return it.
8433 if (RHSRank >= LHSRank)
8434 return -1;
8435
8436 // If the signed type can represent all values of the unsigned type, it
8437 // wins. Because we are dealing with 2's complement and types that are
8438 // powers of two larger than each other, this is always safe.
8439 return 1;
8440}
8441
8443 if (CFConstantStringTypeDecl)
8444 return CFConstantStringTypeDecl;
8445
8446 assert(!CFConstantStringTagDecl &&
8447 "tag and typedef should be initialized together");
8448 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8449 CFConstantStringTagDecl->startDefinition();
8450
8451 struct {
8452 QualType Type;
8453 const char *Name;
8454 } Fields[5];
8455 unsigned Count = 0;
8456
8457 /// Objective-C ABI
8458 ///
8459 /// typedef struct __NSConstantString_tag {
8460 /// const int *isa;
8461 /// int flags;
8462 /// const char *str;
8463 /// long length;
8464 /// } __NSConstantString;
8465 ///
8466 /// Swift ABI (4.1, 4.2)
8467 ///
8468 /// typedef struct __NSConstantString_tag {
8469 /// uintptr_t _cfisa;
8470 /// uintptr_t _swift_rc;
8471 /// _Atomic(uint64_t) _cfinfoa;
8472 /// const char *_ptr;
8473 /// uint32_t _length;
8474 /// } __NSConstantString;
8475 ///
8476 /// Swift ABI (5.0)
8477 ///
8478 /// typedef struct __NSConstantString_tag {
8479 /// uintptr_t _cfisa;
8480 /// uintptr_t _swift_rc;
8481 /// _Atomic(uint64_t) _cfinfoa;
8482 /// const char *_ptr;
8483 /// uintptr_t _length;
8484 /// } __NSConstantString;
8485
8486 const auto CFRuntime = getLangOpts().CFRuntime;
8487 if (static_cast<unsigned>(CFRuntime) <
8488 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8489 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8490 Fields[Count++] = { IntTy, "flags" };
8491 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8492 Fields[Count++] = { LongTy, "length" };
8493 } else {
8494 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8495 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8496 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8497 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8500 Fields[Count++] = { IntTy, "_ptr" };
8501 else
8502 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8503 }
8504
8505 // Create fields
8506 for (unsigned i = 0; i < Count; ++i) {
8507 FieldDecl *Field =
8508 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8509 SourceLocation(), &Idents.get(Fields[i].Name),
8510 Fields[i].Type, /*TInfo=*/nullptr,
8511 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8512 Field->setAccess(AS_public);
8513 CFConstantStringTagDecl->addDecl(Field);
8514 }
8515
8516 CFConstantStringTagDecl->completeDefinition();
8517 // This type is designed to be compatible with NSConstantString, but cannot
8518 // use the same name, since NSConstantString is an interface.
8519 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8520 CFConstantStringTypeDecl =
8521 buildImplicitTypedef(tagType, "__NSConstantString");
8522
8523 return CFConstantStringTypeDecl;
8524}
8525
8527 if (!CFConstantStringTagDecl)
8528 getCFConstantStringDecl(); // Build the tag and the typedef.
8529 return CFConstantStringTagDecl;
8530}
8531
8532// getCFConstantStringType - Return the type used for constant CFStrings.
8537
8539 if (ObjCSuperType.isNull()) {
8540 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8541 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8542 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8543 }
8544 return ObjCSuperType;
8545}
8546
8548 const auto *TT = T->castAs<TypedefType>();
8549 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8550 CFConstantStringTagDecl = TT->castAsRecordDecl();
8551}
8552
8554 if (BlockDescriptorType)
8555 return getCanonicalTagType(BlockDescriptorType);
8556
8557 RecordDecl *RD;
8558 // FIXME: Needs the FlagAppleBlock bit.
8559 RD = buildImplicitRecord("__block_descriptor");
8560 RD->startDefinition();
8561
8562 QualType FieldTypes[] = {
8565 };
8566
8567 static const char *const FieldNames[] = {
8568 "reserved",
8569 "Size"
8570 };
8571
8572 for (size_t i = 0; i < 2; ++i) {
8574 *this, RD, SourceLocation(), SourceLocation(),
8575 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8576 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8577 Field->setAccess(AS_public);
8578 RD->addDecl(Field);
8579 }
8580
8581 RD->completeDefinition();
8582
8583 BlockDescriptorType = RD;
8584
8585 return getCanonicalTagType(BlockDescriptorType);
8586}
8587
8589 if (BlockDescriptorExtendedType)
8590 return getCanonicalTagType(BlockDescriptorExtendedType);
8591
8592 RecordDecl *RD;
8593 // FIXME: Needs the FlagAppleBlock bit.
8594 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8595 RD->startDefinition();
8596
8597 QualType FieldTypes[] = {
8602 };
8603
8604 static const char *const FieldNames[] = {
8605 "reserved",
8606 "Size",
8607 "CopyFuncPtr",
8608 "DestroyFuncPtr"
8609 };
8610
8611 for (size_t i = 0; i < 4; ++i) {
8613 *this, RD, SourceLocation(), SourceLocation(),
8614 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8615 /*BitWidth=*/nullptr,
8616 /*Mutable=*/false, ICIS_NoInit);
8617 Field->setAccess(AS_public);
8618 RD->addDecl(Field);
8619 }
8620
8621 RD->completeDefinition();
8622
8623 BlockDescriptorExtendedType = RD;
8624 return getCanonicalTagType(BlockDescriptorExtendedType);
8625}
8626
8628 const auto *BT = dyn_cast<BuiltinType>(T);
8629
8630 if (!BT) {
8631 if (isa<PipeType>(T))
8632 return OCLTK_Pipe;
8633
8634 return OCLTK_Default;
8635 }
8636
8637 switch (BT->getKind()) {
8638#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8639 case BuiltinType::Id: \
8640 return OCLTK_Image;
8641#include "clang/Basic/OpenCLImageTypes.def"
8642
8643 case BuiltinType::OCLClkEvent:
8644 return OCLTK_ClkEvent;
8645
8646 case BuiltinType::OCLEvent:
8647 return OCLTK_Event;
8648
8649 case BuiltinType::OCLQueue:
8650 return OCLTK_Queue;
8651
8652 case BuiltinType::OCLReserveID:
8653 return OCLTK_ReserveID;
8654
8655 case BuiltinType::OCLSampler:
8656 return OCLTK_Sampler;
8657
8658 default:
8659 return OCLTK_Default;
8660 }
8661}
8662
8664 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8665}
8666
8667/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8668/// requires copy/dispose. Note that this must match the logic
8669/// in buildByrefHelpers.
8671 const VarDecl *D) {
8672 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8673 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8674 if (!copyExpr && record->hasTrivialDestructor()) return false;
8675
8676 return true;
8677 }
8678
8680 return true;
8681
8682 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8683 // move or destroy.
8685 return true;
8686
8687 if (!Ty->isObjCRetainableType()) return false;
8688
8689 Qualifiers qs = Ty.getQualifiers();
8690
8691 // If we have lifetime, that dominates.
8692 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8693 switch (lifetime) {
8694 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8695
8696 // These are just bits as far as the runtime is concerned.
8699 return false;
8700
8701 // These cases should have been taken care of when checking the type's
8702 // non-triviality.
8705 llvm_unreachable("impossible");
8706 }
8707 llvm_unreachable("fell out of lifetime switch!");
8708 }
8709 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8711}
8712
8714 Qualifiers::ObjCLifetime &LifeTime,
8715 bool &HasByrefExtendedLayout) const {
8716 if (!getLangOpts().ObjC ||
8717 getLangOpts().getGC() != LangOptions::NonGC)
8718 return false;
8719
8720 HasByrefExtendedLayout = false;
8721 if (Ty->isRecordType()) {
8722 HasByrefExtendedLayout = true;
8723 LifeTime = Qualifiers::OCL_None;
8724 } else if ((LifeTime = Ty.getObjCLifetime())) {
8725 // Honor the ARC qualifiers.
8726 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8727 // The MRR rule.
8729 } else {
8730 LifeTime = Qualifiers::OCL_None;
8731 }
8732 return true;
8733}
8734
8736 assert(Target && "Expected target to be initialized");
8737 const llvm::Triple &T = Target->getTriple();
8738 // Windows is LLP64 rather than LP64
8739 if (T.isOSWindows() && T.isArch64Bit())
8740 return UnsignedLongLongTy;
8741 return UnsignedLongTy;
8742}
8743
8745 assert(Target && "Expected target to be initialized");
8746 const llvm::Triple &T = Target->getTriple();
8747 // Windows is LLP64 rather than LP64
8748 if (T.isOSWindows() && T.isArch64Bit())
8749 return LongLongTy;
8750 return LongTy;
8751}
8752
8754 if (!ObjCInstanceTypeDecl)
8755 ObjCInstanceTypeDecl =
8756 buildImplicitTypedef(getObjCIdType(), "instancetype");
8757 return ObjCInstanceTypeDecl;
8758}
8759
8760// This returns true if a type has been typedefed to BOOL:
8761// typedef <type> BOOL;
8763 if (const auto *TT = dyn_cast<TypedefType>(T))
8764 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8765 return II->isStr("BOOL");
8766
8767 return false;
8768}
8769
8770/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8771/// purpose.
8773 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8774 return CharUnits::Zero();
8775
8777
8778 // Make all integer and enum types at least as large as an int
8779 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8780 sz = std::max(sz, getTypeSizeInChars(IntTy));
8781 // Treat arrays as pointers, since that's how they're passed in.
8782 else if (type->isArrayType())
8784 return sz;
8785}
8786
8793
8796 if (!VD->isInline())
8798
8799 // In almost all cases, it's a weak definition.
8800 auto *First = VD->getFirstDecl();
8801 if (First->isInlineSpecified() || !First->isStaticDataMember())
8803
8804 // If there's a file-context declaration in this translation unit, it's a
8805 // non-discardable definition.
8806 for (auto *D : VD->redecls())
8808 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8810
8811 // If we've not seen one yet, we don't know.
8813}
8814
8815static std::string charUnitsToString(const CharUnits &CU) {
8816 return llvm::itostr(CU.getQuantity());
8817}
8818
8819/// getObjCEncodingForBlock - Return the encoded type for this block
8820/// declaration.
8822 std::string S;
8823
8824 const BlockDecl *Decl = Expr->getBlockDecl();
8825 QualType BlockTy =
8827 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8828 // Encode result type.
8829 if (getLangOpts().EncodeExtendedBlockSig)
8831 true /*Extended*/);
8832 else
8833 getObjCEncodingForType(BlockReturnTy, S);
8834 // Compute size of all parameters.
8835 // Start with computing size of a pointer in number of bytes.
8836 // FIXME: There might(should) be a better way of doing this computation!
8838 CharUnits ParmOffset = PtrSize;
8839 for (auto *PI : Decl->parameters()) {
8840 QualType PType = PI->getType();
8842 if (sz.isZero())
8843 continue;
8844 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8845 ParmOffset += sz;
8846 }
8847 // Size of the argument frame
8848 S += charUnitsToString(ParmOffset);
8849 // Block pointer and offset.
8850 S += "@?0";
8851
8852 // Argument types.
8853 ParmOffset = PtrSize;
8854 for (auto *PVDecl : Decl->parameters()) {
8855 QualType PType = PVDecl->getOriginalType();
8856 if (const auto *AT =
8857 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8858 // Use array's original type only if it has known number of
8859 // elements.
8860 if (!isa<ConstantArrayType>(AT))
8861 PType = PVDecl->getType();
8862 } else if (PType->isFunctionType())
8863 PType = PVDecl->getType();
8864 if (getLangOpts().EncodeExtendedBlockSig)
8866 S, true /*Extended*/);
8867 else
8868 getObjCEncodingForType(PType, S);
8869 S += charUnitsToString(ParmOffset);
8870 ParmOffset += getObjCEncodingTypeSize(PType);
8871 }
8872
8873 return S;
8874}
8875
8876std::string
8878 std::string S;
8879 // Encode result type.
8880 getObjCEncodingForType(Decl->getReturnType(), S);
8881 CharUnits ParmOffset;
8882 // Compute size of all parameters.
8883 for (auto *PI : Decl->parameters()) {
8884 QualType PType = PI->getType();
8886 if (sz.isZero())
8887 continue;
8888
8889 assert(sz.isPositive() &&
8890 "getObjCEncodingForFunctionDecl - Incomplete param type");
8891 ParmOffset += sz;
8892 }
8893 S += charUnitsToString(ParmOffset);
8894 ParmOffset = CharUnits::Zero();
8895
8896 // Argument types.
8897 for (auto *PVDecl : Decl->parameters()) {
8898 QualType PType = PVDecl->getOriginalType();
8899 if (const auto *AT =
8900 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8901 // Use array's original type only if it has known number of
8902 // elements.
8903 if (!isa<ConstantArrayType>(AT))
8904 PType = PVDecl->getType();
8905 } else if (PType->isFunctionType())
8906 PType = PVDecl->getType();
8907 getObjCEncodingForType(PType, S);
8908 S += charUnitsToString(ParmOffset);
8909 ParmOffset += getObjCEncodingTypeSize(PType);
8910 }
8911
8912 return S;
8913}
8914
8915/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8916/// method parameter or return type. If Extended, include class names and
8917/// block object types.
8919 QualType T, std::string& S,
8920 bool Extended) const {
8921 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8923 // Encode parameter type.
8924 ObjCEncOptions Options = ObjCEncOptions()
8925 .setExpandPointedToStructures()
8926 .setExpandStructures()
8927 .setIsOutermostType();
8928 if (Extended)
8929 Options.setEncodeBlockParameters().setEncodeClassNames();
8930 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8931}
8932
8933/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8934/// declaration.
8936 bool Extended) const {
8937 // FIXME: This is not very efficient.
8938 // Encode return type.
8939 std::string S;
8940 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8941 Decl->getReturnType(), S, Extended);
8942 // Compute size of all parameters.
8943 // Start with computing size of a pointer in number of bytes.
8944 // FIXME: There might(should) be a better way of doing this computation!
8946 // The first two arguments (self and _cmd) are pointers; account for
8947 // their size.
8948 CharUnits ParmOffset = 2 * PtrSize;
8949 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8950 E = Decl->sel_param_end(); PI != E; ++PI) {
8951 QualType PType = (*PI)->getType();
8953 if (sz.isZero())
8954 continue;
8955
8956 assert(sz.isPositive() &&
8957 "getObjCEncodingForMethodDecl - Incomplete param type");
8958 ParmOffset += sz;
8959 }
8960 S += charUnitsToString(ParmOffset);
8961 S += "@0:";
8962 S += charUnitsToString(PtrSize);
8963
8964 // Argument types.
8965 ParmOffset = 2 * PtrSize;
8966 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8967 E = Decl->sel_param_end(); PI != E; ++PI) {
8968 const ParmVarDecl *PVDecl = *PI;
8969 QualType PType = PVDecl->getOriginalType();
8970 if (const auto *AT =
8971 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8972 // Use array's original type only if it has known number of
8973 // elements.
8974 if (!isa<ConstantArrayType>(AT))
8975 PType = PVDecl->getType();
8976 } else if (PType->isFunctionType())
8977 PType = PVDecl->getType();
8979 PType, S, Extended);
8980 S += charUnitsToString(ParmOffset);
8981 ParmOffset += getObjCEncodingTypeSize(PType);
8982 }
8983
8984 return S;
8985}
8986
8989 const ObjCPropertyDecl *PD,
8990 const Decl *Container) const {
8991 if (!Container)
8992 return nullptr;
8993 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8994 for (auto *PID : CID->property_impls())
8995 if (PID->getPropertyDecl() == PD)
8996 return PID;
8997 } else {
8998 const auto *OID = cast<ObjCImplementationDecl>(Container);
8999 for (auto *PID : OID->property_impls())
9000 if (PID->getPropertyDecl() == PD)
9001 return PID;
9002 }
9003 return nullptr;
9004}
9005
9006/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9007/// property declaration. If non-NULL, Container must be either an
9008/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9009/// NULL when getting encodings for protocol properties.
9010/// Property attributes are stored as a comma-delimited C string. The simple
9011/// attributes readonly and bycopy are encoded as single characters. The
9012/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9013/// encoded as single characters, followed by an identifier. Property types
9014/// are also encoded as a parametrized attribute. The characters used to encode
9015/// these attributes are defined by the following enumeration:
9016/// @code
9017/// enum PropertyAttributes {
9018/// kPropertyReadOnly = 'R', // property is read-only.
9019/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9020/// kPropertyByref = '&', // property is a reference to the value last assigned
9021/// kPropertyDynamic = 'D', // property is dynamic
9022/// kPropertyGetter = 'G', // followed by getter selector name
9023/// kPropertySetter = 'S', // followed by setter selector name
9024/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9025/// kPropertyType = 'T' // followed by old-style type encoding.
9026/// kPropertyWeak = 'W' // 'weak' property
9027/// kPropertyStrong = 'P' // property GC'able
9028/// kPropertyNonAtomic = 'N' // property non-atomic
9029/// kPropertyOptional = '?' // property optional
9030/// };
9031/// @endcode
9032std::string
9034 const Decl *Container) const {
9035 // Collect information from the property implementation decl(s).
9036 bool Dynamic = false;
9037 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9038
9039 if (ObjCPropertyImplDecl *PropertyImpDecl =
9041 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9042 Dynamic = true;
9043 else
9044 SynthesizePID = PropertyImpDecl;
9045 }
9046
9047 // FIXME: This is not very efficient.
9048 std::string S = "T";
9049
9050 // Encode result type.
9051 // GCC has some special rules regarding encoding of properties which
9052 // closely resembles encoding of ivars.
9054
9055 if (PD->isOptional())
9056 S += ",?";
9057
9058 if (PD->isReadOnly()) {
9059 S += ",R";
9061 S += ",C";
9063 S += ",&";
9065 S += ",W";
9066 } else {
9067 switch (PD->getSetterKind()) {
9068 case ObjCPropertyDecl::Assign: break;
9069 case ObjCPropertyDecl::Copy: S += ",C"; break;
9070 case ObjCPropertyDecl::Retain: S += ",&"; break;
9071 case ObjCPropertyDecl::Weak: S += ",W"; break;
9072 }
9073 }
9074
9075 // It really isn't clear at all what this means, since properties
9076 // are "dynamic by default".
9077 if (Dynamic)
9078 S += ",D";
9079
9081 S += ",N";
9082
9084 S += ",G";
9085 S += PD->getGetterName().getAsString();
9086 }
9087
9089 S += ",S";
9090 S += PD->getSetterName().getAsString();
9091 }
9092
9093 if (SynthesizePID) {
9094 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9095 S += ",V";
9096 S += OID->getNameAsString();
9097 }
9098
9099 // FIXME: OBJCGC: weak & strong
9100 return S;
9101}
9102
9103/// getLegacyIntegralTypeEncoding -
9104/// Another legacy compatibility encoding: 32-bit longs are encoded as
9105/// 'l' or 'L' , but not always. For typedefs, we need to use
9106/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9108 if (PointeeTy->getAs<TypedefType>()) {
9109 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9110 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9111 PointeeTy = UnsignedIntTy;
9112 else
9113 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9114 PointeeTy = IntTy;
9115 }
9116 }
9117}
9118
9120 const FieldDecl *Field,
9121 QualType *NotEncodedT) const {
9122 // We follow the behavior of gcc, expanding structures which are
9123 // directly pointed to, and expanding embedded structures. Note that
9124 // these rules are sufficient to prevent recursive encoding of the
9125 // same type.
9126 getObjCEncodingForTypeImpl(T, S,
9127 ObjCEncOptions()
9128 .setExpandPointedToStructures()
9129 .setExpandStructures()
9130 .setIsOutermostType(),
9131 Field, NotEncodedT);
9132}
9133
9135 std::string& S) const {
9136 // Encode result type.
9137 // GCC has some special rules regarding encoding of properties which
9138 // closely resembles encoding of ivars.
9139 getObjCEncodingForTypeImpl(T, S,
9140 ObjCEncOptions()
9141 .setExpandPointedToStructures()
9142 .setExpandStructures()
9143 .setIsOutermostType()
9144 .setEncodingProperty(),
9145 /*Field=*/nullptr);
9146}
9147
9149 const BuiltinType *BT) {
9151 switch (kind) {
9152 case BuiltinType::Void: return 'v';
9153 case BuiltinType::Bool: return 'B';
9154 case BuiltinType::Char8:
9155 case BuiltinType::Char_U:
9156 case BuiltinType::UChar: return 'C';
9157 case BuiltinType::Char16:
9158 case BuiltinType::UShort: return 'S';
9159 case BuiltinType::Char32:
9160 case BuiltinType::UInt: return 'I';
9161 case BuiltinType::ULong:
9162 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9163 case BuiltinType::UInt128: return 'T';
9164 case BuiltinType::ULongLong: return 'Q';
9165 case BuiltinType::Char_S:
9166 case BuiltinType::SChar: return 'c';
9167 case BuiltinType::Short: return 's';
9168 case BuiltinType::WChar_S:
9169 case BuiltinType::WChar_U:
9170 case BuiltinType::Int: return 'i';
9171 case BuiltinType::Long:
9172 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9173 case BuiltinType::LongLong: return 'q';
9174 case BuiltinType::Int128: return 't';
9175 case BuiltinType::Float: return 'f';
9176 case BuiltinType::Double: return 'd';
9177 case BuiltinType::LongDouble: return 'D';
9178 case BuiltinType::NullPtr: return '*'; // like char*
9179
9180 case BuiltinType::BFloat16:
9181 case BuiltinType::Float16:
9182 case BuiltinType::Float128:
9183 case BuiltinType::Ibm128:
9184 case BuiltinType::Half:
9185 case BuiltinType::ShortAccum:
9186 case BuiltinType::Accum:
9187 case BuiltinType::LongAccum:
9188 case BuiltinType::UShortAccum:
9189 case BuiltinType::UAccum:
9190 case BuiltinType::ULongAccum:
9191 case BuiltinType::ShortFract:
9192 case BuiltinType::Fract:
9193 case BuiltinType::LongFract:
9194 case BuiltinType::UShortFract:
9195 case BuiltinType::UFract:
9196 case BuiltinType::ULongFract:
9197 case BuiltinType::SatShortAccum:
9198 case BuiltinType::SatAccum:
9199 case BuiltinType::SatLongAccum:
9200 case BuiltinType::SatUShortAccum:
9201 case BuiltinType::SatUAccum:
9202 case BuiltinType::SatULongAccum:
9203 case BuiltinType::SatShortFract:
9204 case BuiltinType::SatFract:
9205 case BuiltinType::SatLongFract:
9206 case BuiltinType::SatUShortFract:
9207 case BuiltinType::SatUFract:
9208 case BuiltinType::SatULongFract:
9209 // FIXME: potentially need @encodes for these!
9210 return ' ';
9211
9212#define SVE_TYPE(Name, Id, SingletonId) \
9213 case BuiltinType::Id:
9214#include "clang/Basic/AArch64ACLETypes.def"
9215#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9216#include "clang/Basic/RISCVVTypes.def"
9217#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9218#include "clang/Basic/WebAssemblyReferenceTypes.def"
9219#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9220#include "clang/Basic/AMDGPUTypes.def"
9221 {
9222 DiagnosticsEngine &Diags = C->getDiagnostics();
9223 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9224 << QualType(BT, 0);
9225 return ' ';
9226 }
9227
9228 case BuiltinType::ObjCId:
9229 case BuiltinType::ObjCClass:
9230 case BuiltinType::ObjCSel:
9231 llvm_unreachable("@encoding ObjC primitive type");
9232
9233 // OpenCL and placeholder types don't need @encodings.
9234#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9235 case BuiltinType::Id:
9236#include "clang/Basic/OpenCLImageTypes.def"
9237#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9238 case BuiltinType::Id:
9239#include "clang/Basic/OpenCLExtensionTypes.def"
9240 case BuiltinType::OCLEvent:
9241 case BuiltinType::OCLClkEvent:
9242 case BuiltinType::OCLQueue:
9243 case BuiltinType::OCLReserveID:
9244 case BuiltinType::OCLSampler:
9245 case BuiltinType::Dependent:
9246#define PPC_VECTOR_TYPE(Name, Id, Size) \
9247 case BuiltinType::Id:
9248#include "clang/Basic/PPCTypes.def"
9249#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9250#include "clang/Basic/HLSLIntangibleTypes.def"
9251#define BUILTIN_TYPE(KIND, ID)
9252#define PLACEHOLDER_TYPE(KIND, ID) \
9253 case BuiltinType::KIND:
9254#include "clang/AST/BuiltinTypes.def"
9255 llvm_unreachable("invalid builtin type for @encode");
9256 }
9257 llvm_unreachable("invalid BuiltinType::Kind value");
9258}
9259
9260static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9262
9263 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9264 if (!Enum->isFixed())
9265 return 'i';
9266
9267 // The encoding of a fixed enum type matches its fixed underlying type.
9268 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9270}
9271
9272static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9273 QualType T, const FieldDecl *FD) {
9274 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9275 S += 'b';
9276 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9277 // The GNU runtime requires more information; bitfields are encoded as b,
9278 // then the offset (in bits) of the first element, then the type of the
9279 // bitfield, then the size in bits. For example, in this structure:
9280 //
9281 // struct
9282 // {
9283 // int integer;
9284 // int flags:2;
9285 // };
9286 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9287 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9288 // information is not especially sensible, but we're stuck with it for
9289 // compatibility with GCC, although providing it breaks anything that
9290 // actually uses runtime introspection and wants to work on both runtimes...
9291 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9292 uint64_t Offset;
9293
9294 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9295 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9296 } else {
9297 const RecordDecl *RD = FD->getParent();
9298 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9299 Offset = RL.getFieldOffset(FD->getFieldIndex());
9300 }
9301
9302 S += llvm::utostr(Offset);
9303
9304 if (const auto *ET = T->getAsCanonical<EnumType>())
9305 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9306 else {
9307 const auto *BT = T->castAs<BuiltinType>();
9308 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9309 }
9310 }
9311 S += llvm::utostr(FD->getBitWidthValue());
9312}
9313
9314// Helper function for determining whether the encoded type string would include
9315// a template specialization type.
9317 bool VisitBasesAndFields) {
9318 T = T->getBaseElementTypeUnsafe();
9319
9320 if (auto *PT = T->getAs<PointerType>())
9322 PT->getPointeeType().getTypePtr(), false);
9323
9324 auto *CXXRD = T->getAsCXXRecordDecl();
9325
9326 if (!CXXRD)
9327 return false;
9328
9330 return true;
9331
9332 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9333 return false;
9334
9335 for (const auto &B : CXXRD->bases())
9336 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9337 true))
9338 return true;
9339
9340 for (auto *FD : CXXRD->fields())
9341 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9342 true))
9343 return true;
9344
9345 return false;
9346}
9347
9348// FIXME: Use SmallString for accumulating string.
9349void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9350 const ObjCEncOptions Options,
9351 const FieldDecl *FD,
9352 QualType *NotEncodedT) const {
9354 switch (CT->getTypeClass()) {
9355 case Type::Builtin:
9356 case Type::Enum:
9357 if (FD && FD->isBitField())
9358 return EncodeBitField(this, S, T, FD);
9359 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9360 S += getObjCEncodingForPrimitiveType(this, BT);
9361 else
9362 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9363 return;
9364
9365 case Type::Complex:
9366 S += 'j';
9367 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9368 ObjCEncOptions(),
9369 /*Field=*/nullptr);
9370 return;
9371
9372 case Type::Atomic:
9373 S += 'A';
9374 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9375 ObjCEncOptions(),
9376 /*Field=*/nullptr);
9377 return;
9378
9379 // encoding for pointer or reference types.
9380 case Type::Pointer:
9381 case Type::LValueReference:
9382 case Type::RValueReference: {
9383 QualType PointeeTy;
9384 if (isa<PointerType>(CT)) {
9385 const auto *PT = T->castAs<PointerType>();
9386 if (PT->isObjCSelType()) {
9387 S += ':';
9388 return;
9389 }
9390 PointeeTy = PT->getPointeeType();
9391 } else {
9392 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9393 }
9394
9395 bool isReadOnly = false;
9396 // For historical/compatibility reasons, the read-only qualifier of the
9397 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9398 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9399 // Also, do not emit the 'r' for anything but the outermost type!
9400 if (T->getAs<TypedefType>()) {
9401 if (Options.IsOutermostType() && T.isConstQualified()) {
9402 isReadOnly = true;
9403 S += 'r';
9404 }
9405 } else if (Options.IsOutermostType()) {
9406 QualType P = PointeeTy;
9407 while (auto PT = P->getAs<PointerType>())
9408 P = PT->getPointeeType();
9409 if (P.isConstQualified()) {
9410 isReadOnly = true;
9411 S += 'r';
9412 }
9413 }
9414 if (isReadOnly) {
9415 // Another legacy compatibility encoding. Some ObjC qualifier and type
9416 // combinations need to be rearranged.
9417 // Rewrite "in const" from "nr" to "rn"
9418 if (StringRef(S).ends_with("nr"))
9419 S.replace(S.end()-2, S.end(), "rn");
9420 }
9421
9422 if (PointeeTy->isCharType()) {
9423 // char pointer types should be encoded as '*' unless it is a
9424 // type that has been typedef'd to 'BOOL'.
9425 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9426 S += '*';
9427 return;
9428 }
9429 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9430 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9431 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9432 if (II == &Idents.get("objc_class")) {
9433 S += '#';
9434 return;
9435 }
9436 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9437 if (II == &Idents.get("objc_object")) {
9438 S += '@';
9439 return;
9440 }
9441 // If the encoded string for the class includes template names, just emit
9442 // "^v" for pointers to the class.
9443 if (getLangOpts().CPlusPlus &&
9444 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9446 RTy, Options.ExpandPointedToStructures()))) {
9447 S += "^v";
9448 return;
9449 }
9450 // fall through...
9451 }
9452 S += '^';
9454
9455 ObjCEncOptions NewOptions;
9456 if (Options.ExpandPointedToStructures())
9457 NewOptions.setExpandStructures();
9458 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9459 /*Field=*/nullptr, NotEncodedT);
9460 return;
9461 }
9462
9463 case Type::ConstantArray:
9464 case Type::IncompleteArray:
9465 case Type::VariableArray: {
9466 const auto *AT = cast<ArrayType>(CT);
9467
9468 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9469 // Incomplete arrays are encoded as a pointer to the array element.
9470 S += '^';
9471
9472 getObjCEncodingForTypeImpl(
9473 AT->getElementType(), S,
9474 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9475 } else {
9476 S += '[';
9477
9478 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9479 S += llvm::utostr(CAT->getZExtSize());
9480 else {
9481 //Variable length arrays are encoded as a regular array with 0 elements.
9483 "Unknown array type!");
9484 S += '0';
9485 }
9486
9487 getObjCEncodingForTypeImpl(
9488 AT->getElementType(), S,
9489 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9490 NotEncodedT);
9491 S += ']';
9492 }
9493 return;
9494 }
9495
9496 case Type::FunctionNoProto:
9497 case Type::FunctionProto:
9498 S += '?';
9499 return;
9500
9501 case Type::Record: {
9502 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9503 S += RDecl->isUnion() ? '(' : '{';
9504 // Anonymous structures print as '?'
9505 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9506 S += II->getName();
9507 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9508 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9509 llvm::raw_string_ostream OS(S);
9510 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9512 }
9513 } else {
9514 S += '?';
9515 }
9516 if (Options.ExpandStructures()) {
9517 S += '=';
9518 if (!RDecl->isUnion()) {
9519 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9520 } else {
9521 for (const auto *Field : RDecl->fields()) {
9522 if (FD) {
9523 S += '"';
9524 S += Field->getNameAsString();
9525 S += '"';
9526 }
9527
9528 // Special case bit-fields.
9529 if (Field->isBitField()) {
9530 getObjCEncodingForTypeImpl(Field->getType(), S,
9531 ObjCEncOptions().setExpandStructures(),
9532 Field);
9533 } else {
9534 QualType qt = Field->getType();
9536 getObjCEncodingForTypeImpl(
9537 qt, S,
9538 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9539 NotEncodedT);
9540 }
9541 }
9542 }
9543 }
9544 S += RDecl->isUnion() ? ')' : '}';
9545 return;
9546 }
9547
9548 case Type::BlockPointer: {
9549 const auto *BT = T->castAs<BlockPointerType>();
9550 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9551 if (Options.EncodeBlockParameters()) {
9552 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9553
9554 S += '<';
9555 // Block return type
9556 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9557 Options.forComponentType(), FD, NotEncodedT);
9558 // Block self
9559 S += "@?";
9560 // Block parameters
9561 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9562 for (const auto &I : FPT->param_types())
9563 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9564 NotEncodedT);
9565 }
9566 S += '>';
9567 }
9568 return;
9569 }
9570
9571 case Type::ObjCObject: {
9572 // hack to match legacy encoding of *id and *Class
9573 QualType Ty = getObjCObjectPointerType(CT);
9574 if (Ty->isObjCIdType()) {
9575 S += "{objc_object=}";
9576 return;
9577 }
9578 else if (Ty->isObjCClassType()) {
9579 S += "{objc_class=}";
9580 return;
9581 }
9582 // TODO: Double check to make sure this intentionally falls through.
9583 [[fallthrough]];
9584 }
9585
9586 case Type::ObjCInterface: {
9587 // Ignore protocol qualifiers when mangling at this level.
9588 // @encode(class_name)
9589 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9590 S += '{';
9591 S += OI->getObjCRuntimeNameAsString();
9592 if (Options.ExpandStructures()) {
9593 S += '=';
9594 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9595 DeepCollectObjCIvars(OI, true, Ivars);
9596 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9597 const FieldDecl *Field = Ivars[i];
9598 if (Field->isBitField())
9599 getObjCEncodingForTypeImpl(Field->getType(), S,
9600 ObjCEncOptions().setExpandStructures(),
9601 Field);
9602 else
9603 getObjCEncodingForTypeImpl(Field->getType(), S,
9604 ObjCEncOptions().setExpandStructures(), FD,
9605 NotEncodedT);
9606 }
9607 }
9608 S += '}';
9609 return;
9610 }
9611
9612 case Type::ObjCObjectPointer: {
9613 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9614 if (OPT->isObjCIdType()) {
9615 S += '@';
9616 return;
9617 }
9618
9619 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9620 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9621 // Since this is a binary compatibility issue, need to consult with
9622 // runtime folks. Fortunately, this is a *very* obscure construct.
9623 S += '#';
9624 return;
9625 }
9626
9627 if (OPT->isObjCQualifiedIdType()) {
9628 getObjCEncodingForTypeImpl(
9629 getObjCIdType(), S,
9630 Options.keepingOnly(ObjCEncOptions()
9631 .setExpandPointedToStructures()
9632 .setExpandStructures()),
9633 FD);
9634 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9635 // Note that we do extended encoding of protocol qualifier list
9636 // Only when doing ivar or property encoding.
9637 S += '"';
9638 for (const auto *I : OPT->quals()) {
9639 S += '<';
9640 S += I->getObjCRuntimeNameAsString();
9641 S += '>';
9642 }
9643 S += '"';
9644 }
9645 return;
9646 }
9647
9648 S += '@';
9649 if (OPT->getInterfaceDecl() &&
9650 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9651 S += '"';
9652 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9653 for (const auto *I : OPT->quals()) {
9654 S += '<';
9655 S += I->getObjCRuntimeNameAsString();
9656 S += '>';
9657 }
9658 S += '"';
9659 }
9660 return;
9661 }
9662
9663 // gcc just blithely ignores member pointers.
9664 // FIXME: we should do better than that. 'M' is available.
9665 case Type::MemberPointer:
9666 // This matches gcc's encoding, even though technically it is insufficient.
9667 //FIXME. We should do a better job than gcc.
9668 case Type::Vector:
9669 case Type::ExtVector:
9670 // Until we have a coherent encoding of these three types, issue warning.
9671 if (NotEncodedT)
9672 *NotEncodedT = T;
9673 return;
9674
9675 case Type::ConstantMatrix:
9676 if (NotEncodedT)
9677 *NotEncodedT = T;
9678 return;
9679
9680 case Type::BitInt:
9681 if (NotEncodedT)
9682 *NotEncodedT = T;
9683 return;
9684
9685 // We could see an undeduced auto type here during error recovery.
9686 // Just ignore it.
9687 case Type::Auto:
9688 case Type::DeducedTemplateSpecialization:
9689 return;
9690
9691 case Type::HLSLAttributedResource:
9692 case Type::HLSLInlineSpirv:
9693 case Type::OverflowBehavior:
9694 llvm_unreachable("unexpected type");
9695
9696 case Type::ArrayParameter:
9697 case Type::Pipe:
9698#define ABSTRACT_TYPE(KIND, BASE)
9699#define TYPE(KIND, BASE)
9700#define DEPENDENT_TYPE(KIND, BASE) \
9701 case Type::KIND:
9702#define NON_CANONICAL_TYPE(KIND, BASE) \
9703 case Type::KIND:
9704#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9705 case Type::KIND:
9706#include "clang/AST/TypeNodes.inc"
9707 llvm_unreachable("@encode for dependent type!");
9708 }
9709 llvm_unreachable("bad type kind!");
9710}
9711
9712void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9713 std::string &S,
9714 const FieldDecl *FD,
9715 bool includeVBases,
9716 QualType *NotEncodedT) const {
9717 assert(RDecl && "Expected non-null RecordDecl");
9718 assert(!RDecl->isUnion() && "Should not be called for unions");
9719 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9720 return;
9721
9722 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9723 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9724 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9725
9726 if (CXXRec) {
9727 for (const auto &BI : CXXRec->bases()) {
9728 if (!BI.isVirtual()) {
9729 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9730 if (base->isEmpty())
9731 continue;
9732 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9733 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9734 std::make_pair(offs, base));
9735 }
9736 }
9737 }
9738
9739 for (FieldDecl *Field : RDecl->fields()) {
9740 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9741 continue;
9742 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9743 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9744 std::make_pair(offs, Field));
9745 }
9746
9747 if (CXXRec && includeVBases) {
9748 for (const auto &BI : CXXRec->vbases()) {
9749 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9750 if (base->isEmpty())
9751 continue;
9752 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9753 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9754 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9755 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9756 std::make_pair(offs, base));
9757 }
9758 }
9759
9760 CharUnits size;
9761 if (CXXRec) {
9762 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9763 } else {
9764 size = layout.getSize();
9765 }
9766
9767#ifndef NDEBUG
9768 uint64_t CurOffs = 0;
9769#endif
9770 std::multimap<uint64_t, NamedDecl *>::iterator
9771 CurLayObj = FieldOrBaseOffsets.begin();
9772
9773 if (CXXRec && CXXRec->isDynamicClass() &&
9774 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9775 if (FD) {
9776 S += "\"_vptr$";
9777 std::string recname = CXXRec->getNameAsString();
9778 if (recname.empty()) recname = "?";
9779 S += recname;
9780 S += '"';
9781 }
9782 S += "^^?";
9783#ifndef NDEBUG
9784 CurOffs += getTypeSize(VoidPtrTy);
9785#endif
9786 }
9787
9788 if (!RDecl->hasFlexibleArrayMember()) {
9789 // Mark the end of the structure.
9790 uint64_t offs = toBits(size);
9791 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9792 std::make_pair(offs, nullptr));
9793 }
9794
9795 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9796#ifndef NDEBUG
9797 assert(CurOffs <= CurLayObj->first);
9798 if (CurOffs < CurLayObj->first) {
9799 uint64_t padding = CurLayObj->first - CurOffs;
9800 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9801 // packing/alignment of members is different that normal, in which case
9802 // the encoding will be out-of-sync with the real layout.
9803 // If the runtime switches to just consider the size of types without
9804 // taking into account alignment, we could make padding explicit in the
9805 // encoding (e.g. using arrays of chars). The encoding strings would be
9806 // longer then though.
9807 CurOffs += padding;
9808 }
9809#endif
9810
9811 NamedDecl *dcl = CurLayObj->second;
9812 if (!dcl)
9813 break; // reached end of structure.
9814
9815 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9816 // We expand the bases without their virtual bases since those are going
9817 // in the initial structure. Note that this differs from gcc which
9818 // expands virtual bases each time one is encountered in the hierarchy,
9819 // making the encoding type bigger than it really is.
9820 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9821 NotEncodedT);
9822 assert(!base->isEmpty());
9823#ifndef NDEBUG
9824 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9825#endif
9826 } else {
9827 const auto *field = cast<FieldDecl>(dcl);
9828 if (FD) {
9829 S += '"';
9830 S += field->getNameAsString();
9831 S += '"';
9832 }
9833
9834 if (field->isBitField()) {
9835 EncodeBitField(this, S, field->getType(), field);
9836#ifndef NDEBUG
9837 CurOffs += field->getBitWidthValue();
9838#endif
9839 } else {
9840 QualType qt = field->getType();
9842 getObjCEncodingForTypeImpl(
9843 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9844 FD, NotEncodedT);
9845#ifndef NDEBUG
9846 CurOffs += getTypeSize(field->getType());
9847#endif
9848 }
9849 }
9850 }
9851}
9852
9854 std::string& S) const {
9855 if (QT & Decl::OBJC_TQ_In)
9856 S += 'n';
9857 if (QT & Decl::OBJC_TQ_Inout)
9858 S += 'N';
9859 if (QT & Decl::OBJC_TQ_Out)
9860 S += 'o';
9861 if (QT & Decl::OBJC_TQ_Bycopy)
9862 S += 'O';
9863 if (QT & Decl::OBJC_TQ_Byref)
9864 S += 'R';
9865 if (QT & Decl::OBJC_TQ_Oneway)
9866 S += 'V';
9867}
9868
9870 if (!ObjCIdDecl) {
9873 ObjCIdDecl = buildImplicitTypedef(T, "id");
9874 }
9875 return ObjCIdDecl;
9876}
9877
9879 if (!ObjCSelDecl) {
9881 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9882 }
9883 return ObjCSelDecl;
9884}
9885
9887 if (!ObjCClassDecl) {
9890 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9891 }
9892 return ObjCClassDecl;
9893}
9894
9896 if (!ObjCProtocolClassDecl) {
9897 ObjCProtocolClassDecl
9900 &Idents.get("Protocol"),
9901 /*typeParamList=*/nullptr,
9902 /*PrevDecl=*/nullptr,
9903 SourceLocation(), true);
9904 }
9905
9906 return ObjCProtocolClassDecl;
9907}
9908
9910 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9911 return PointerAuthQualifier();
9913 getLangOpts().PointerAuthObjcInterfaceSelKey,
9914 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9916 /*isIsaPointer=*/false,
9917 /*authenticatesNullValues=*/false);
9918}
9919
9920//===----------------------------------------------------------------------===//
9921// __builtin_va_list Construction Functions
9922//===----------------------------------------------------------------------===//
9923
9925 StringRef Name) {
9926 // typedef char* __builtin[_ms]_va_list;
9927 QualType T = Context->getPointerType(Context->CharTy);
9928 return Context->buildImplicitTypedef(T, Name);
9929}
9930
9932 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9933}
9934
9936 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9937}
9938
9940 // typedef void* __builtin_va_list;
9941 QualType T = Context->getPointerType(Context->VoidTy);
9942 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9943}
9944
9945static TypedefDecl *
9947 // struct __va_list
9948 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9949 if (Context->getLangOpts().CPlusPlus) {
9950 // namespace std { struct __va_list {
9951 auto *NS = NamespaceDecl::Create(
9952 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9953 /*Inline=*/false, SourceLocation(), SourceLocation(),
9954 &Context->Idents.get("std"),
9955 /*PrevDecl=*/nullptr, /*Nested=*/false);
9956 NS->setImplicit();
9958 }
9959
9960 VaListTagDecl->startDefinition();
9961
9962 const size_t NumFields = 5;
9963 QualType FieldTypes[NumFields];
9964 const char *FieldNames[NumFields];
9965
9966 // void *__stack;
9967 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9968 FieldNames[0] = "__stack";
9969
9970 // void *__gr_top;
9971 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9972 FieldNames[1] = "__gr_top";
9973
9974 // void *__vr_top;
9975 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9976 FieldNames[2] = "__vr_top";
9977
9978 // int __gr_offs;
9979 FieldTypes[3] = Context->IntTy;
9980 FieldNames[3] = "__gr_offs";
9981
9982 // int __vr_offs;
9983 FieldTypes[4] = Context->IntTy;
9984 FieldNames[4] = "__vr_offs";
9985
9986 // Create fields
9987 for (unsigned i = 0; i < NumFields; ++i) {
9988 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9992 &Context->Idents.get(FieldNames[i]),
9993 FieldTypes[i], /*TInfo=*/nullptr,
9994 /*BitWidth=*/nullptr,
9995 /*Mutable=*/false,
9996 ICIS_NoInit);
9997 Field->setAccess(AS_public);
9998 VaListTagDecl->addDecl(Field);
9999 }
10000 VaListTagDecl->completeDefinition();
10001 Context->VaListTagDecl = VaListTagDecl;
10002 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10003
10004 // } __builtin_va_list;
10005 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10006}
10007
10009 // typedef struct __va_list_tag {
10011
10012 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10013 VaListTagDecl->startDefinition();
10014
10015 const size_t NumFields = 5;
10016 QualType FieldTypes[NumFields];
10017 const char *FieldNames[NumFields];
10018
10019 // unsigned char gpr;
10020 FieldTypes[0] = Context->UnsignedCharTy;
10021 FieldNames[0] = "gpr";
10022
10023 // unsigned char fpr;
10024 FieldTypes[1] = Context->UnsignedCharTy;
10025 FieldNames[1] = "fpr";
10026
10027 // unsigned short reserved;
10028 FieldTypes[2] = Context->UnsignedShortTy;
10029 FieldNames[2] = "reserved";
10030
10031 // void* overflow_arg_area;
10032 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10033 FieldNames[3] = "overflow_arg_area";
10034
10035 // void* reg_save_area;
10036 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10037 FieldNames[4] = "reg_save_area";
10038
10039 // Create fields
10040 for (unsigned i = 0; i < NumFields; ++i) {
10041 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10044 &Context->Idents.get(FieldNames[i]),
10045 FieldTypes[i], /*TInfo=*/nullptr,
10046 /*BitWidth=*/nullptr,
10047 /*Mutable=*/false,
10048 ICIS_NoInit);
10049 Field->setAccess(AS_public);
10050 VaListTagDecl->addDecl(Field);
10051 }
10052 VaListTagDecl->completeDefinition();
10053 Context->VaListTagDecl = VaListTagDecl;
10054 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10055
10056 // } __va_list_tag;
10057 TypedefDecl *VaListTagTypedefDecl =
10058 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10059
10060 QualType VaListTagTypedefType =
10061 Context->getTypedefType(ElaboratedTypeKeyword::None,
10062 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10063
10064 // typedef __va_list_tag __builtin_va_list[1];
10065 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10066 QualType VaListTagArrayType = Context->getConstantArrayType(
10067 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10068 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10069}
10070
10071static TypedefDecl *
10073 // struct __va_list_tag {
10075 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10076 VaListTagDecl->startDefinition();
10077
10078 const size_t NumFields = 4;
10079 QualType FieldTypes[NumFields];
10080 const char *FieldNames[NumFields];
10081
10082 // unsigned gp_offset;
10083 FieldTypes[0] = Context->UnsignedIntTy;
10084 FieldNames[0] = "gp_offset";
10085
10086 // unsigned fp_offset;
10087 FieldTypes[1] = Context->UnsignedIntTy;
10088 FieldNames[1] = "fp_offset";
10089
10090 // void* overflow_arg_area;
10091 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10092 FieldNames[2] = "overflow_arg_area";
10093
10094 // void* reg_save_area;
10095 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10096 FieldNames[3] = "reg_save_area";
10097
10098 // Create fields
10099 for (unsigned i = 0; i < NumFields; ++i) {
10100 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10104 &Context->Idents.get(FieldNames[i]),
10105 FieldTypes[i], /*TInfo=*/nullptr,
10106 /*BitWidth=*/nullptr,
10107 /*Mutable=*/false,
10108 ICIS_NoInit);
10109 Field->setAccess(AS_public);
10110 VaListTagDecl->addDecl(Field);
10111 }
10112 VaListTagDecl->completeDefinition();
10113 Context->VaListTagDecl = VaListTagDecl;
10114 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10115
10116 // };
10117
10118 // typedef struct __va_list_tag __builtin_va_list[1];
10119 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10120 QualType VaListTagArrayType = Context->getConstantArrayType(
10121 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10122 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10123}
10124
10125static TypedefDecl *
10127 // struct __va_list
10128 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10129 if (Context->getLangOpts().CPlusPlus) {
10130 // namespace std { struct __va_list {
10131 NamespaceDecl *NS;
10132 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10133 Context->getTranslationUnitDecl(),
10134 /*Inline=*/false, SourceLocation(),
10135 SourceLocation(), &Context->Idents.get("std"),
10136 /*PrevDecl=*/nullptr, /*Nested=*/false);
10137 NS->setImplicit();
10138 VaListDecl->setDeclContext(NS);
10139 }
10140
10141 VaListDecl->startDefinition();
10142
10143 // void * __ap;
10144 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10145 VaListDecl,
10148 &Context->Idents.get("__ap"),
10149 Context->getPointerType(Context->VoidTy),
10150 /*TInfo=*/nullptr,
10151 /*BitWidth=*/nullptr,
10152 /*Mutable=*/false,
10153 ICIS_NoInit);
10154 Field->setAccess(AS_public);
10155 VaListDecl->addDecl(Field);
10156
10157 // };
10158 VaListDecl->completeDefinition();
10159 Context->VaListTagDecl = VaListDecl;
10160
10161 // typedef struct __va_list __builtin_va_list;
10162 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10163 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10164}
10165
10166static TypedefDecl *
10168 // struct __va_list_tag {
10170 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10171 VaListTagDecl->startDefinition();
10172
10173 const size_t NumFields = 4;
10174 QualType FieldTypes[NumFields];
10175 const char *FieldNames[NumFields];
10176
10177 // long __gpr;
10178 FieldTypes[0] = Context->LongTy;
10179 FieldNames[0] = "__gpr";
10180
10181 // long __fpr;
10182 FieldTypes[1] = Context->LongTy;
10183 FieldNames[1] = "__fpr";
10184
10185 // void *__overflow_arg_area;
10186 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10187 FieldNames[2] = "__overflow_arg_area";
10188
10189 // void *__reg_save_area;
10190 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10191 FieldNames[3] = "__reg_save_area";
10192
10193 // Create fields
10194 for (unsigned i = 0; i < NumFields; ++i) {
10195 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10199 &Context->Idents.get(FieldNames[i]),
10200 FieldTypes[i], /*TInfo=*/nullptr,
10201 /*BitWidth=*/nullptr,
10202 /*Mutable=*/false,
10203 ICIS_NoInit);
10204 Field->setAccess(AS_public);
10205 VaListTagDecl->addDecl(Field);
10206 }
10207 VaListTagDecl->completeDefinition();
10208 Context->VaListTagDecl = VaListTagDecl;
10209 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10210
10211 // };
10212
10213 // typedef __va_list_tag __builtin_va_list[1];
10214 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10215 QualType VaListTagArrayType = Context->getConstantArrayType(
10216 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10217
10218 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10219}
10220
10222 // typedef struct __va_list_tag {
10224 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10225 VaListTagDecl->startDefinition();
10226
10227 const size_t NumFields = 3;
10228 QualType FieldTypes[NumFields];
10229 const char *FieldNames[NumFields];
10230
10231 // void *CurrentSavedRegisterArea;
10232 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10233 FieldNames[0] = "__current_saved_reg_area_pointer";
10234
10235 // void *SavedRegAreaEnd;
10236 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10237 FieldNames[1] = "__saved_reg_area_end_pointer";
10238
10239 // void *OverflowArea;
10240 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10241 FieldNames[2] = "__overflow_area_pointer";
10242
10243 // Create fields
10244 for (unsigned i = 0; i < NumFields; ++i) {
10246 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10247 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10248 /*TInfo=*/nullptr,
10249 /*BitWidth=*/nullptr,
10250 /*Mutable=*/false, ICIS_NoInit);
10251 Field->setAccess(AS_public);
10252 VaListTagDecl->addDecl(Field);
10253 }
10254 VaListTagDecl->completeDefinition();
10255 Context->VaListTagDecl = VaListTagDecl;
10256 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10257
10258 // } __va_list_tag;
10259 TypedefDecl *VaListTagTypedefDecl =
10260 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10261
10262 QualType VaListTagTypedefType =
10263 Context->getTypedefType(ElaboratedTypeKeyword::None,
10264 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10265
10266 // typedef __va_list_tag __builtin_va_list[1];
10267 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10268 QualType VaListTagArrayType = Context->getConstantArrayType(
10269 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10270
10271 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10272}
10273
10274static TypedefDecl *
10276 // typedef struct __va_list_tag {
10277 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10278
10279 VaListTagDecl->startDefinition();
10280
10281 // int* __va_stk;
10282 // int* __va_reg;
10283 // int __va_ndx;
10284 constexpr size_t NumFields = 3;
10285 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10286 Context->getPointerType(Context->IntTy),
10287 Context->IntTy};
10288 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10289
10290 // Create fields
10291 for (unsigned i = 0; i < NumFields; ++i) {
10294 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10295 /*BitWidth=*/nullptr,
10296 /*Mutable=*/false, ICIS_NoInit);
10297 Field->setAccess(AS_public);
10298 VaListTagDecl->addDecl(Field);
10299 }
10300 VaListTagDecl->completeDefinition();
10301 Context->VaListTagDecl = VaListTagDecl;
10302 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10303
10304 // } __va_list_tag;
10305 TypedefDecl *VaListTagTypedefDecl =
10306 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10307
10308 return VaListTagTypedefDecl;
10309}
10310
10313 switch (Kind) {
10315 return CreateCharPtrBuiltinVaListDecl(Context);
10317 return CreateVoidPtrBuiltinVaListDecl(Context);
10319 return CreateAArch64ABIBuiltinVaListDecl(Context);
10321 return CreatePowerABIBuiltinVaListDecl(Context);
10323 return CreateX86_64ABIBuiltinVaListDecl(Context);
10325 return CreateAAPCSABIBuiltinVaListDecl(Context);
10327 return CreateSystemZBuiltinVaListDecl(Context);
10329 return CreateHexagonBuiltinVaListDecl(Context);
10331 return CreateXtensaABIBuiltinVaListDecl(Context);
10332 }
10333
10334 llvm_unreachable("Unhandled __builtin_va_list type kind");
10335}
10336
10338 if (!BuiltinVaListDecl) {
10339 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10340 assert(BuiltinVaListDecl->isImplicit());
10341 }
10342
10343 return BuiltinVaListDecl;
10344}
10345
10347 // Force the creation of VaListTagDecl by building the __builtin_va_list
10348 // declaration.
10349 if (!VaListTagDecl)
10350 (void)getBuiltinVaListDecl();
10351
10352 return VaListTagDecl;
10353}
10354
10356 if (!BuiltinMSVaListDecl)
10357 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10358
10359 return BuiltinMSVaListDecl;
10360}
10361
10363 // Allow redecl custom type checking builtin for HLSL.
10364 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10365 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10366 return true;
10367 // Allow redecl custom type checking builtin for SPIR-V.
10368 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10369 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10370 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10371 return true;
10372 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10373}
10374
10376 assert(ObjCConstantStringType.isNull() &&
10377 "'NSConstantString' type already set!");
10378
10379 ObjCConstantStringType = getObjCInterfaceType(Decl);
10380}
10381
10382/// Retrieve the template name that corresponds to a non-empty
10383/// lookup.
10386 UnresolvedSetIterator End) const {
10387 unsigned size = End - Begin;
10388 assert(size > 1 && "set is not overloaded!");
10389
10390 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10391 size * sizeof(FunctionTemplateDecl*));
10392 auto *OT = new (memory) OverloadedTemplateStorage(size);
10393
10394 NamedDecl **Storage = OT->getStorage();
10395 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10396 NamedDecl *D = *I;
10397 assert(isa<FunctionTemplateDecl>(D) ||
10401 *Storage++ = D;
10402 }
10403
10404 return TemplateName(OT);
10405}
10406
10407/// Retrieve a template name representing an unqualified-id that has been
10408/// assumed to name a template for ADL purposes.
10410 auto *OT = new (*this) AssumedTemplateStorage(Name);
10411 return TemplateName(OT);
10412}
10413
10414/// Retrieve the template name that represents a qualified
10415/// template name such as \c std::vector.
10417 bool TemplateKeyword,
10418 TemplateName Template) const {
10419 assert(Template.getKind() == TemplateName::Template ||
10421
10422 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10423 assert(!Qualifier && "unexpected qualified template template parameter");
10424 assert(TemplateKeyword == false);
10425 return Template;
10426 }
10427
10428 // FIXME: Canonicalization?
10429 llvm::FoldingSetNodeID ID;
10430 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10431
10432 void *InsertPos = nullptr;
10434 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10435 if (!QTN) {
10436 QTN = new (*this, alignof(QualifiedTemplateName))
10437 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10438 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10439 }
10440
10441 return TemplateName(QTN);
10442}
10443
10444/// Retrieve the template name that represents a dependent
10445/// template name such as \c MetaFun::template operator+.
10448 llvm::FoldingSetNodeID ID;
10449 S.Profile(ID);
10450
10451 void *InsertPos = nullptr;
10452 if (DependentTemplateName *QTN =
10453 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10454 return TemplateName(QTN);
10455
10457 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10458 DependentTemplateNames.InsertNode(QTN, InsertPos);
10459 return TemplateName(QTN);
10460}
10461
10463 Decl *AssociatedDecl,
10464 unsigned Index,
10465 UnsignedOrNone PackIndex,
10466 bool Final) const {
10467 llvm::FoldingSetNodeID ID;
10468 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10469 Index, PackIndex, Final);
10470
10471 void *insertPos = nullptr;
10473 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10474
10475 if (!subst) {
10476 subst = new (*this) SubstTemplateTemplateParmStorage(
10477 Replacement, AssociatedDecl, Index, PackIndex, Final);
10478 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10479 }
10480
10481 return TemplateName(subst);
10482}
10483
10486 Decl *AssociatedDecl,
10487 unsigned Index, bool Final) const {
10488 auto &Self = const_cast<ASTContext &>(*this);
10489 llvm::FoldingSetNodeID ID;
10491 AssociatedDecl, Index, Final);
10492
10493 void *InsertPos = nullptr;
10495 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10496
10497 if (!Subst) {
10498 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10499 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10500 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10501 }
10502
10503 return TemplateName(Subst);
10504}
10505
10506/// Retrieve the template name that represents a template name
10507/// deduced from a specialization.
10510 DefaultArguments DefaultArgs) const {
10511 if (!DefaultArgs)
10512 return Underlying;
10513
10514 llvm::FoldingSetNodeID ID;
10515 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10516
10517 void *InsertPos = nullptr;
10519 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10520 if (!DTS) {
10521 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10522 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10523 alignof(DeducedTemplateStorage));
10524 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10525 DeducedTemplates.InsertNode(DTS, InsertPos);
10526 }
10527 return TemplateName(DTS);
10528}
10529
10530/// getFromTargetType - Given one of the integer types provided by
10531/// TargetInfo, produce the corresponding type. The unsigned @p Type
10532/// is actually a value of type @c TargetInfo::IntType.
10533CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10534 switch (Type) {
10535 case TargetInfo::NoInt: return {};
10538 case TargetInfo::SignedShort: return ShortTy;
10540 case TargetInfo::SignedInt: return IntTy;
10542 case TargetInfo::SignedLong: return LongTy;
10546 }
10547
10548 llvm_unreachable("Unhandled TargetInfo::IntType value");
10549}
10550
10551//===----------------------------------------------------------------------===//
10552// Type Predicates.
10553//===----------------------------------------------------------------------===//
10554
10555/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10556/// garbage collection attribute.
10557///
10559 if (getLangOpts().getGC() == LangOptions::NonGC)
10560 return Qualifiers::GCNone;
10561
10562 assert(getLangOpts().ObjC);
10563 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10564
10565 // Default behaviour under objective-C's gc is for ObjC pointers
10566 // (or pointers to them) be treated as though they were declared
10567 // as __strong.
10568 if (GCAttrs == Qualifiers::GCNone) {
10570 return Qualifiers::Strong;
10571 else if (Ty->isPointerType())
10573 } else {
10574 // It's not valid to set GC attributes on anything that isn't a
10575 // pointer.
10576#ifndef NDEBUG
10578 while (const auto *AT = dyn_cast<ArrayType>(CT))
10579 CT = AT->getElementType();
10580 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10581#endif
10582 }
10583 return GCAttrs;
10584}
10585
10586//===----------------------------------------------------------------------===//
10587// Type Compatibility Testing
10588//===----------------------------------------------------------------------===//
10589
10590/// areCompatVectorTypes - Return true if the two specified vector types are
10591/// compatible.
10592static bool areCompatVectorTypes(const VectorType *LHS,
10593 const VectorType *RHS) {
10594 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10595 return LHS->getElementType() == RHS->getElementType() &&
10596 LHS->getNumElements() == RHS->getNumElements();
10597}
10598
10599/// areCompatMatrixTypes - Return true if the two specified matrix types are
10600/// compatible.
10602 const ConstantMatrixType *RHS) {
10603 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10604 return LHS->getElementType() == RHS->getElementType() &&
10605 LHS->getNumRows() == RHS->getNumRows() &&
10606 LHS->getNumColumns() == RHS->getNumColumns();
10607}
10608
10610 QualType SecondVec) {
10611 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10612 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10613
10614 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10615 return true;
10616
10617 // Treat Neon vector types and most AltiVec vector types as if they are the
10618 // equivalent GCC vector types.
10619 const auto *First = FirstVec->castAs<VectorType>();
10620 const auto *Second = SecondVec->castAs<VectorType>();
10621 if (First->getNumElements() == Second->getNumElements() &&
10622 hasSameType(First->getElementType(), Second->getElementType()) &&
10623 First->getVectorKind() != VectorKind::AltiVecPixel &&
10624 First->getVectorKind() != VectorKind::AltiVecBool &&
10627 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10628 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10631 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10633 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10635 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10637 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10639 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10641 return true;
10642
10643 // In OpenCL, treat half and _Float16 vector types as compatible.
10644 if (getLangOpts().OpenCL &&
10645 First->getNumElements() == Second->getNumElements()) {
10646 QualType FirstElt = First->getElementType();
10647 QualType SecondElt = Second->getElementType();
10648
10649 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10650 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10651 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10652 First->getVectorKind() != VectorKind::AltiVecBool &&
10655 return true;
10656 }
10657 }
10658 return false;
10659}
10660
10666
10669 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10670 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10671
10672 if (!LHSOBT && !RHSOBT)
10674
10675 if (LHSOBT && RHSOBT) {
10676 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10679 }
10680
10681 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10682 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10683
10684 if (RHSOBT && !LHSOBT) {
10685 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10687 }
10688
10690}
10691
10692/// getRVVTypeSize - Return RVV vector register size.
10693static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10694 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10695 auto VScale = Context.getTargetInfo().getVScaleRange(
10696 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10697 if (!VScale)
10698 return 0;
10699
10700 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10701
10702 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10703 if (Info.ElementType == Context.BoolTy)
10704 EltSize = 1;
10705
10706 uint64_t MinElts = Info.EC.getKnownMinValue();
10707 return VScale->first * MinElts * EltSize;
10708}
10709
10711 QualType SecondType) {
10712 assert(
10713 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10714 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10715 "Expected RVV builtin type and vector type!");
10716
10717 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10718 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10719 if (const auto *VT = SecondType->getAs<VectorType>()) {
10720 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10722 return FirstType->isRVVVLSBuiltinType() &&
10723 Info.ElementType == BoolTy &&
10724 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10725 }
10726 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10728 return FirstType->isRVVVLSBuiltinType() &&
10729 Info.ElementType == BoolTy &&
10730 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10731 }
10732 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10734 return FirstType->isRVVVLSBuiltinType() &&
10735 Info.ElementType == BoolTy &&
10736 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10737 }
10738 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10740 return FirstType->isRVVVLSBuiltinType() &&
10741 Info.ElementType == BoolTy &&
10742 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10743 }
10744 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10745 VT->getVectorKind() == VectorKind::Generic)
10746 return FirstType->isRVVVLSBuiltinType() &&
10747 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10748 hasSameType(VT->getElementType(),
10749 getBuiltinVectorTypeInfo(BT).ElementType);
10750 }
10751 }
10752 return false;
10753 };
10754
10755 return IsValidCast(FirstType, SecondType) ||
10756 IsValidCast(SecondType, FirstType);
10757}
10758
10760 QualType SecondType) {
10761 assert(
10762 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10763 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10764 "Expected RVV builtin type and vector type!");
10765
10766 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10767 const auto *BT = FirstType->getAs<BuiltinType>();
10768 if (!BT)
10769 return false;
10770
10771 if (!BT->isRVVVLSBuiltinType())
10772 return false;
10773
10774 const auto *VecTy = SecondType->getAs<VectorType>();
10775 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10777 getLangOpts().getLaxVectorConversions();
10778
10779 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10780 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10781 return false;
10782
10783 // If -flax-vector-conversions=all is specified, the types are
10784 // certainly compatible.
10786 return true;
10787
10788 // If -flax-vector-conversions=integer is specified, the types are
10789 // compatible if the elements are integer types.
10791 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10792 FirstType->getRVVEltType(*this)->isIntegerType();
10793 }
10794
10795 return false;
10796 };
10797
10798 return IsLaxCompatible(FirstType, SecondType) ||
10799 IsLaxCompatible(SecondType, FirstType);
10800}
10801
10803 while (true) {
10804 // __strong id
10805 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10806 if (Attr->getAttrKind() == attr::ObjCOwnership)
10807 return true;
10808
10809 Ty = Attr->getModifiedType();
10810
10811 // X *__strong (...)
10812 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10813 Ty = Paren->getInnerType();
10814
10815 // We do not want to look through typedefs, typeof(expr),
10816 // typeof(type), or any other way that the type is somehow
10817 // abstracted.
10818 } else {
10819 return false;
10820 }
10821 }
10822}
10823
10824//===----------------------------------------------------------------------===//
10825// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10826//===----------------------------------------------------------------------===//
10827
10828/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10829/// inheritance hierarchy of 'rProto'.
10830bool
10832 ObjCProtocolDecl *rProto) const {
10833 if (declaresSameEntity(lProto, rProto))
10834 return true;
10835 for (auto *PI : rProto->protocols())
10836 if (ProtocolCompatibleWithProtocol(lProto, PI))
10837 return true;
10838 return false;
10839}
10840
10841/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10842/// Class<pr1, ...>.
10844 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10845 for (auto *lhsProto : lhs->quals()) {
10846 bool match = false;
10847 for (auto *rhsProto : rhs->quals()) {
10848 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10849 match = true;
10850 break;
10851 }
10852 }
10853 if (!match)
10854 return false;
10855 }
10856 return true;
10857}
10858
10859/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10860/// ObjCQualifiedIDType.
10862 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10863 bool compare) {
10864 // Allow id<P..> and an 'id' in all cases.
10865 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10866 return true;
10867
10868 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10869 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10871 return false;
10872
10873 if (lhs->isObjCQualifiedIdType()) {
10874 if (rhs->qual_empty()) {
10875 // If the RHS is a unqualified interface pointer "NSString*",
10876 // make sure we check the class hierarchy.
10877 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10878 for (auto *I : lhs->quals()) {
10879 // when comparing an id<P> on lhs with a static type on rhs,
10880 // see if static class implements all of id's protocols, directly or
10881 // through its super class and categories.
10882 if (!rhsID->ClassImplementsProtocol(I, true))
10883 return false;
10884 }
10885 }
10886 // If there are no qualifiers and no interface, we have an 'id'.
10887 return true;
10888 }
10889 // Both the right and left sides have qualifiers.
10890 for (auto *lhsProto : lhs->quals()) {
10891 bool match = false;
10892
10893 // when comparing an id<P> on lhs with a static type on rhs,
10894 // see if static class implements all of id's protocols, directly or
10895 // through its super class and categories.
10896 for (auto *rhsProto : rhs->quals()) {
10897 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10898 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10899 match = true;
10900 break;
10901 }
10902 }
10903 // If the RHS is a qualified interface pointer "NSString<P>*",
10904 // make sure we check the class hierarchy.
10905 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10906 for (auto *I : lhs->quals()) {
10907 // when comparing an id<P> on lhs with a static type on rhs,
10908 // see if static class implements all of id's protocols, directly or
10909 // through its super class and categories.
10910 if (rhsID->ClassImplementsProtocol(I, true)) {
10911 match = true;
10912 break;
10913 }
10914 }
10915 }
10916 if (!match)
10917 return false;
10918 }
10919
10920 return true;
10921 }
10922
10923 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10924
10925 if (lhs->getInterfaceType()) {
10926 // If both the right and left sides have qualifiers.
10927 for (auto *lhsProto : lhs->quals()) {
10928 bool match = false;
10929
10930 // when comparing an id<P> on rhs with a static type on lhs,
10931 // see if static class implements all of id's protocols, directly or
10932 // through its super class and categories.
10933 // First, lhs protocols in the qualifier list must be found, direct
10934 // or indirect in rhs's qualifier list or it is a mismatch.
10935 for (auto *rhsProto : rhs->quals()) {
10936 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10937 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10938 match = true;
10939 break;
10940 }
10941 }
10942 if (!match)
10943 return false;
10944 }
10945
10946 // Static class's protocols, or its super class or category protocols
10947 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10948 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10949 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10950 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10951 // This is rather dubious but matches gcc's behavior. If lhs has
10952 // no type qualifier and its class has no static protocol(s)
10953 // assume that it is mismatch.
10954 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10955 return false;
10956 for (auto *lhsProto : LHSInheritedProtocols) {
10957 bool match = false;
10958 for (auto *rhsProto : rhs->quals()) {
10959 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10960 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10961 match = true;
10962 break;
10963 }
10964 }
10965 if (!match)
10966 return false;
10967 }
10968 }
10969 return true;
10970 }
10971 return false;
10972}
10973
10974/// canAssignObjCInterfaces - Return true if the two interface types are
10975/// compatible for assignment from RHS to LHS. This handles validation of any
10976/// protocol qualifiers on the LHS or RHS.
10978 const ObjCObjectPointerType *RHSOPT) {
10979 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10980 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10981
10982 // If either type represents the built-in 'id' type, return true.
10983 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10984 return true;
10985
10986 // Function object that propagates a successful result or handles
10987 // __kindof types.
10988 auto finish = [&](bool succeeded) -> bool {
10989 if (succeeded)
10990 return true;
10991
10992 if (!RHS->isKindOfType())
10993 return false;
10994
10995 // Strip off __kindof and protocol qualifiers, then check whether
10996 // we can assign the other way.
10998 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10999 };
11000
11001 // Casts from or to id<P> are allowed when the other side has compatible
11002 // protocols.
11003 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11004 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11005 }
11006
11007 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11008 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11009 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11010 }
11011
11012 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11013 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11014 return true;
11015 }
11016
11017 // If we have 2 user-defined types, fall into that path.
11018 if (LHS->getInterface() && RHS->getInterface()) {
11019 return finish(canAssignObjCInterfaces(LHS, RHS));
11020 }
11021
11022 return false;
11023}
11024
11025/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11026/// for providing type-safety for objective-c pointers used to pass/return
11027/// arguments in block literals. When passed as arguments, passing 'A*' where
11028/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11029/// not OK. For the return type, the opposite is not OK.
11031 const ObjCObjectPointerType *LHSOPT,
11032 const ObjCObjectPointerType *RHSOPT,
11033 bool BlockReturnType) {
11034
11035 // Function object that propagates a successful result or handles
11036 // __kindof types.
11037 auto finish = [&](bool succeeded) -> bool {
11038 if (succeeded)
11039 return true;
11040
11041 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11042 if (!Expected->isKindOfType())
11043 return false;
11044
11045 // Strip off __kindof and protocol qualifiers, then check whether
11046 // we can assign the other way.
11048 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11049 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11050 BlockReturnType);
11051 };
11052
11053 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11054 return true;
11055
11056 if (LHSOPT->isObjCBuiltinType()) {
11057 return finish(RHSOPT->isObjCBuiltinType() ||
11058 RHSOPT->isObjCQualifiedIdType());
11059 }
11060
11061 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11062 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11063 // Use for block parameters previous type checking for compatibility.
11064 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11065 // Or corrected type checking as in non-compat mode.
11066 (!BlockReturnType &&
11067 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11068 else
11070 (BlockReturnType ? LHSOPT : RHSOPT),
11071 (BlockReturnType ? RHSOPT : LHSOPT), false));
11072 }
11073
11074 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11075 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11076 if (LHS && RHS) { // We have 2 user-defined types.
11077 if (LHS != RHS) {
11078 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11079 return finish(BlockReturnType);
11080 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11081 return finish(!BlockReturnType);
11082 }
11083 else
11084 return true;
11085 }
11086 return false;
11087}
11088
11089/// Comparison routine for Objective-C protocols to be used with
11090/// llvm::array_pod_sort.
11092 ObjCProtocolDecl * const *rhs) {
11093 return (*lhs)->getName().compare((*rhs)->getName());
11094}
11095
11096/// getIntersectionOfProtocols - This routine finds the intersection of set
11097/// of protocols inherited from two distinct objective-c pointer objects with
11098/// the given common base.
11099/// It is used to build composite qualifier list of the composite type of
11100/// the conditional expression involving two objective-c pointer objects.
11101static
11103 const ObjCInterfaceDecl *CommonBase,
11104 const ObjCObjectPointerType *LHSOPT,
11105 const ObjCObjectPointerType *RHSOPT,
11106 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11107
11108 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11109 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11110 assert(LHS->getInterface() && "LHS must have an interface base");
11111 assert(RHS->getInterface() && "RHS must have an interface base");
11112
11113 // Add all of the protocols for the LHS.
11115
11116 // Start with the protocol qualifiers.
11117 for (auto *proto : LHS->quals()) {
11118 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11119 }
11120
11121 // Also add the protocols associated with the LHS interface.
11122 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11123
11124 // Add all of the protocols for the RHS.
11126
11127 // Start with the protocol qualifiers.
11128 for (auto *proto : RHS->quals()) {
11129 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11130 }
11131
11132 // Also add the protocols associated with the RHS interface.
11133 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11134
11135 // Compute the intersection of the collected protocol sets.
11136 for (auto *proto : LHSProtocolSet) {
11137 if (RHSProtocolSet.count(proto))
11138 IntersectionSet.push_back(proto);
11139 }
11140
11141 // Compute the set of protocols that is implied by either the common type or
11142 // the protocols within the intersection.
11144 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11145
11146 // Remove any implied protocols from the list of inherited protocols.
11147 if (!ImpliedProtocols.empty()) {
11148 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11149 return ImpliedProtocols.contains(proto);
11150 });
11151 }
11152
11153 // Sort the remaining protocols by name.
11154 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11156}
11157
11158/// Determine whether the first type is a subtype of the second.
11160 QualType rhs) {
11161 // Common case: two object pointers.
11162 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11163 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11164 if (lhsOPT && rhsOPT)
11165 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11166
11167 // Two block pointers.
11168 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11169 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11170 if (lhsBlock && rhsBlock)
11171 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11172
11173 // If either is an unqualified 'id' and the other is a block, it's
11174 // acceptable.
11175 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11176 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11177 return true;
11178
11179 return false;
11180}
11181
11182// Check that the given Objective-C type argument lists are equivalent.
11184 const ObjCInterfaceDecl *iface,
11185 ArrayRef<QualType> lhsArgs,
11186 ArrayRef<QualType> rhsArgs,
11187 bool stripKindOf) {
11188 if (lhsArgs.size() != rhsArgs.size())
11189 return false;
11190
11191 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11192 if (!typeParams)
11193 return false;
11194
11195 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11196 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11197 continue;
11198
11199 switch (typeParams->begin()[i]->getVariance()) {
11201 if (!stripKindOf ||
11202 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11203 rhsArgs[i].stripObjCKindOfType(ctx))) {
11204 return false;
11205 }
11206 break;
11207
11209 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11210 return false;
11211 break;
11212
11214 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11215 return false;
11216 break;
11217 }
11218 }
11219
11220 return true;
11221}
11222
11224 const ObjCObjectPointerType *Lptr,
11225 const ObjCObjectPointerType *Rptr) {
11226 const ObjCObjectType *LHS = Lptr->getObjectType();
11227 const ObjCObjectType *RHS = Rptr->getObjectType();
11228 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11229 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11230
11231 if (!LDecl || !RDecl)
11232 return {};
11233
11234 // When either LHS or RHS is a kindof type, we should return a kindof type.
11235 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11236 // kindof(A).
11237 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11238
11239 // Follow the left-hand side up the class hierarchy until we either hit a
11240 // root or find the RHS. Record the ancestors in case we don't find it.
11241 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11242 LHSAncestors;
11243 while (true) {
11244 // Record this ancestor. We'll need this if the common type isn't in the
11245 // path from the LHS to the root.
11246 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11247
11248 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11249 // Get the type arguments.
11250 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11251 bool anyChanges = false;
11252 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11253 // Both have type arguments, compare them.
11254 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11255 LHS->getTypeArgs(), RHS->getTypeArgs(),
11256 /*stripKindOf=*/true))
11257 return {};
11258 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11259 // If only one has type arguments, the result will not have type
11260 // arguments.
11261 LHSTypeArgs = {};
11262 anyChanges = true;
11263 }
11264
11265 // Compute the intersection of protocols.
11267 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11268 Protocols);
11269 if (!Protocols.empty())
11270 anyChanges = true;
11271
11272 // If anything in the LHS will have changed, build a new result type.
11273 // If we need to return a kindof type but LHS is not a kindof type, we
11274 // build a new result type.
11275 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11276 QualType Result = getObjCInterfaceType(LHS->getInterface());
11277 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11278 anyKindOf || LHS->isKindOfType());
11280 }
11281
11282 return getObjCObjectPointerType(QualType(LHS, 0));
11283 }
11284
11285 // Find the superclass.
11286 QualType LHSSuperType = LHS->getSuperClassType();
11287 if (LHSSuperType.isNull())
11288 break;
11289
11290 LHS = LHSSuperType->castAs<ObjCObjectType>();
11291 }
11292
11293 // We didn't find anything by following the LHS to its root; now check
11294 // the RHS against the cached set of ancestors.
11295 while (true) {
11296 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11297 if (KnownLHS != LHSAncestors.end()) {
11298 LHS = KnownLHS->second;
11299
11300 // Get the type arguments.
11301 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11302 bool anyChanges = false;
11303 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11304 // Both have type arguments, compare them.
11305 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11306 LHS->getTypeArgs(), RHS->getTypeArgs(),
11307 /*stripKindOf=*/true))
11308 return {};
11309 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11310 // If only one has type arguments, the result will not have type
11311 // arguments.
11312 RHSTypeArgs = {};
11313 anyChanges = true;
11314 }
11315
11316 // Compute the intersection of protocols.
11318 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11319 Protocols);
11320 if (!Protocols.empty())
11321 anyChanges = true;
11322
11323 // If we need to return a kindof type but RHS is not a kindof type, we
11324 // build a new result type.
11325 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11326 QualType Result = getObjCInterfaceType(RHS->getInterface());
11327 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11328 anyKindOf || RHS->isKindOfType());
11330 }
11331
11332 return getObjCObjectPointerType(QualType(RHS, 0));
11333 }
11334
11335 // Find the superclass of the RHS.
11336 QualType RHSSuperType = RHS->getSuperClassType();
11337 if (RHSSuperType.isNull())
11338 break;
11339
11340 RHS = RHSSuperType->castAs<ObjCObjectType>();
11341 }
11342
11343 return {};
11344}
11345
11347 const ObjCObjectType *RHS) {
11348 assert(LHS->getInterface() && "LHS is not an interface type");
11349 assert(RHS->getInterface() && "RHS is not an interface type");
11350
11351 // Verify that the base decls are compatible: the RHS must be a subclass of
11352 // the LHS.
11353 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11354 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11355 if (!IsSuperClass)
11356 return false;
11357
11358 // If the LHS has protocol qualifiers, determine whether all of them are
11359 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11360 // LHS).
11361 if (LHS->getNumProtocols() > 0) {
11362 // OK if conversion of LHS to SuperClass results in narrowing of types
11363 // ; i.e., SuperClass may implement at least one of the protocols
11364 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11365 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11366 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11367 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11368 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11369 // qualifiers.
11370 for (auto *RHSPI : RHS->quals())
11371 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11372 // If there is no protocols associated with RHS, it is not a match.
11373 if (SuperClassInheritedProtocols.empty())
11374 return false;
11375
11376 for (const auto *LHSProto : LHS->quals()) {
11377 bool SuperImplementsProtocol = false;
11378 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11379 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11380 SuperImplementsProtocol = true;
11381 break;
11382 }
11383 if (!SuperImplementsProtocol)
11384 return false;
11385 }
11386 }
11387
11388 // If the LHS is specialized, we may need to check type arguments.
11389 if (LHS->isSpecialized()) {
11390 // Follow the superclass chain until we've matched the LHS class in the
11391 // hierarchy. This substitutes type arguments through.
11392 const ObjCObjectType *RHSSuper = RHS;
11393 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11394 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11395
11396 // If the RHS is specializd, compare type arguments.
11397 if (RHSSuper->isSpecialized() &&
11398 !sameObjCTypeArgs(*this, LHS->getInterface(),
11399 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11400 /*stripKindOf=*/true)) {
11401 return false;
11402 }
11403 }
11404
11405 return true;
11406}
11407
11409 // get the "pointed to" types
11410 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11411 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11412
11413 if (!LHSOPT || !RHSOPT)
11414 return false;
11415
11416 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11417 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11418}
11419
11422 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11423 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11424}
11425
11426/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11427/// both shall have the identically qualified version of a compatible type.
11428/// C99 6.2.7p1: Two types have compatible types if their types are the
11429/// same. See 6.7.[2,3,5] for additional rules.
11431 bool CompareUnqualified) {
11432 if (getLangOpts().CPlusPlus)
11433 return hasSameType(LHS, RHS);
11434
11435 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11436}
11437
11439 return typesAreCompatible(LHS, RHS);
11440}
11441
11443 return !mergeTypes(LHS, RHS, true).isNull();
11444}
11445
11446/// mergeTransparentUnionType - if T is a transparent union type and a member
11447/// of T is compatible with SubType, return the merged type, else return
11448/// QualType()
11450 bool OfBlockPointer,
11451 bool Unqualified) {
11452 if (const RecordType *UT = T->getAsUnionType()) {
11453 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11454 if (UD->hasAttr<TransparentUnionAttr>()) {
11455 for (const auto *I : UD->fields()) {
11456 QualType ET = I->getType().getUnqualifiedType();
11457 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11458 if (!MT.isNull())
11459 return MT;
11460 }
11461 }
11462 }
11463
11464 return {};
11465}
11466
11467/// mergeFunctionParameterTypes - merge two types which appear as function
11468/// parameter types
11470 bool OfBlockPointer,
11471 bool Unqualified) {
11472 // GNU extension: two types are compatible if they appear as a function
11473 // argument, one of the types is a transparent union type and the other
11474 // type is compatible with a union member
11475 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11476 Unqualified);
11477 if (!lmerge.isNull())
11478 return lmerge;
11479
11480 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11481 Unqualified);
11482 if (!rmerge.isNull())
11483 return rmerge;
11484
11485 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11486}
11487
11489 bool OfBlockPointer, bool Unqualified,
11490 bool AllowCXX,
11491 bool IsConditionalOperator) {
11492 const auto *lbase = lhs->castAs<FunctionType>();
11493 const auto *rbase = rhs->castAs<FunctionType>();
11494 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11495 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11496 bool allLTypes = true;
11497 bool allRTypes = true;
11498
11499 // Check return type
11500 QualType retType;
11501 if (OfBlockPointer) {
11502 QualType RHS = rbase->getReturnType();
11503 QualType LHS = lbase->getReturnType();
11504 bool UnqualifiedResult = Unqualified;
11505 if (!UnqualifiedResult)
11506 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11507 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11508 }
11509 else
11510 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11511 Unqualified);
11512 if (retType.isNull())
11513 return {};
11514
11515 if (Unqualified)
11516 retType = retType.getUnqualifiedType();
11517
11518 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11519 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11520 if (Unqualified) {
11521 LRetType = LRetType.getUnqualifiedType();
11522 RRetType = RRetType.getUnqualifiedType();
11523 }
11524
11525 if (getCanonicalType(retType) != LRetType)
11526 allLTypes = false;
11527 if (getCanonicalType(retType) != RRetType)
11528 allRTypes = false;
11529
11530 // FIXME: double check this
11531 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11532 // rbase->getRegParmAttr() != 0 &&
11533 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11534 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11535 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11536
11537 // Compatible functions must have compatible calling conventions
11538 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11539 return {};
11540
11541 // Regparm is part of the calling convention.
11542 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11543 return {};
11544 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11545 return {};
11546
11547 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11548 return {};
11549 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11550 return {};
11551 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11552 return {};
11553
11554 // When merging declarations, it's common for supplemental information like
11555 // attributes to only be present in one of the declarations, and we generally
11556 // want type merging to preserve the union of information. So a merged
11557 // function type should be noreturn if it was noreturn in *either* operand
11558 // type.
11559 //
11560 // But for the conditional operator, this is backwards. The result of the
11561 // operator could be either operand, and its type should conservatively
11562 // reflect that. So a function type in a composite type is noreturn only
11563 // if it's noreturn in *both* operand types.
11564 //
11565 // Arguably, noreturn is a kind of subtype, and the conditional operator
11566 // ought to produce the most specific common supertype of its operand types.
11567 // That would differ from this rule in contravariant positions. However,
11568 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11569 // as a practical matter, it would only affect C code that does abstraction of
11570 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11571 // say the least. So we use the simpler rule.
11572 bool NoReturn = IsConditionalOperator
11573 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11574 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11575 if (lbaseInfo.getNoReturn() != NoReturn)
11576 allLTypes = false;
11577 if (rbaseInfo.getNoReturn() != NoReturn)
11578 allRTypes = false;
11579
11580 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11581
11582 std::optional<FunctionEffectSet> MergedFX;
11583
11584 if (lproto && rproto) { // two C99 style function prototypes
11585 assert((AllowCXX ||
11586 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11587 "C++ shouldn't be here");
11588 // Compatible functions must have the same number of parameters
11589 if (lproto->getNumParams() != rproto->getNumParams())
11590 return {};
11591
11592 // Variadic and non-variadic functions aren't compatible
11593 if (lproto->isVariadic() != rproto->isVariadic())
11594 return {};
11595
11596 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11597 return {};
11598
11599 // Function protos with different 'cfi_salt' values aren't compatible.
11600 if (lproto->getExtraAttributeInfo().CFISalt !=
11601 rproto->getExtraAttributeInfo().CFISalt)
11602 return {};
11603
11604 // Function effects are handled similarly to noreturn, see above.
11605 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11606 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11607 if (LHSFX != RHSFX) {
11608 if (IsConditionalOperator)
11609 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11610 else {
11612 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11613 // Here we're discarding a possible error due to conflicts in the effect
11614 // sets. But we're not in a context where we can report it. The
11615 // operation does however guarantee maintenance of invariants.
11616 }
11617 if (*MergedFX != LHSFX)
11618 allLTypes = false;
11619 if (*MergedFX != RHSFX)
11620 allRTypes = false;
11621 }
11622
11624 bool canUseLeft, canUseRight;
11625 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11626 newParamInfos))
11627 return {};
11628
11629 if (!canUseLeft)
11630 allLTypes = false;
11631 if (!canUseRight)
11632 allRTypes = false;
11633
11634 // Check parameter type compatibility
11636 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11637 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11638 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11640 lParamType, rParamType, OfBlockPointer, Unqualified);
11641 if (paramType.isNull())
11642 return {};
11643
11644 if (Unqualified)
11645 paramType = paramType.getUnqualifiedType();
11646
11647 types.push_back(paramType);
11648 if (Unqualified) {
11649 lParamType = lParamType.getUnqualifiedType();
11650 rParamType = rParamType.getUnqualifiedType();
11651 }
11652
11653 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11654 allLTypes = false;
11655 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11656 allRTypes = false;
11657 }
11658
11659 if (allLTypes) return lhs;
11660 if (allRTypes) return rhs;
11661
11662 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11663 EPI.ExtInfo = einfo;
11664 EPI.ExtParameterInfos =
11665 newParamInfos.empty() ? nullptr : newParamInfos.data();
11666 if (MergedFX)
11667 EPI.FunctionEffects = *MergedFX;
11668 return getFunctionType(retType, types, EPI);
11669 }
11670
11671 if (lproto) allRTypes = false;
11672 if (rproto) allLTypes = false;
11673
11674 const FunctionProtoType *proto = lproto ? lproto : rproto;
11675 if (proto) {
11676 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11677 if (proto->isVariadic())
11678 return {};
11679 // Check that the types are compatible with the types that
11680 // would result from default argument promotions (C99 6.7.5.3p15).
11681 // The only types actually affected are promotable integer
11682 // types and floats, which would be passed as a different
11683 // type depending on whether the prototype is visible.
11684 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11685 QualType paramTy = proto->getParamType(i);
11686
11687 // Look at the converted type of enum types, since that is the type used
11688 // to pass enum values.
11689 if (const auto *ED = paramTy->getAsEnumDecl()) {
11690 paramTy = ED->getIntegerType();
11691 if (paramTy.isNull())
11692 return {};
11693 }
11694
11695 if (isPromotableIntegerType(paramTy) ||
11696 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11697 return {};
11698 }
11699
11700 if (allLTypes) return lhs;
11701 if (allRTypes) return rhs;
11702
11704 EPI.ExtInfo = einfo;
11705 if (MergedFX)
11706 EPI.FunctionEffects = *MergedFX;
11707 return getFunctionType(retType, proto->getParamTypes(), EPI);
11708 }
11709
11710 if (allLTypes) return lhs;
11711 if (allRTypes) return rhs;
11712 return getFunctionNoProtoType(retType, einfo);
11713}
11714
11715/// Given that we have an enum type and a non-enum type, try to merge them.
11716static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11717 QualType other, bool isBlockReturnType) {
11718 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11719 // a signed integer type, or an unsigned integer type.
11720 // Compatibility is based on the underlying type, not the promotion
11721 // type.
11722 QualType underlyingType =
11723 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11724 if (underlyingType.isNull())
11725 return {};
11726 if (Context.hasSameType(underlyingType, other))
11727 return other;
11728
11729 // In block return types, we're more permissive and accept any
11730 // integral type of the same size.
11731 if (isBlockReturnType && other->isIntegerType() &&
11732 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11733 return other;
11734
11735 return {};
11736}
11737
11739 // C17 and earlier and C++ disallow two tag definitions within the same TU
11740 // from being compatible.
11741 if (LangOpts.CPlusPlus || !LangOpts.C23)
11742 return {};
11743
11744 // Nameless tags are comparable only within outer definitions. At the top
11745 // level they are not comparable.
11746 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11747 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11748 return {};
11749
11750 // C23, on the other hand, requires the members to be "the same enough", so
11751 // we use a structural equivalence check.
11754 getLangOpts(), *this, *this, NonEquivalentDecls,
11755 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11756 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11757 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11758}
11759
11761 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11762 bool BlockReturnType, bool IsConditionalOperator) {
11763 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11764 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11765
11766 if (!LHSOBT && !RHSOBT)
11767 return std::nullopt;
11768
11769 if (LHSOBT) {
11770 if (RHSOBT) {
11771 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11772 return QualType();
11773
11774 QualType MergedUnderlying = mergeTypes(
11775 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11776 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11777
11778 if (MergedUnderlying.isNull())
11779 return QualType();
11780
11781 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11782 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11783 return getCommonSugaredType(LHS, RHS);
11785 LHSOBT->getBehaviorKind(),
11786 getCanonicalType(LHSOBT->getUnderlyingType()));
11787 }
11788
11789 // For different underlying types that successfully merge, wrap the
11790 // merged underlying type with the common overflow behavior
11791 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11792 MergedUnderlying);
11793 }
11794 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11795 Unqualified, BlockReturnType, IsConditionalOperator);
11796 }
11797
11798 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11799 Unqualified, BlockReturnType, IsConditionalOperator);
11800}
11801
11802QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11803 bool Unqualified, bool BlockReturnType,
11804 bool IsConditionalOperator) {
11805 // For C++ we will not reach this code with reference types (see below),
11806 // for OpenMP variant call overloading we might.
11807 //
11808 // C++ [expr]: If an expression initially has the type "reference to T", the
11809 // type is adjusted to "T" prior to any further analysis, the expression
11810 // designates the object or function denoted by the reference, and the
11811 // expression is an lvalue unless the reference is an rvalue reference and
11812 // the expression is a function call (possibly inside parentheses).
11813 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11814 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11815 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11816 LHS->getTypeClass() == RHS->getTypeClass())
11817 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11818 OfBlockPointer, Unqualified, BlockReturnType);
11819 if (LHSRefTy || RHSRefTy)
11820 return {};
11821
11822 if (std::optional<QualType> MergedOBT =
11823 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11824 BlockReturnType, IsConditionalOperator))
11825 return *MergedOBT;
11826
11827 if (Unqualified) {
11828 LHS = LHS.getUnqualifiedType();
11829 RHS = RHS.getUnqualifiedType();
11830 }
11831
11832 QualType LHSCan = getCanonicalType(LHS),
11833 RHSCan = getCanonicalType(RHS);
11834
11835 // If two types are identical, they are compatible.
11836 if (LHSCan == RHSCan)
11837 return LHS;
11838
11839 // If the qualifiers are different, the types aren't compatible... mostly.
11840 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11841 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11842 if (LQuals != RQuals) {
11843 // If any of these qualifiers are different, we have a type
11844 // mismatch.
11845 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11846 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11847 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11848 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11849 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11850 return {};
11851
11852 // Exactly one GC qualifier difference is allowed: __strong is
11853 // okay if the other type has no GC qualifier but is an Objective
11854 // C object pointer (i.e. implicitly strong by default). We fix
11855 // this by pretending that the unqualified type was actually
11856 // qualified __strong.
11857 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11858 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11859 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11860
11861 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11862 return {};
11863
11864 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11866 }
11867 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11869 }
11870 return {};
11871 }
11872
11873 // Okay, qualifiers are equal.
11874
11875 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11876 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11877
11878 // We want to consider the two function types to be the same for these
11879 // comparisons, just force one to the other.
11880 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11881 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11882
11883 // Same as above for arrays
11884 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11885 LHSClass = Type::ConstantArray;
11886 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11887 RHSClass = Type::ConstantArray;
11888
11889 // ObjCInterfaces are just specialized ObjCObjects.
11890 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11891 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11892
11893 // Canonicalize ExtVector -> Vector.
11894 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11895 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11896
11897 // If the canonical type classes don't match.
11898 if (LHSClass != RHSClass) {
11899 // Note that we only have special rules for turning block enum
11900 // returns into block int returns, not vice-versa.
11901 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11902 return mergeEnumWithInteger(*this, ETy, RHS, false);
11903 }
11904 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11905 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11906 }
11907 // allow block pointer type to match an 'id' type.
11908 if (OfBlockPointer && !BlockReturnType) {
11909 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11910 return LHS;
11911 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11912 return RHS;
11913 }
11914 // Allow __auto_type to match anything; it merges to the type with more
11915 // information.
11916 if (const auto *AT = LHS->getAs<AutoType>()) {
11917 if (!AT->isDeduced() && AT->isGNUAutoType())
11918 return RHS;
11919 }
11920 if (const auto *AT = RHS->getAs<AutoType>()) {
11921 if (!AT->isDeduced() && AT->isGNUAutoType())
11922 return LHS;
11923 }
11924 return {};
11925 }
11926
11927 // The canonical type classes match.
11928 switch (LHSClass) {
11929#define TYPE(Class, Base)
11930#define ABSTRACT_TYPE(Class, Base)
11931#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11932#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11933#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11934#include "clang/AST/TypeNodes.inc"
11935 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11936
11937 case Type::Auto:
11938 case Type::DeducedTemplateSpecialization:
11939 case Type::LValueReference:
11940 case Type::RValueReference:
11941 case Type::MemberPointer:
11942 llvm_unreachable("C++ should never be in mergeTypes");
11943
11944 case Type::ObjCInterface:
11945 case Type::IncompleteArray:
11946 case Type::VariableArray:
11947 case Type::FunctionProto:
11948 case Type::ExtVector:
11949 case Type::OverflowBehavior:
11950 llvm_unreachable("Types are eliminated above");
11951
11952 case Type::Pointer:
11953 {
11954 // Merge two pointer types, while trying to preserve typedef info
11955 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11956 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11957 if (Unqualified) {
11958 LHSPointee = LHSPointee.getUnqualifiedType();
11959 RHSPointee = RHSPointee.getUnqualifiedType();
11960 }
11961 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11962 Unqualified);
11963 if (ResultType.isNull())
11964 return {};
11965 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11966 return LHS;
11967 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11968 return RHS;
11969 return getPointerType(ResultType);
11970 }
11971 case Type::BlockPointer:
11972 {
11973 // Merge two block pointer types, while trying to preserve typedef info
11974 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11975 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11976 if (Unqualified) {
11977 LHSPointee = LHSPointee.getUnqualifiedType();
11978 RHSPointee = RHSPointee.getUnqualifiedType();
11979 }
11980 if (getLangOpts().OpenCL) {
11981 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11982 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11983 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11984 // 6.12.5) thus the following check is asymmetric.
11985 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11986 return {};
11987 LHSPteeQual.removeAddressSpace();
11988 RHSPteeQual.removeAddressSpace();
11989 LHSPointee =
11990 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11991 RHSPointee =
11992 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11993 }
11994 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11995 Unqualified);
11996 if (ResultType.isNull())
11997 return {};
11998 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11999 return LHS;
12000 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12001 return RHS;
12002 return getBlockPointerType(ResultType);
12003 }
12004 case Type::Atomic:
12005 {
12006 // Merge two pointer types, while trying to preserve typedef info
12007 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12008 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12009 if (Unqualified) {
12010 LHSValue = LHSValue.getUnqualifiedType();
12011 RHSValue = RHSValue.getUnqualifiedType();
12012 }
12013 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12014 Unqualified);
12015 if (ResultType.isNull())
12016 return {};
12017 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12018 return LHS;
12019 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12020 return RHS;
12021 return getAtomicType(ResultType);
12022 }
12023 case Type::ConstantArray:
12024 {
12025 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12026 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12027 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12028 return {};
12029
12030 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12031 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12032 if (Unqualified) {
12033 LHSElem = LHSElem.getUnqualifiedType();
12034 RHSElem = RHSElem.getUnqualifiedType();
12035 }
12036
12037 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12038 if (ResultType.isNull())
12039 return {};
12040
12041 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12042 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12043
12044 // If either side is a variable array, and both are complete, check whether
12045 // the current dimension is definite.
12046 if (LVAT || RVAT) {
12047 auto SizeFetch = [this](const VariableArrayType* VAT,
12048 const ConstantArrayType* CAT)
12049 -> std::pair<bool,llvm::APInt> {
12050 if (VAT) {
12051 std::optional<llvm::APSInt> TheInt;
12052 Expr *E = VAT->getSizeExpr();
12053 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12054 return std::make_pair(true, *TheInt);
12055 return std::make_pair(false, llvm::APSInt());
12056 }
12057 if (CAT)
12058 return std::make_pair(true, CAT->getSize());
12059 return std::make_pair(false, llvm::APInt());
12060 };
12061
12062 bool HaveLSize, HaveRSize;
12063 llvm::APInt LSize, RSize;
12064 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12065 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12066 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12067 return {}; // Definite, but unequal, array dimension
12068 }
12069
12070 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12071 return LHS;
12072 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12073 return RHS;
12074 if (LCAT)
12075 return getConstantArrayType(ResultType, LCAT->getSize(),
12076 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12077 if (RCAT)
12078 return getConstantArrayType(ResultType, RCAT->getSize(),
12079 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12080 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12081 return LHS;
12082 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12083 return RHS;
12084 if (LVAT) {
12085 // FIXME: This isn't correct! But tricky to implement because
12086 // the array's size has to be the size of LHS, but the type
12087 // has to be different.
12088 return LHS;
12089 }
12090 if (RVAT) {
12091 // FIXME: This isn't correct! But tricky to implement because
12092 // the array's size has to be the size of RHS, but the type
12093 // has to be different.
12094 return RHS;
12095 }
12096 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12097 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12098 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12099 }
12100 case Type::FunctionNoProto:
12101 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12102 /*AllowCXX=*/false, IsConditionalOperator);
12103 case Type::Record:
12104 case Type::Enum:
12105 return mergeTagDefinitions(LHS, RHS);
12106 case Type::Builtin:
12107 // Only exactly equal builtin types are compatible, which is tested above.
12108 return {};
12109 case Type::Complex:
12110 // Distinct complex types are incompatible.
12111 return {};
12112 case Type::Vector:
12113 // FIXME: The merged type should be an ExtVector!
12114 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12115 RHSCan->castAs<VectorType>()))
12116 return LHS;
12117 return {};
12118 case Type::ConstantMatrix:
12120 RHSCan->castAs<ConstantMatrixType>()))
12121 return LHS;
12122 return {};
12123 case Type::ObjCObject: {
12124 // Check if the types are assignment compatible.
12125 // FIXME: This should be type compatibility, e.g. whether
12126 // "LHS x; RHS x;" at global scope is legal.
12128 RHS->castAs<ObjCObjectType>()))
12129 return LHS;
12130 return {};
12131 }
12132 case Type::ObjCObjectPointer:
12133 if (OfBlockPointer) {
12136 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12137 return LHS;
12138 return {};
12139 }
12142 return LHS;
12143 return {};
12144 case Type::Pipe:
12145 assert(LHS != RHS &&
12146 "Equivalent pipe types should have already been handled!");
12147 return {};
12148 case Type::ArrayParameter:
12149 assert(LHS != RHS &&
12150 "Equivalent ArrayParameter types should have already been handled!");
12151 return {};
12152 case Type::BitInt: {
12153 // Merge two bit-precise int types, while trying to preserve typedef info.
12154 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12155 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12156 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12157 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12158
12159 // Like unsigned/int, shouldn't have a type if they don't match.
12160 if (LHSUnsigned != RHSUnsigned)
12161 return {};
12162
12163 if (LHSBits != RHSBits)
12164 return {};
12165 return LHS;
12166 }
12167 case Type::HLSLAttributedResource: {
12168 const HLSLAttributedResourceType *LHSTy =
12169 LHS->castAs<HLSLAttributedResourceType>();
12170 const HLSLAttributedResourceType *RHSTy =
12171 RHS->castAs<HLSLAttributedResourceType>();
12172 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12173 LHSTy->getWrappedType()->isHLSLResourceType() &&
12174 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12175
12176 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12177 LHSTy->getContainedType() == RHSTy->getContainedType())
12178 return LHS;
12179 return {};
12180 }
12181 case Type::HLSLInlineSpirv:
12182 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12183 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12184
12185 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12186 LHSTy->getSize() == RHSTy->getSize() &&
12187 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12188 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12189 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12190 return {};
12191
12192 return LHS;
12193 }
12194 return {};
12195 }
12196
12197 llvm_unreachable("Invalid Type::Class!");
12198}
12199
12201 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12202 bool &CanUseFirst, bool &CanUseSecond,
12204 assert(NewParamInfos.empty() && "param info list not empty");
12205 CanUseFirst = CanUseSecond = true;
12206 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12207 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12208
12209 // Fast path: if the first type doesn't have ext parameter infos,
12210 // we match if and only if the second type also doesn't have them.
12211 if (!FirstHasInfo && !SecondHasInfo)
12212 return true;
12213
12214 bool NeedParamInfo = false;
12215 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12216 : SecondFnType->getExtParameterInfos().size();
12217
12218 for (size_t I = 0; I < E; ++I) {
12219 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12220 if (FirstHasInfo)
12221 FirstParam = FirstFnType->getExtParameterInfo(I);
12222 if (SecondHasInfo)
12223 SecondParam = SecondFnType->getExtParameterInfo(I);
12224
12225 // Cannot merge unless everything except the noescape flag matches.
12226 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12227 return false;
12228
12229 bool FirstNoEscape = FirstParam.isNoEscape();
12230 bool SecondNoEscape = SecondParam.isNoEscape();
12231 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12232 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12233 if (NewParamInfos.back().getOpaqueValue())
12234 NeedParamInfo = true;
12235 if (FirstNoEscape != IsNoEscape)
12236 CanUseFirst = false;
12237 if (SecondNoEscape != IsNoEscape)
12238 CanUseSecond = false;
12239 }
12240
12241 if (!NeedParamInfo)
12242 NewParamInfos.clear();
12243
12244 return true;
12245}
12246
12248 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12249 It->second = nullptr;
12250 for (auto *SubClass : ObjCSubClasses.lookup(D))
12251 ResetObjCLayout(SubClass);
12252 }
12253}
12254
12255/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12256/// 'RHS' attributes and returns the merged version; including for function
12257/// return types.
12259 QualType LHSCan = getCanonicalType(LHS),
12260 RHSCan = getCanonicalType(RHS);
12261 // If two types are identical, they are compatible.
12262 if (LHSCan == RHSCan)
12263 return LHS;
12264 if (RHSCan->isFunctionType()) {
12265 if (!LHSCan->isFunctionType())
12266 return {};
12267 QualType OldReturnType =
12268 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12269 QualType NewReturnType =
12270 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12271 QualType ResReturnType =
12272 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12273 if (ResReturnType.isNull())
12274 return {};
12275 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12276 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12277 // In either case, use OldReturnType to build the new function type.
12278 const auto *F = LHS->castAs<FunctionType>();
12279 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12280 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12281 EPI.ExtInfo = getFunctionExtInfo(LHS);
12282 QualType ResultType =
12283 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12284 return ResultType;
12285 }
12286 }
12287 return {};
12288 }
12289
12290 // If the qualifiers are different, the types can still be merged.
12291 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12292 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12293 if (LQuals != RQuals) {
12294 // If any of these qualifiers are different, we have a type mismatch.
12295 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12296 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12297 return {};
12298
12299 // Exactly one GC qualifier difference is allowed: __strong is
12300 // okay if the other type has no GC qualifier but is an Objective
12301 // C object pointer (i.e. implicitly strong by default). We fix
12302 // this by pretending that the unqualified type was actually
12303 // qualified __strong.
12304 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12305 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12306 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12307
12308 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12309 return {};
12310
12311 if (GC_L == Qualifiers::Strong)
12312 return LHS;
12313 if (GC_R == Qualifiers::Strong)
12314 return RHS;
12315 return {};
12316 }
12317
12318 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12319 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12320 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12321 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12322 if (ResQT == LHSBaseQT)
12323 return LHS;
12324 if (ResQT == RHSBaseQT)
12325 return RHS;
12326 }
12327 return {};
12328}
12329
12330//===----------------------------------------------------------------------===//
12331// Integer Predicates
12332//===----------------------------------------------------------------------===//
12333
12335 if (const auto *ED = T->getAsEnumDecl())
12336 T = ED->getIntegerType();
12337 if (T->isBooleanType())
12338 return 1;
12339 if (const auto *EIT = T->getAs<BitIntType>())
12340 return EIT->getNumBits();
12341 // For builtin types, just use the standard type sizing method
12342 return (unsigned)getTypeSize(T);
12343}
12344
12346 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12347 T->isFixedPointType()) &&
12348 "Unexpected type");
12349
12350 // Turn <4 x signed int> -> <4 x unsigned int>
12351 if (const auto *VTy = T->getAs<VectorType>())
12352 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12353 VTy->getNumElements(), VTy->getVectorKind());
12354
12355 // For _BitInt, return an unsigned _BitInt with same width.
12356 if (const auto *EITy = T->getAs<BitIntType>())
12357 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12358
12359 // For the overflow behavior types, construct a new unsigned variant
12360 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12362 OBT->getBehaviorKind(),
12363 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12364
12365 // For enums, get the underlying integer type of the enum, and let the general
12366 // integer type signchanging code handle it.
12367 if (const auto *ED = T->getAsEnumDecl())
12368 T = ED->getIntegerType();
12369
12370 switch (T->castAs<BuiltinType>()->getKind()) {
12371 case BuiltinType::Char_U:
12372 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12373 case BuiltinType::Char_S:
12374 case BuiltinType::SChar:
12375 case BuiltinType::Char8:
12376 return UnsignedCharTy;
12377 case BuiltinType::Short:
12378 return UnsignedShortTy;
12379 case BuiltinType::Int:
12380 return UnsignedIntTy;
12381 case BuiltinType::Long:
12382 return UnsignedLongTy;
12383 case BuiltinType::LongLong:
12384 return UnsignedLongLongTy;
12385 case BuiltinType::Int128:
12386 return UnsignedInt128Ty;
12387 // wchar_t is special. It is either signed or not, but when it's signed,
12388 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12389 // version of its underlying type instead.
12390 case BuiltinType::WChar_S:
12391 return getUnsignedWCharType();
12392
12393 case BuiltinType::ShortAccum:
12394 return UnsignedShortAccumTy;
12395 case BuiltinType::Accum:
12396 return UnsignedAccumTy;
12397 case BuiltinType::LongAccum:
12398 return UnsignedLongAccumTy;
12399 case BuiltinType::SatShortAccum:
12401 case BuiltinType::SatAccum:
12402 return SatUnsignedAccumTy;
12403 case BuiltinType::SatLongAccum:
12405 case BuiltinType::ShortFract:
12406 return UnsignedShortFractTy;
12407 case BuiltinType::Fract:
12408 return UnsignedFractTy;
12409 case BuiltinType::LongFract:
12410 return UnsignedLongFractTy;
12411 case BuiltinType::SatShortFract:
12413 case BuiltinType::SatFract:
12414 return SatUnsignedFractTy;
12415 case BuiltinType::SatLongFract:
12417 default:
12418 assert((T->hasUnsignedIntegerRepresentation() ||
12419 T->isUnsignedFixedPointType()) &&
12420 "Unexpected signed integer or fixed point type");
12421 return T;
12422 }
12423}
12424
12426 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12427 T->isFixedPointType()) &&
12428 "Unexpected type");
12429
12430 // Turn <4 x unsigned int> -> <4 x signed int>
12431 if (const auto *VTy = T->getAs<VectorType>())
12432 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12433 VTy->getNumElements(), VTy->getVectorKind());
12434
12435 // For _BitInt, return a signed _BitInt with same width.
12436 if (const auto *EITy = T->getAs<BitIntType>())
12437 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12438
12439 // For enums, get the underlying integer type of the enum, and let the general
12440 // integer type signchanging code handle it.
12441 if (const auto *ED = T->getAsEnumDecl())
12442 T = ED->getIntegerType();
12443
12444 switch (T->castAs<BuiltinType>()->getKind()) {
12445 case BuiltinType::Char_S:
12446 // Plain `char` is mapped to `signed char` even if it's already signed
12447 case BuiltinType::Char_U:
12448 case BuiltinType::UChar:
12449 case BuiltinType::Char8:
12450 return SignedCharTy;
12451 case BuiltinType::UShort:
12452 return ShortTy;
12453 case BuiltinType::UInt:
12454 return IntTy;
12455 case BuiltinType::ULong:
12456 return LongTy;
12457 case BuiltinType::ULongLong:
12458 return LongLongTy;
12459 case BuiltinType::UInt128:
12460 return Int128Ty;
12461 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12462 // there's no matching "signed wchar_t". Therefore we return the signed
12463 // version of its underlying type instead.
12464 case BuiltinType::WChar_U:
12465 return getSignedWCharType();
12466
12467 case BuiltinType::UShortAccum:
12468 return ShortAccumTy;
12469 case BuiltinType::UAccum:
12470 return AccumTy;
12471 case BuiltinType::ULongAccum:
12472 return LongAccumTy;
12473 case BuiltinType::SatUShortAccum:
12474 return SatShortAccumTy;
12475 case BuiltinType::SatUAccum:
12476 return SatAccumTy;
12477 case BuiltinType::SatULongAccum:
12478 return SatLongAccumTy;
12479 case BuiltinType::UShortFract:
12480 return ShortFractTy;
12481 case BuiltinType::UFract:
12482 return FractTy;
12483 case BuiltinType::ULongFract:
12484 return LongFractTy;
12485 case BuiltinType::SatUShortFract:
12486 return SatShortFractTy;
12487 case BuiltinType::SatUFract:
12488 return SatFractTy;
12489 case BuiltinType::SatULongFract:
12490 return SatLongFractTy;
12491 default:
12492 assert(
12493 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12494 "Unexpected signed integer or fixed point type");
12495 return T;
12496 }
12497}
12498
12500
12503
12504//===----------------------------------------------------------------------===//
12505// Builtin Type Computation
12506//===----------------------------------------------------------------------===//
12507
12508/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12509/// pointer over the consumed characters. This returns the resultant type. If
12510/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12511/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12512/// a vector of "i*".
12513///
12514/// RequiresICE is filled in on return to indicate whether the value is required
12515/// to be an Integer Constant Expression.
12516static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12518 bool &RequiresICE,
12519 bool AllowTypeModifiers) {
12520 // Modifiers.
12521 int HowLong = 0;
12522 bool Signed = false, Unsigned = false;
12523 RequiresICE = false;
12524
12525 // Read the prefixed modifiers first.
12526 bool Done = false;
12527 #ifndef NDEBUG
12528 bool IsSpecial = false;
12529 #endif
12530 while (!Done) {
12531 switch (*Str++) {
12532 default: Done = true; --Str; break;
12533 case 'I':
12534 RequiresICE = true;
12535 break;
12536 case 'S':
12537 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12538 assert(!Signed && "Can't use 'S' modifier multiple times!");
12539 Signed = true;
12540 break;
12541 case 'U':
12542 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12543 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12544 Unsigned = true;
12545 break;
12546 case 'L':
12547 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12548 assert(HowLong <= 2 && "Can't have LLLL modifier");
12549 ++HowLong;
12550 break;
12551 case 'N':
12552 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12553 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12554 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12555 #ifndef NDEBUG
12556 IsSpecial = true;
12557 #endif
12558 if (Context.getTargetInfo().getLongWidth() == 32)
12559 ++HowLong;
12560 break;
12561 case 'W':
12562 // This modifier represents int64 type.
12563 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12564 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12565 #ifndef NDEBUG
12566 IsSpecial = true;
12567 #endif
12568 switch (Context.getTargetInfo().getInt64Type()) {
12569 default:
12570 llvm_unreachable("Unexpected integer type");
12572 HowLong = 1;
12573 break;
12575 HowLong = 2;
12576 break;
12577 }
12578 break;
12579 case 'Z':
12580 // This modifier represents int32 type.
12581 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12582 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12583 #ifndef NDEBUG
12584 IsSpecial = true;
12585 #endif
12586 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12587 default:
12588 llvm_unreachable("Unexpected integer type");
12590 HowLong = 0;
12591 break;
12593 HowLong = 1;
12594 break;
12596 HowLong = 2;
12597 break;
12598 }
12599 break;
12600 case 'O':
12601 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12602 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12603 #ifndef NDEBUG
12604 IsSpecial = true;
12605 #endif
12606 if (Context.getLangOpts().OpenCL)
12607 HowLong = 1;
12608 else
12609 HowLong = 2;
12610 break;
12611 }
12612 }
12613
12614 QualType Type;
12615
12616 // Read the base type.
12617 switch (*Str++) {
12618 default:
12619 llvm_unreachable("Unknown builtin type letter!");
12620 case 'x':
12621 assert(HowLong == 0 && !Signed && !Unsigned &&
12622 "Bad modifiers used with 'x'!");
12623 Type = Context.Float16Ty;
12624 break;
12625 case 'y':
12626 assert(HowLong == 0 && !Signed && !Unsigned &&
12627 "Bad modifiers used with 'y'!");
12628 Type = Context.BFloat16Ty;
12629 break;
12630 case 'v':
12631 assert(HowLong == 0 && !Signed && !Unsigned &&
12632 "Bad modifiers used with 'v'!");
12633 Type = Context.VoidTy;
12634 break;
12635 case 'h':
12636 assert(HowLong == 0 && !Signed && !Unsigned &&
12637 "Bad modifiers used with 'h'!");
12638 Type = Context.HalfTy;
12639 break;
12640 case 'f':
12641 assert(HowLong == 0 && !Signed && !Unsigned &&
12642 "Bad modifiers used with 'f'!");
12643 Type = Context.FloatTy;
12644 break;
12645 case 'd':
12646 assert(HowLong < 3 && !Signed && !Unsigned &&
12647 "Bad modifiers used with 'd'!");
12648 if (HowLong == 1)
12649 Type = Context.LongDoubleTy;
12650 else if (HowLong == 2)
12651 Type = Context.Float128Ty;
12652 else
12653 Type = Context.DoubleTy;
12654 break;
12655 case 's':
12656 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12657 if (Unsigned)
12658 Type = Context.UnsignedShortTy;
12659 else
12660 Type = Context.ShortTy;
12661 break;
12662 case 'i':
12663 if (HowLong == 3)
12664 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12665 else if (HowLong == 2)
12666 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12667 else if (HowLong == 1)
12668 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12669 else
12670 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12671 break;
12672 case 'c':
12673 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12674 if (Signed)
12675 Type = Context.SignedCharTy;
12676 else if (Unsigned)
12677 Type = Context.UnsignedCharTy;
12678 else
12679 Type = Context.CharTy;
12680 break;
12681 case 'b': // boolean
12682 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12683 Type = Context.BoolTy;
12684 break;
12685 case 'z': // size_t.
12686 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12687 Type = Context.getSizeType();
12688 break;
12689 case 'w': // wchar_t.
12690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12691 Type = Context.getWideCharType();
12692 break;
12693 case 'F':
12694 Type = Context.getCFConstantStringType();
12695 break;
12696 case 'G':
12697 Type = Context.getObjCIdType();
12698 break;
12699 case 'H':
12700 Type = Context.getObjCSelType();
12701 break;
12702 case 'M':
12703 Type = Context.getObjCSuperType();
12704 break;
12705 case 'a':
12706 Type = Context.getBuiltinVaListType();
12707 assert(!Type.isNull() && "builtin va list type not initialized!");
12708 break;
12709 case 'A':
12710 // This is a "reference" to a va_list; however, what exactly
12711 // this means depends on how va_list is defined. There are two
12712 // different kinds of va_list: ones passed by value, and ones
12713 // passed by reference. An example of a by-value va_list is
12714 // x86, where va_list is a char*. An example of by-ref va_list
12715 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12716 // we want this argument to be a char*&; for x86-64, we want
12717 // it to be a __va_list_tag*.
12718 Type = Context.getBuiltinVaListType();
12719 assert(!Type.isNull() && "builtin va list type not initialized!");
12720 if (Type->isArrayType())
12721 Type = Context.getArrayDecayedType(Type);
12722 else
12723 Type = Context.getLValueReferenceType(Type);
12724 break;
12725 case 'q': {
12726 char *End;
12727 unsigned NumElements = strtoul(Str, &End, 10);
12728 assert(End != Str && "Missing vector size");
12729 Str = End;
12730
12731 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12732 RequiresICE, false);
12733 assert(!RequiresICE && "Can't require vector ICE");
12734
12735 Type = Context.getScalableVectorType(ElementType, NumElements);
12736 break;
12737 }
12738 case 'Q': {
12739 switch (*Str++) {
12740 case 'a': {
12741 Type = Context.SveCountTy;
12742 break;
12743 }
12744 case 'b': {
12745 Type = Context.AMDGPUBufferRsrcTy;
12746 break;
12747 }
12748 case 'c': {
12749 Type = Context.AMDGPUFeaturePredicateTy;
12750 break;
12751 }
12752 case 't': {
12753 Type = Context.AMDGPUTextureTy;
12754 break;
12755 }
12756 case 'r': {
12757 Type = Context.HLSLResourceTy;
12758 break;
12759 }
12760 default:
12761 llvm_unreachable("Unexpected target builtin type");
12762 }
12763 break;
12764 }
12765 case 'V': {
12766 char *End;
12767 unsigned NumElements = strtoul(Str, &End, 10);
12768 assert(End != Str && "Missing vector size");
12769 Str = End;
12770
12771 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12772 RequiresICE, false);
12773 assert(!RequiresICE && "Can't require vector ICE");
12774
12775 // TODO: No way to make AltiVec vectors in builtins yet.
12776 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12777 break;
12778 }
12779 case 'E': {
12780 char *End;
12781
12782 unsigned NumElements = strtoul(Str, &End, 10);
12783 assert(End != Str && "Missing vector size");
12784
12785 Str = End;
12786
12787 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12788 false);
12789 Type = Context.getExtVectorType(ElementType, NumElements);
12790 break;
12791 }
12792 case 'X': {
12793 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12794 false);
12795 assert(!RequiresICE && "Can't require complex ICE");
12796 Type = Context.getComplexType(ElementType);
12797 break;
12798 }
12799 case 'Y':
12800 Type = Context.getPointerDiffType();
12801 break;
12802 case 'P':
12803 Type = Context.getFILEType();
12804 if (Type.isNull()) {
12806 return {};
12807 }
12808 break;
12809 case 'J':
12810 if (Signed)
12811 Type = Context.getsigjmp_bufType();
12812 else
12813 Type = Context.getjmp_bufType();
12814
12815 if (Type.isNull()) {
12817 return {};
12818 }
12819 break;
12820 case 'K':
12821 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12822 Type = Context.getucontext_tType();
12823
12824 if (Type.isNull()) {
12826 return {};
12827 }
12828 break;
12829 case 'p':
12830 Type = Context.getProcessIDType();
12831 break;
12832 case 'm':
12833 Type = Context.MFloat8Ty;
12834 break;
12835 }
12836
12837 // If there are modifiers and if we're allowed to parse them, go for it.
12838 Done = !AllowTypeModifiers;
12839 while (!Done) {
12840 switch (char c = *Str++) {
12841 default: Done = true; --Str; break;
12842 case '*':
12843 case '&': {
12844 // Both pointers and references can have their pointee types
12845 // qualified with an address space.
12846 char *End;
12847 unsigned AddrSpace = strtoul(Str, &End, 10);
12848 if (End != Str) {
12849 // Note AddrSpace == 0 is not the same as an unspecified address space.
12850 Type = Context.getAddrSpaceQualType(
12851 Type,
12852 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12853 Str = End;
12854 }
12855 if (c == '*')
12856 Type = Context.getPointerType(Type);
12857 else
12858 Type = Context.getLValueReferenceType(Type);
12859 break;
12860 }
12861 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12862 case 'C':
12863 Type = Type.withConst();
12864 break;
12865 case 'D':
12866 Type = Context.getVolatileType(Type);
12867 break;
12868 case 'R':
12869 Type = Type.withRestrict();
12870 break;
12871 }
12872 }
12873
12874 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12875 "Integer constant 'I' type must be an integer");
12876
12877 return Type;
12878}
12879
12880// On some targets such as PowerPC, some of the builtins are defined with custom
12881// type descriptors for target-dependent types. These descriptors are decoded in
12882// other functions, but it may be useful to be able to fall back to default
12883// descriptor decoding to define builtins mixing target-dependent and target-
12884// independent types. This function allows decoding one type descriptor with
12885// default decoding.
12886QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12887 GetBuiltinTypeError &Error, bool &RequireICE,
12888 bool AllowTypeModifiers) const {
12889 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12890}
12891
12892/// GetBuiltinType - Return the type for the specified builtin.
12895 unsigned *IntegerConstantArgs) const {
12896 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12897 if (TypeStr[0] == '\0') {
12899 return {};
12900 }
12901
12902 SmallVector<QualType, 8> ArgTypes;
12903
12904 bool RequiresICE = false;
12905 Error = GE_None;
12906 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12907 RequiresICE, true);
12908 if (Error != GE_None)
12909 return {};
12910
12911 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12912
12913 while (TypeStr[0] && TypeStr[0] != '.') {
12914 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12915 if (Error != GE_None)
12916 return {};
12917
12918 // If this argument is required to be an IntegerConstantExpression and the
12919 // caller cares, fill in the bitmask we return.
12920 if (RequiresICE && IntegerConstantArgs)
12921 *IntegerConstantArgs |= 1 << ArgTypes.size();
12922
12923 // Do array -> pointer decay. The builtin should use the decayed type.
12924 if (Ty->isArrayType())
12925 Ty = getArrayDecayedType(Ty);
12926
12927 ArgTypes.push_back(Ty);
12928 }
12929
12930 if (Id == Builtin::BI__GetExceptionInfo)
12931 return {};
12932
12933 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12934 "'.' should only occur at end of builtin type list!");
12935
12936 bool Variadic = (TypeStr[0] == '.');
12937
12938 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12939 if (BuiltinInfo.isNoReturn(Id))
12940 EI = EI.withNoReturn(true);
12941
12942 // We really shouldn't be making a no-proto type here.
12943 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12944 return getFunctionNoProtoType(ResType, EI);
12945
12947 EPI.ExtInfo = EI;
12948 EPI.Variadic = Variadic;
12949 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12950 EPI.ExceptionSpec.Type =
12952
12953 return getFunctionType(ResType, ArgTypes, EPI);
12954}
12955
12957 const FunctionDecl *FD) {
12958 if (!FD->isExternallyVisible())
12959 return GVA_Internal;
12960
12961 // Non-user-provided functions get emitted as weak definitions with every
12962 // use, no matter whether they've been explicitly instantiated etc.
12963 if (!FD->isUserProvided())
12964 return GVA_DiscardableODR;
12965
12967 switch (FD->getTemplateSpecializationKind()) {
12968 case TSK_Undeclared:
12971 break;
12972
12974 return GVA_StrongODR;
12975
12976 // C++11 [temp.explicit]p10:
12977 // [ Note: The intent is that an inline function that is the subject of
12978 // an explicit instantiation declaration will still be implicitly
12979 // instantiated when used so that the body can be considered for
12980 // inlining, but that no out-of-line copy of the inline function would be
12981 // generated in the translation unit. -- end note ]
12984
12987 break;
12988 }
12989
12990 if (!FD->isInlined())
12991 return External;
12992
12993 if ((!Context.getLangOpts().CPlusPlus &&
12994 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12995 !FD->hasAttr<DLLExportAttr>()) ||
12996 FD->hasAttr<GNUInlineAttr>()) {
12997 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12998
12999 // GNU or C99 inline semantics. Determine whether this symbol should be
13000 // externally visible.
13002 return External;
13003
13004 // C99 inline semantics, where the symbol is not externally visible.
13006 }
13007
13008 // Functions specified with extern and inline in -fms-compatibility mode
13009 // forcibly get emitted. While the body of the function cannot be later
13010 // replaced, the function definition cannot be discarded.
13011 if (FD->isMSExternInline())
13012 return GVA_StrongODR;
13013
13014 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13016 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13017 !FD->hasAttr<DLLExportAttr>()) {
13018 // Both Clang and MSVC implement inherited constructors as forwarding
13019 // thunks that delegate to the base constructor. Keep non-dllexport
13020 // inheriting constructor thunks internal since they are not needed
13021 // outside the translation unit.
13022 //
13023 // dllexport inherited constructors are exempted so they are externally
13024 // visible, matching MSVC's export behavior. Inherited constructors
13025 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13026 // cleanup types) are excluded from export in Sema to avoid silent
13027 // runtime mismatches.
13028 return GVA_Internal;
13029 }
13030
13031 return GVA_DiscardableODR;
13032}
13033
13035 const Decl *D, GVALinkage L) {
13036 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13037 // dllexport/dllimport on inline functions.
13038 if (D->hasAttr<DLLImportAttr>()) {
13039 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13041 } else if (D->hasAttr<DLLExportAttr>()) {
13042 if (L == GVA_DiscardableODR)
13043 return GVA_StrongODR;
13044 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13045 // Device-side functions with __global__ attribute must always be
13046 // visible externally so they can be launched from host.
13047 if (D->hasAttr<CUDAGlobalAttr>() &&
13048 (L == GVA_DiscardableODR || L == GVA_Internal))
13049 return GVA_StrongODR;
13050 // Single source offloading languages like CUDA/HIP need to be able to
13051 // access static device variables from host code of the same compilation
13052 // unit. This is done by externalizing the static variable with a shared
13053 // name between the host and device compilation which is the same for the
13054 // same compilation unit whereas different among different compilation
13055 // units.
13056 if (Context.shouldExternalize(D))
13057 return GVA_StrongExternal;
13058 }
13059 return L;
13060}
13061
13062/// Adjust the GVALinkage for a declaration based on what an external AST source
13063/// knows about whether there can be other definitions of this declaration.
13064static GVALinkage
13066 GVALinkage L) {
13067 ExternalASTSource *Source = Ctx.getExternalSource();
13068 if (!Source)
13069 return L;
13070
13071 switch (Source->hasExternalDefinitions(D)) {
13073 // Other translation units rely on us to provide the definition.
13074 if (L == GVA_DiscardableODR)
13075 return GVA_StrongODR;
13076 break;
13077
13080
13082 break;
13083 }
13084 return L;
13085}
13086
13092
13094 const VarDecl *VD) {
13095 // As an extension for interactive REPLs, make sure constant variables are
13096 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13097 // marking them as internal.
13098 if (Context.getLangOpts().CPlusPlus &&
13099 Context.getLangOpts().IncrementalExtensions &&
13100 VD->getType().isConstQualified() &&
13101 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13103 return GVA_DiscardableODR;
13104
13105 if (!VD->isExternallyVisible())
13106 return GVA_Internal;
13107
13108 if (VD->isStaticLocal()) {
13109 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13110 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13111 LexicalContext = LexicalContext->getLexicalParent();
13112
13113 // ObjC Blocks can create local variables that don't have a FunctionDecl
13114 // LexicalContext.
13115 if (!LexicalContext)
13116 return GVA_DiscardableODR;
13117
13118 // Otherwise, let the static local variable inherit its linkage from the
13119 // nearest enclosing function.
13120 auto StaticLocalLinkage =
13121 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13122
13123 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13124 // be emitted in any object with references to the symbol for the object it
13125 // contains, whether inline or out-of-line."
13126 // Similar behavior is observed with MSVC. An alternative ABI could use
13127 // StrongODR/AvailableExternally to match the function, but none are
13128 // known/supported currently.
13129 if (StaticLocalLinkage == GVA_StrongODR ||
13130 StaticLocalLinkage == GVA_AvailableExternally)
13131 return GVA_DiscardableODR;
13132 return StaticLocalLinkage;
13133 }
13134
13135 // MSVC treats in-class initialized static data members as definitions.
13136 // By giving them non-strong linkage, out-of-line definitions won't
13137 // cause link errors.
13138 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13139 return GVA_DiscardableODR;
13140
13141 // Most non-template variables have strong linkage; inline variables are
13142 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13143 GVALinkage StrongLinkage;
13144 switch (Context.getInlineVariableDefinitionKind(VD)) {
13146 StrongLinkage = GVA_StrongExternal;
13147 break;
13150 StrongLinkage = GVA_DiscardableODR;
13151 break;
13153 StrongLinkage = GVA_StrongODR;
13154 break;
13155 }
13156
13157 switch (VD->getTemplateSpecializationKind()) {
13158 case TSK_Undeclared:
13159 return StrongLinkage;
13160
13162 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13163 VD->isStaticDataMember()
13165 : StrongLinkage;
13166
13168 return GVA_StrongODR;
13169
13172
13174 return GVA_DiscardableODR;
13175 }
13176
13177 llvm_unreachable("Invalid Linkage!");
13178}
13179
13185
13187 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13188 if (!VD->isFileVarDecl())
13189 return false;
13190 // Global named register variables (GNU extension) are never emitted.
13191 if (VD->getStorageClass() == SC_Register)
13192 return false;
13193 if (VD->getDescribedVarTemplate() ||
13195 return false;
13196 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13197 // We never need to emit an uninstantiated function template.
13198 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13199 return false;
13200 } else if (isa<PragmaCommentDecl>(D))
13201 return true;
13203 return true;
13204 else if (isa<OMPRequiresDecl>(D))
13205 return true;
13206 else if (isa<OMPThreadPrivateDecl>(D))
13207 return !D->getDeclContext()->isDependentContext();
13208 else if (isa<OMPAllocateDecl>(D))
13209 return !D->getDeclContext()->isDependentContext();
13211 return !D->getDeclContext()->isDependentContext();
13212 else if (isa<ImportDecl>(D))
13213 return true;
13214 else
13215 return false;
13216
13217 // If this is a member of a class template, we do not need to emit it.
13219 return false;
13220
13221 // Weak references don't produce any output by themselves.
13222 if (D->hasAttr<WeakRefAttr>())
13223 return false;
13224
13225 // SYCL device compilation requires that functions defined with the
13226 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13227 // other entities are emitted only if they are used by a function
13228 // defined with one of those attributes.
13229 if (LangOpts.SYCLIsDevice)
13230 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13231 D->hasAttr<SYCLExternalAttr>());
13232
13233 // Aliases and used decls are required.
13234 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13235 return true;
13236
13237 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13238 // Forward declarations aren't required.
13239 if (!FD->doesThisDeclarationHaveABody())
13240 return FD->doesDeclarationForceExternallyVisibleDefinition();
13241
13242 // Constructors and destructors are required.
13243 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13244 return true;
13245
13246 // The key function for a class is required. This rule only comes
13247 // into play when inline functions can be key functions, though.
13248 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13249 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13250 const CXXRecordDecl *RD = MD->getParent();
13251 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13252 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13253 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13254 return true;
13255 }
13256 }
13257 }
13258
13260
13261 // static, static inline, always_inline, and extern inline functions can
13262 // always be deferred. Normal inline functions can be deferred in C99/C++.
13263 // Implicit template instantiations can also be deferred in C++.
13265 }
13266
13267 const auto *VD = cast<VarDecl>(D);
13268 assert(VD->isFileVarDecl() && "Expected file scoped var");
13269
13270 // If the decl is marked as `declare target to`, it should be emitted for the
13271 // host and for the device.
13272 if (LangOpts.OpenMP &&
13273 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13274 return true;
13275
13276 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13278 return false;
13279
13280 if (VD->shouldEmitInExternalSource())
13281 return false;
13282
13283 // Variables that can be needed in other TUs are required.
13286 return true;
13287
13288 // We never need to emit a variable that is available in another TU.
13290 return false;
13291
13292 // Variables that have destruction with side-effects are required.
13293 if (VD->needsDestruction(*this))
13294 return true;
13295
13296 // Variables that have initialization with side-effects are required.
13297 if (VD->hasInitWithSideEffects())
13298 return true;
13299
13300 // Likewise, variables with tuple-like bindings are required if their
13301 // bindings have side-effects.
13302 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13303 for (const auto *BD : DD->flat_bindings())
13304 if (const auto *BindingVD = BD->getHoldingVar())
13305 if (DeclMustBeEmitted(BindingVD))
13306 return true;
13307 }
13308
13309 return false;
13310}
13311
13313 const FunctionDecl *FD,
13314 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13315 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13316 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13317 FD = FD->getMostRecentDecl();
13318 // FIXME: The order of traversal here matters and depends on the order of
13319 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13320 // shouldn't rely on that.
13321 for (auto *CurDecl :
13323 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13324 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13325 SeenDecls.insert(CurFD).second) {
13326 Pred(CurFD);
13327 }
13328 }
13329}
13330
13332 bool IsCXXMethod) const {
13333 // Pass through to the C++ ABI object
13334 if (IsCXXMethod)
13335 return ABI->getDefaultMethodCallConv(IsVariadic);
13336
13337 switch (LangOpts.getDefaultCallingConv()) {
13339 break;
13341 return CC_C;
13343 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13344 return CC_X86FastCall;
13345 break;
13347 if (!IsVariadic)
13348 return CC_X86StdCall;
13349 break;
13351 // __vectorcall cannot be applied to variadic functions.
13352 if (!IsVariadic)
13353 return CC_X86VectorCall;
13354 break;
13356 // __regcall cannot be applied to variadic functions.
13357 if (!IsVariadic)
13358 return CC_X86RegCall;
13359 break;
13361 if (!IsVariadic)
13362 return CC_M68kRTD;
13363 break;
13364 }
13365 return Target->getDefaultCallingConv();
13366}
13367
13369 // Pass through to the C++ ABI object
13370 return ABI->isNearlyEmpty(RD);
13371}
13372
13374 if (!VTContext) {
13375 auto ABI = Target->getCXXABI();
13376 if (ABI.isMicrosoft())
13377 VTContext.reset(new MicrosoftVTableContext(*this));
13378 else {
13379 VTContext.reset(new ItaniumVTableContext(*this));
13380 }
13381 }
13382 return VTContext.get();
13383}
13384
13386 if (!T)
13387 T = Target;
13388 switch (T->getCXXABI().getKind()) {
13389 case TargetCXXABI::AppleARM64:
13390 case TargetCXXABI::Fuchsia:
13391 case TargetCXXABI::GenericAArch64:
13392 case TargetCXXABI::GenericItanium:
13393 case TargetCXXABI::GenericARM:
13394 case TargetCXXABI::GenericMIPS:
13395 case TargetCXXABI::iOS:
13396 case TargetCXXABI::WebAssembly:
13397 case TargetCXXABI::WatchOS:
13398 case TargetCXXABI::XL:
13400 case TargetCXXABI::Microsoft:
13402 }
13403 llvm_unreachable("Unsupported ABI");
13404}
13405
13407 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13408 "Device mangle context does not support Microsoft mangling.");
13409 switch (T.getCXXABI().getKind()) {
13410 case TargetCXXABI::AppleARM64:
13411 case TargetCXXABI::Fuchsia:
13412 case TargetCXXABI::GenericAArch64:
13413 case TargetCXXABI::GenericItanium:
13414 case TargetCXXABI::GenericARM:
13415 case TargetCXXABI::GenericMIPS:
13416 case TargetCXXABI::iOS:
13417 case TargetCXXABI::WebAssembly:
13418 case TargetCXXABI::WatchOS:
13419 case TargetCXXABI::XL:
13421 *this, getDiagnostics(),
13422 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13423 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13424 return RD->getDeviceLambdaManglingNumber();
13425 return std::nullopt;
13426 },
13427 /*IsAux=*/true);
13428 case TargetCXXABI::Microsoft:
13430 /*IsAux=*/true);
13431 }
13432 llvm_unreachable("Unsupported ABI");
13433}
13434
13436 // If the host and device have different C++ ABIs, mark it as the device
13437 // mangle context so that the mangling needs to retrieve the additional
13438 // device lambda mangling number instead of the regular host one.
13439 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13440 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13442 }
13443
13445}
13446
13447CXXABI::~CXXABI() = default;
13448
13450 return ASTRecordLayouts.getMemorySize() +
13451 llvm::capacity_in_bytes(ObjCLayouts) +
13452 llvm::capacity_in_bytes(KeyFunctions) +
13453 llvm::capacity_in_bytes(ObjCImpls) +
13454 llvm::capacity_in_bytes(BlockVarCopyInits) +
13455 llvm::capacity_in_bytes(DeclAttrs) +
13456 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13457 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13458 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13459 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13460 llvm::capacity_in_bytes(OverriddenMethods) +
13461 llvm::capacity_in_bytes(Types) +
13462 llvm::capacity_in_bytes(VariableArrayTypes);
13463}
13464
13465/// getIntTypeForBitwidth -
13466/// sets integer QualTy according to specified details:
13467/// bitwidth, signed/unsigned.
13468/// Returns empty type if there is no appropriate target types.
13470 unsigned Signed) const {
13472 CanQualType QualTy = getFromTargetType(Ty);
13473 if (!QualTy && DestWidth == 128)
13474 return Signed ? Int128Ty : UnsignedInt128Ty;
13475 return QualTy;
13476}
13477
13478/// getRealTypeForBitwidth -
13479/// sets floating point QualTy according to specified bitwidth.
13480/// Returns empty type if there is no appropriate target types.
13482 FloatModeKind ExplicitType) const {
13483 FloatModeKind Ty =
13484 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13485 switch (Ty) {
13487 return HalfTy;
13489 return FloatTy;
13491 return DoubleTy;
13493 return LongDoubleTy;
13495 return Float128Ty;
13497 return Ibm128Ty;
13499 return {};
13500 }
13501
13502 llvm_unreachable("Unhandled TargetInfo::RealType value");
13503}
13504
13505void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13506 if (Number <= 1)
13507 return;
13508
13509 MangleNumbers[ND] = Number;
13510
13511 if (Listener)
13512 Listener->AddedManglingNumber(ND, Number);
13513}
13514
13516 bool ForAuxTarget) const {
13517 auto I = MangleNumbers.find(ND);
13518 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13519 // CUDA/HIP host compilation encodes host and device mangling numbers
13520 // as lower and upper half of 32 bit integer.
13521 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13522 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13523 } else {
13524 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13525 "number for aux target");
13526 }
13527 return Res > 1 ? Res : 1;
13528}
13529
13530void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13531 if (Number <= 1)
13532 return;
13533
13534 StaticLocalNumbers[VD] = Number;
13535
13536 if (Listener)
13537 Listener->AddedStaticLocalNumbers(VD, Number);
13538}
13539
13541 auto I = StaticLocalNumbers.find(VD);
13542 return I != StaticLocalNumbers.end() ? I->second : 1;
13543}
13544
13546 bool IsDestroying) {
13547 if (!IsDestroying) {
13548 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13549 return;
13550 }
13551 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13552}
13553
13555 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13556}
13557
13559 bool IsTypeAware) {
13560 if (!IsTypeAware) {
13561 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13562 return;
13563 }
13564 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13565}
13566
13568 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13569}
13570
13572 FunctionDecl *OperatorDelete,
13573 OperatorDeleteKind K) const {
13574 switch (K) {
13576 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13577 break;
13579 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13580 OperatorDelete;
13581 break;
13583 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13584 OperatorDelete;
13585 break;
13587 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13588 OperatorDelete;
13589 break;
13590 }
13591}
13592
13594 OperatorDeleteKind K) const {
13595 switch (K) {
13597 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13599 return GlobalOperatorDeletesForVirtualDtor.contains(
13600 Dtor->getCanonicalDecl());
13602 return ArrayOperatorDeletesForVirtualDtor.contains(
13603 Dtor->getCanonicalDecl());
13605 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13606 Dtor->getCanonicalDecl());
13607 }
13608 return false;
13609}
13610
13613 OperatorDeleteKind K) const {
13614 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13615 switch (K) {
13617 if (OperatorDeletesForVirtualDtor.contains(Canon))
13618 return OperatorDeletesForVirtualDtor[Canon];
13619 return nullptr;
13621 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13622 return GlobalOperatorDeletesForVirtualDtor[Canon];
13623 return nullptr;
13625 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13626 return ArrayOperatorDeletesForVirtualDtor[Canon];
13627 return nullptr;
13629 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13630 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13631 return nullptr;
13632 }
13633 return nullptr;
13634}
13635
13637 const CXXRecordDecl *RD) {
13638 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13639 return false;
13640
13641 return MaybeRequireVectorDeletingDtor.count(RD);
13642}
13643
13645 const CXXRecordDecl *RD) {
13646 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13647 return;
13648
13649 MaybeRequireVectorDeletingDtor.insert(RD);
13650}
13651
13654 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13655 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13656 if (!MCtx)
13658 return *MCtx;
13659}
13660
13663 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13664 std::unique_ptr<MangleNumberingContext> &MCtx =
13665 ExtraMangleNumberingContexts[D];
13666 if (!MCtx)
13668 return *MCtx;
13669}
13670
13671std::unique_ptr<MangleNumberingContext>
13673 return ABI->createMangleNumberingContext();
13674}
13675
13676const CXXConstructorDecl *
13678 return ABI->getCopyConstructorForExceptionObject(
13680}
13681
13683 CXXConstructorDecl *CD) {
13684 return ABI->addCopyConstructorForExceptionObject(
13687}
13688
13690 TypedefNameDecl *DD) {
13691 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13692}
13693
13696 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13697}
13698
13700 DeclaratorDecl *DD) {
13701 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13702}
13703
13705 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13706}
13707
13709 ParamIndices[D] = index;
13710}
13711
13713 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13714 assert(I != ParamIndices.end() &&
13715 "ParmIndices lacks entry set by ParmVarDecl");
13716 return I->second;
13717}
13718
13720 unsigned Length) const {
13721 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13722 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13723 EltTy = EltTy.withConst();
13724
13725 EltTy = adjustStringLiteralBaseType(EltTy);
13726
13727 // Get an array type for the string, according to C99 6.4.5. This includes
13728 // the null terminator character.
13729 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13730 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13731}
13732
13735 StringLiteral *&Result = StringLiteralCache[Key];
13736 if (!Result)
13738 *this, Key, StringLiteralKind::Ordinary,
13739 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13740 SourceLocation());
13741 return Result;
13742}
13743
13744MSGuidDecl *
13746 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13747
13748 llvm::FoldingSetNodeID ID;
13749 MSGuidDecl::Profile(ID, Parts);
13750
13751 void *InsertPos;
13752 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13753 return Existing;
13754
13755 QualType GUIDType = getMSGuidType().withConst();
13756 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13757 MSGuidDecls.InsertNode(New, InsertPos);
13758 return New;
13759}
13760
13763 const APValue &APVal) const {
13764 llvm::FoldingSetNodeID ID;
13766
13767 void *InsertPos;
13768 if (UnnamedGlobalConstantDecl *Existing =
13769 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13770 return Existing;
13771
13773 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13774 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13775 return New;
13776}
13777
13780 assert(T->isRecordType() && "template param object of unexpected type");
13781
13782 // C++ [temp.param]p8:
13783 // [...] a static storage duration object of type 'const T' [...]
13784 T.addConst();
13785
13786 llvm::FoldingSetNodeID ID;
13788
13789 void *InsertPos;
13790 if (TemplateParamObjectDecl *Existing =
13791 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13792 return Existing;
13793
13794 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13795 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13796 return New;
13797}
13798
13800 const llvm::Triple &T = getTargetInfo().getTriple();
13801 if (!T.isOSDarwin())
13802 return false;
13803
13804 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13805 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13806 return false;
13807
13808 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13809 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13810 uint64_t Size = sizeChars.getQuantity();
13811 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13812 unsigned Align = alignChars.getQuantity();
13813 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13814 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13815}
13816
13817bool
13819 const ObjCMethodDecl *MethodImpl) {
13820 // No point trying to match an unavailable/deprecated mothod.
13821 if (MethodDecl->hasAttr<UnavailableAttr>()
13822 || MethodDecl->hasAttr<DeprecatedAttr>())
13823 return false;
13824 if (MethodDecl->getObjCDeclQualifier() !=
13825 MethodImpl->getObjCDeclQualifier())
13826 return false;
13827 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13828 return false;
13829
13830 if (MethodDecl->param_size() != MethodImpl->param_size())
13831 return false;
13832
13833 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13834 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13835 EF = MethodDecl->param_end();
13836 IM != EM && IF != EF; ++IM, ++IF) {
13837 const ParmVarDecl *DeclVar = (*IF);
13838 const ParmVarDecl *ImplVar = (*IM);
13839 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13840 return false;
13841 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13842 return false;
13843 }
13844
13845 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13846}
13847
13849 LangAS AS;
13851 AS = LangAS::Default;
13852 else
13853 AS = QT->getPointeeType().getAddressSpace();
13854
13856}
13857
13860}
13861
13862bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13863 if (X == Y)
13864 return true;
13865 if (!X || !Y)
13866 return false;
13867 llvm::FoldingSetNodeID IDX, IDY;
13868 X->Profile(IDX, *this, /*Canonical=*/true);
13869 Y->Profile(IDY, *this, /*Canonical=*/true);
13870 return IDX == IDY;
13871}
13872
13873// The getCommon* helpers return, for given 'same' X and Y entities given as
13874// inputs, another entity which is also the 'same' as the inputs, but which
13875// is closer to the canonical form of the inputs, each according to a given
13876// criteria.
13877// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13878// the regular ones.
13879
13881 if (!declaresSameEntity(X, Y))
13882 return nullptr;
13883 for (const Decl *DX : X->redecls()) {
13884 // If we reach Y before reaching the first decl, that means X is older.
13885 if (DX == Y)
13886 return X;
13887 // If we reach the first decl, then Y is older.
13888 if (DX->isFirstDecl())
13889 return Y;
13890 }
13891 llvm_unreachable("Corrupt redecls chain");
13892}
13893
13894template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13895static T *getCommonDecl(T *X, T *Y) {
13896 return cast_or_null<T>(
13897 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13898 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13899}
13900
13901template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13902static T *getCommonDeclChecked(T *X, T *Y) {
13903 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13904 const_cast<Decl *>(cast<Decl>(Y))));
13905}
13906
13908 TemplateName Y,
13909 bool IgnoreDeduced = false) {
13910 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13911 return X;
13912 // FIXME: There are cases here where we could find a common template name
13913 // with more sugar. For example one could be a SubstTemplateTemplate*
13914 // replacing the other.
13915 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13916 if (CX.getAsVoidPointer() !=
13918 return TemplateName();
13919 return CX;
13920}
13921
13924 bool IgnoreDeduced) {
13925 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13926 assert(R.getAsVoidPointer() != nullptr);
13927 return R;
13928}
13929
13931 ArrayRef<QualType> Ys, bool Unqualified = false) {
13932 assert(Xs.size() == Ys.size());
13933 SmallVector<QualType, 8> Rs(Xs.size());
13934 for (size_t I = 0; I < Rs.size(); ++I)
13935 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13936 return Rs;
13937}
13938
13939template <class T>
13940static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13941 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13942 : SourceLocation();
13943}
13944
13946 const TemplateArgument &X,
13947 const TemplateArgument &Y) {
13948 if (X.getKind() != Y.getKind())
13949 return TemplateArgument();
13950
13951 switch (X.getKind()) {
13953 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13954 return TemplateArgument();
13955 return TemplateArgument(
13956 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13958 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13959 return TemplateArgument();
13960 return TemplateArgument(
13961 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13962 /*Unqualified=*/true);
13964 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13965 return TemplateArgument();
13966 // FIXME: Try to keep the common sugar.
13967 return X;
13969 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13970 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13971 if (!CTN.getAsVoidPointer())
13972 return TemplateArgument();
13973 return TemplateArgument(CTN);
13974 }
13976 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13978 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13979 if (!CTN.getAsVoidPointer())
13980 return TemplateName();
13981 auto NExpX = X.getNumTemplateExpansions();
13982 assert(NExpX == Y.getNumTemplateExpansions());
13983 return TemplateArgument(CTN, NExpX);
13984 }
13985 default:
13986 // FIXME: Handle the other argument kinds.
13987 return X;
13988 }
13989}
13990
13995 if (Xs.size() != Ys.size())
13996 return true;
13997 R.resize(Xs.size());
13998 for (size_t I = 0; I < R.size(); ++I) {
13999 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14000 if (R[I].isNull())
14001 return true;
14002 }
14003 return false;
14004}
14005
14010 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14011 assert(!Different);
14012 (void)Different;
14013 return R;
14014}
14015
14016template <class T>
14018 bool IsSame) {
14019 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14020 if (KX == KY)
14021 return KX;
14023 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14024 return KX;
14025}
14026
14027/// Returns a NestedNameSpecifier which has only the common sugar
14028/// present in both NNS1 and NNS2.
14031 NestedNameSpecifier NNS2, bool IsSame) {
14032 // If they are identical, all sugar is common.
14033 if (NNS1 == NNS2)
14034 return NNS1;
14035
14036 // IsSame implies both Qualifiers are equivalent.
14037 NestedNameSpecifier Canon = NNS1.getCanonical();
14038 if (Canon != NNS2.getCanonical()) {
14039 assert(!IsSame && "Should be the same NestedNameSpecifier");
14040 // If they are not the same, there is nothing to unify.
14041 return std::nullopt;
14042 }
14043
14044 NestedNameSpecifier R = std::nullopt;
14045 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14046 assert(Kind == NNS2.getKind());
14047 switch (Kind) {
14049 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14050 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14051 auto Kind = Namespace1->getKind();
14052 if (Kind != Namespace2->getKind() ||
14053 (Kind == Decl::NamespaceAlias &&
14054 !declaresSameEntity(Namespace1, Namespace2))) {
14056 Ctx,
14057 ::getCommonDeclChecked(Namespace1->getNamespace(),
14058 Namespace2->getNamespace()),
14059 /*Prefix=*/std::nullopt);
14060 break;
14061 }
14062 // The prefixes for namespaces are not significant, its declaration
14063 // identifies it uniquely.
14064 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14065 /*IsSame=*/false);
14066 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14067 Prefix);
14068 break;
14069 }
14071 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14072 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14073 /*Unqualified=*/true)
14074 .getTypePtr();
14075 R = NestedNameSpecifier(T);
14076 break;
14077 }
14079 // FIXME: Can __super even be used with data members?
14080 // If it's only usable in functions, we will never see it here,
14081 // unless we save the qualifiers used in function types.
14082 // In that case, it might be possible NNS2 is a type,
14083 // in which case we should degrade the result to
14084 // a CXXRecordType.
14086 NNS2.getAsMicrosoftSuper()));
14087 break;
14088 }
14091 // These are singletons.
14092 llvm_unreachable("singletons did not compare equal");
14093 }
14094 assert(R.getCanonical() == Canon);
14095 return R;
14096}
14097
14098template <class T>
14100 const T *Y, bool IsSame) {
14101 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14102}
14103
14104template <class T>
14105static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14106 const T *Y) {
14107 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14108}
14109
14111 QualType X, QualType Y,
14112 Qualifiers &QX,
14113 Qualifiers &QY) {
14114 QualType R = Ctx.getCommonSugaredType(X, Y,
14115 /*Unqualified=*/true);
14116 // Qualifiers common to both element types.
14117 Qualifiers RQ = R.getQualifiers();
14118 // For each side, move to the top level any qualifiers which are not common to
14119 // both element types. The caller must assume top level qualifiers might
14120 // be different, even if they are the same type, and can be treated as sugar.
14121 QX += X.getQualifiers() - RQ;
14122 QY += Y.getQualifiers() - RQ;
14123 return R;
14124}
14125
14126template <class T>
14128 Qualifiers &QX, const T *Y,
14129 Qualifiers &QY) {
14130 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14131 Y->getElementType(), QX, QY);
14132}
14133
14134template <class T>
14135static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14136 const T *Y) {
14137 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14138}
14139
14140template <class T>
14141static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14142 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14143 return X->getSizeExpr();
14144}
14145
14146static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14147 assert(X->getSizeModifier() == Y->getSizeModifier());
14148 return X->getSizeModifier();
14149}
14150
14152 const ArrayType *Y) {
14153 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14154 return X->getIndexTypeCVRQualifiers();
14155}
14156
14157// Merges two type lists such that the resulting vector will contain
14158// each type (in a canonical sense) only once, in the order they appear
14159// from X to Y. If they occur in both X and Y, the result will contain
14160// the common sugared type between them.
14161static void mergeTypeLists(const ASTContext &Ctx,
14164 llvm::DenseMap<QualType, unsigned> Found;
14165 for (auto Ts : {X, Y}) {
14166 for (QualType T : Ts) {
14167 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14168 if (!Res.second) {
14169 QualType &U = Out[Res.first->second];
14170 U = Ctx.getCommonSugaredType(U, T);
14171 } else {
14172 Out.emplace_back(T);
14173 }
14174 }
14175 }
14176}
14177
14178FunctionProtoType::ExceptionSpecInfo
14181 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14182 bool AcceptDependent) const {
14183 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14184
14185 // If either of them can throw anything, that is the result.
14186 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14187 if (EST1 == I)
14188 return ESI1;
14189 if (EST2 == I)
14190 return ESI2;
14191 }
14192
14193 // If either of them is non-throwing, the result is the other.
14194 for (auto I :
14196 if (EST1 == I)
14197 return ESI2;
14198 if (EST2 == I)
14199 return ESI1;
14200 }
14201
14202 // If we're left with value-dependent computed noexcept expressions, we're
14203 // stuck. Before C++17, we can just drop the exception specification entirely,
14204 // since it's not actually part of the canonical type. And this should never
14205 // happen in C++17, because it would mean we were computing the composite
14206 // pointer type of dependent types, which should never happen.
14207 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14208 assert(AcceptDependent &&
14209 "computing composite pointer type of dependent types");
14211 }
14212
14213 // Switch over the possibilities so that people adding new values know to
14214 // update this function.
14215 switch (EST1) {
14216 case EST_None:
14217 case EST_DynamicNone:
14218 case EST_MSAny:
14219 case EST_BasicNoexcept:
14221 case EST_NoexceptFalse:
14222 case EST_NoexceptTrue:
14223 case EST_NoThrow:
14224 llvm_unreachable("These ESTs should be handled above");
14225
14226 case EST_Dynamic: {
14227 // This is the fun case: both exception specifications are dynamic. Form
14228 // the union of the two lists.
14229 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14230 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14231 ESI2.Exceptions);
14233 Result.Exceptions = ExceptionTypeStorage;
14234 return Result;
14235 }
14236
14237 case EST_Unevaluated:
14238 case EST_Uninstantiated:
14239 case EST_Unparsed:
14240 llvm_unreachable("shouldn't see unresolved exception specifications here");
14241 }
14242
14243 llvm_unreachable("invalid ExceptionSpecificationType");
14244}
14245
14247 Qualifiers &QX, const Type *Y,
14248 Qualifiers &QY) {
14249 Type::TypeClass TC = X->getTypeClass();
14250 assert(TC == Y->getTypeClass());
14251 switch (TC) {
14252#define UNEXPECTED_TYPE(Class, Kind) \
14253 case Type::Class: \
14254 llvm_unreachable("Unexpected " Kind ": " #Class);
14255
14256#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14257#define TYPE(Class, Base)
14258#include "clang/AST/TypeNodes.inc"
14259
14260#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14262 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14263 SUGAR_FREE_TYPE(DependentBitInt)
14265 SUGAR_FREE_TYPE(ObjCInterface)
14266 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14267 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14268 SUGAR_FREE_TYPE(UnresolvedUsing)
14269 SUGAR_FREE_TYPE(HLSLAttributedResource)
14270 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14271#undef SUGAR_FREE_TYPE
14272#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14273 NON_UNIQUE_TYPE(TypeOfExpr)
14274 NON_UNIQUE_TYPE(VariableArray)
14275#undef NON_UNIQUE_TYPE
14276
14277 UNEXPECTED_TYPE(TypeOf, "sugar")
14278
14279#undef UNEXPECTED_TYPE
14280
14281 case Type::Auto: {
14282 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14283 assert(AX->getDeducedKind() == AY->getDeducedKind());
14284 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14285 assert(AX->getKeyword() == AY->getKeyword());
14286 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14287 AY->getTypeConstraintConcept());
14289 if (CD &&
14290 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14291 AY->getTypeConstraintArguments())) {
14292 CD = nullptr; // The arguments differ, so make it unconstrained.
14293 As.clear();
14294 }
14295 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14296 CD, As);
14297 }
14298 case Type::IncompleteArray: {
14299 const auto *AX = cast<IncompleteArrayType>(X),
14301 return Ctx.getIncompleteArrayType(
14302 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14304 }
14305 case Type::DependentSizedArray: {
14306 const auto *AX = cast<DependentSizedArrayType>(X),
14308 return Ctx.getDependentSizedArrayType(
14309 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14310 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14312 }
14313 case Type::ConstantArray: {
14314 const auto *AX = cast<ConstantArrayType>(X),
14315 *AY = cast<ConstantArrayType>(Y);
14316 assert(AX->getSize() == AY->getSize());
14317 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14318 ? AX->getSizeExpr()
14319 : nullptr;
14320 return Ctx.getConstantArrayType(
14321 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14323 }
14324 case Type::ArrayParameter: {
14325 const auto *AX = cast<ArrayParameterType>(X),
14326 *AY = cast<ArrayParameterType>(Y);
14327 assert(AX->getSize() == AY->getSize());
14328 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14329 ? AX->getSizeExpr()
14330 : nullptr;
14331 auto ArrayTy = Ctx.getConstantArrayType(
14332 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14334 return Ctx.getArrayParameterType(ArrayTy);
14335 }
14336 case Type::Atomic: {
14337 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14338 return Ctx.getAtomicType(
14339 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14340 }
14341 case Type::Complex: {
14342 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14343 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14344 }
14345 case Type::Pointer: {
14346 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14347 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14348 }
14349 case Type::BlockPointer: {
14350 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14351 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14352 }
14353 case Type::ObjCObjectPointer: {
14354 const auto *PX = cast<ObjCObjectPointerType>(X),
14356 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14357 }
14358 case Type::MemberPointer: {
14359 const auto *PX = cast<MemberPointerType>(X),
14360 *PY = cast<MemberPointerType>(Y);
14361 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14362 PY->getMostRecentCXXRecordDecl()));
14363 return Ctx.getMemberPointerType(
14364 getCommonPointeeType(Ctx, PX, PY),
14365 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14366 PX->getMostRecentCXXRecordDecl());
14367 }
14368 case Type::LValueReference: {
14369 const auto *PX = cast<LValueReferenceType>(X),
14371 // FIXME: Preserve PointeeTypeAsWritten.
14372 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14373 PX->isSpelledAsLValue() ||
14374 PY->isSpelledAsLValue());
14375 }
14376 case Type::RValueReference: {
14377 const auto *PX = cast<RValueReferenceType>(X),
14379 // FIXME: Preserve PointeeTypeAsWritten.
14380 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14381 }
14382 case Type::DependentAddressSpace: {
14383 const auto *PX = cast<DependentAddressSpaceType>(X),
14385 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14386 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14387 PX->getAddrSpaceExpr(),
14388 getCommonAttrLoc(PX, PY));
14389 }
14390 case Type::FunctionNoProto: {
14391 const auto *FX = cast<FunctionNoProtoType>(X),
14393 assert(FX->getExtInfo() == FY->getExtInfo());
14394 return Ctx.getFunctionNoProtoType(
14395 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14396 FX->getExtInfo());
14397 }
14398 case Type::FunctionProto: {
14399 const auto *FX = cast<FunctionProtoType>(X),
14400 *FY = cast<FunctionProtoType>(Y);
14401 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14402 EPIY = FY->getExtProtoInfo();
14403 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14404 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14405 assert(!EPIX.ExtParameterInfos ||
14406 llvm::equal(
14407 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14408 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14409 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14410 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14411 assert(EPIX.Variadic == EPIY.Variadic);
14412
14413 // FIXME: Can we handle an empty EllipsisLoc?
14414 // Use emtpy EllipsisLoc if X and Y differ.
14415
14416 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14417
14418 QualType R =
14419 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14420 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14421 /*Unqualified=*/true);
14422
14423 SmallVector<QualType, 8> Exceptions;
14425 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14426 return Ctx.getFunctionType(R, P, EPIX);
14427 }
14428 case Type::ObjCObject: {
14429 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14430 assert(
14431 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14432 OY->getProtocols().begin(), OY->getProtocols().end(),
14433 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14434 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14435 }) &&
14436 "protocol lists must be the same");
14437 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14438 OY->getTypeArgsAsWritten());
14439 return Ctx.getObjCObjectType(
14440 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14441 OX->getProtocols(),
14442 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14443 }
14444 case Type::ConstantMatrix: {
14445 const auto *MX = cast<ConstantMatrixType>(X),
14446 *MY = cast<ConstantMatrixType>(Y);
14447 assert(MX->getNumRows() == MY->getNumRows());
14448 assert(MX->getNumColumns() == MY->getNumColumns());
14449 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14450 MX->getNumRows(), MX->getNumColumns());
14451 }
14452 case Type::DependentSizedMatrix: {
14453 const auto *MX = cast<DependentSizedMatrixType>(X),
14455 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14456 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14457 return Ctx.getDependentSizedMatrixType(
14458 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14459 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14460 }
14461 case Type::Vector: {
14462 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14463 assert(VX->getNumElements() == VY->getNumElements());
14464 assert(VX->getVectorKind() == VY->getVectorKind());
14465 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14466 VX->getNumElements(), VX->getVectorKind());
14467 }
14468 case Type::ExtVector: {
14469 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14470 assert(VX->getNumElements() == VY->getNumElements());
14471 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14472 VX->getNumElements());
14473 }
14474 case Type::DependentSizedExtVector: {
14475 const auto *VX = cast<DependentSizedExtVectorType>(X),
14478 getCommonSizeExpr(Ctx, VX, VY),
14479 getCommonAttrLoc(VX, VY));
14480 }
14481 case Type::DependentVector: {
14482 const auto *VX = cast<DependentVectorType>(X),
14484 assert(VX->getVectorKind() == VY->getVectorKind());
14485 return Ctx.getDependentVectorType(
14486 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14487 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14488 }
14489 case Type::Enum:
14490 case Type::Record:
14491 case Type::InjectedClassName: {
14492 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14493 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14494 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14495 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14496 /*OwnedTag=*/false);
14497 }
14498 case Type::TemplateSpecialization: {
14499 const auto *TX = cast<TemplateSpecializationType>(X),
14501 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14502 TY->template_arguments());
14504 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14505 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14506 TY->getTemplateName(),
14507 /*IgnoreDeduced=*/true),
14508 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14509 }
14510 case Type::Decltype: {
14511 const auto *DX = cast<DecltypeType>(X);
14512 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14513 assert(DX->isDependentType());
14514 assert(DY->isDependentType());
14515 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14516 // As Decltype is not uniqued, building a common type would be wasteful.
14517 return QualType(DX, 0);
14518 }
14519 case Type::PackIndexing: {
14520 const auto *DX = cast<PackIndexingType>(X);
14521 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14522 assert(DX->isDependentType());
14523 assert(DY->isDependentType());
14524 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14525 return QualType(DX, 0);
14526 }
14527 case Type::DependentName: {
14528 const auto *NX = cast<DependentNameType>(X),
14529 *NY = cast<DependentNameType>(Y);
14530 assert(NX->getIdentifier() == NY->getIdentifier());
14531 return Ctx.getDependentNameType(
14532 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14533 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14534 }
14535 case Type::OverflowBehavior: {
14536 const auto *NX = cast<OverflowBehaviorType>(X),
14538 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14539 return Ctx.getOverflowBehaviorType(
14540 NX->getBehaviorKind(),
14541 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14542 NY->getUnderlyingType(), QX, QY));
14543 }
14544 case Type::UnaryTransform: {
14545 const auto *TX = cast<UnaryTransformType>(X),
14546 *TY = cast<UnaryTransformType>(Y);
14547 assert(TX->getUTTKind() == TY->getUTTKind());
14548 return Ctx.getUnaryTransformType(
14549 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14550 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14551 TY->getUnderlyingType()),
14552 TX->getUTTKind());
14553 }
14554 case Type::PackExpansion: {
14555 const auto *PX = cast<PackExpansionType>(X),
14556 *PY = cast<PackExpansionType>(Y);
14557 assert(PX->getNumExpansions() == PY->getNumExpansions());
14558 return Ctx.getPackExpansionType(
14559 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14560 PX->getNumExpansions(), false);
14561 }
14562 case Type::Pipe: {
14563 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14564 assert(PX->isReadOnly() == PY->isReadOnly());
14565 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14567 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14568 }
14569 case Type::TemplateTypeParm: {
14570 const auto *TX = cast<TemplateTypeParmType>(X),
14572 assert(TX->getDepth() == TY->getDepth());
14573 assert(TX->getIndex() == TY->getIndex());
14574 assert(TX->isParameterPack() == TY->isParameterPack());
14575 return Ctx.getTemplateTypeParmType(
14576 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14577 getCommonDecl(TX->getDecl(), TY->getDecl()));
14578 }
14579 }
14580 llvm_unreachable("Unknown Type Class");
14581}
14582
14584 const Type *Y,
14585 SplitQualType Underlying) {
14586 Type::TypeClass TC = X->getTypeClass();
14587 if (TC != Y->getTypeClass())
14588 return QualType();
14589 switch (TC) {
14590#define UNEXPECTED_TYPE(Class, Kind) \
14591 case Type::Class: \
14592 llvm_unreachable("Unexpected " Kind ": " #Class);
14593#define TYPE(Class, Base)
14594#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14595#include "clang/AST/TypeNodes.inc"
14596
14597#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14600 CANONICAL_TYPE(BlockPointer)
14603 CANONICAL_TYPE(ConstantArray)
14604 CANONICAL_TYPE(ArrayParameter)
14605 CANONICAL_TYPE(ConstantMatrix)
14607 CANONICAL_TYPE(ExtVector)
14608 CANONICAL_TYPE(FunctionNoProto)
14609 CANONICAL_TYPE(FunctionProto)
14610 CANONICAL_TYPE(IncompleteArray)
14611 CANONICAL_TYPE(HLSLAttributedResource)
14612 CANONICAL_TYPE(HLSLInlineSpirv)
14613 CANONICAL_TYPE(LValueReference)
14614 CANONICAL_TYPE(ObjCInterface)
14615 CANONICAL_TYPE(ObjCObject)
14616 CANONICAL_TYPE(ObjCObjectPointer)
14617 CANONICAL_TYPE(OverflowBehavior)
14621 CANONICAL_TYPE(RValueReference)
14622 CANONICAL_TYPE(VariableArray)
14624#undef CANONICAL_TYPE
14625
14626#undef UNEXPECTED_TYPE
14627
14628 case Type::Adjusted: {
14629 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14630 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14631 if (!Ctx.hasSameType(OX, OY))
14632 return QualType();
14633 // FIXME: It's inefficient to have to unify the original types.
14634 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14635 Ctx.getQualifiedType(Underlying));
14636 }
14637 case Type::Decayed: {
14638 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14639 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14640 if (!Ctx.hasSameType(OX, OY))
14641 return QualType();
14642 // FIXME: It's inefficient to have to unify the original types.
14643 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14644 Ctx.getQualifiedType(Underlying));
14645 }
14646 case Type::Attributed: {
14647 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14648 AttributedType::Kind Kind = AX->getAttrKind();
14649 if (Kind != AY->getAttrKind())
14650 return QualType();
14651 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14652 if (!Ctx.hasSameType(MX, MY))
14653 return QualType();
14654 // FIXME: It's inefficient to have to unify the modified types.
14655 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14656 Ctx.getQualifiedType(Underlying),
14657 AX->getAttr());
14658 }
14659 case Type::BTFTagAttributed: {
14660 const auto *BX = cast<BTFTagAttributedType>(X);
14661 const BTFTypeTagAttr *AX = BX->getAttr();
14662 // The attribute is not uniqued, so just compare the tag.
14663 if (AX->getBTFTypeTag() !=
14664 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14665 return QualType();
14666 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14667 }
14668 case Type::Auto: {
14669 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14670 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14671 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14672
14673 AutoTypeKeyword KW = AX->getKeyword();
14674 if (KW != AY->getKeyword())
14675 return QualType();
14676
14677 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14678 AY->getTypeConstraintConcept());
14680 if (CD &&
14681 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14682 AY->getTypeConstraintArguments())) {
14683 CD = nullptr; // The arguments differ, so make it unconstrained.
14684 As.clear();
14685 }
14686
14687 // Both auto types can't be dependent, otherwise they wouldn't have been
14688 // sugar. This implies they can't contain unexpanded packs either.
14690 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14691 CD, As);
14692 }
14693 case Type::PackIndexing:
14694 case Type::Decltype:
14695 return QualType();
14696 case Type::DeducedTemplateSpecialization:
14697 // FIXME: Try to merge these.
14698 return QualType();
14699 case Type::MacroQualified: {
14700 const auto *MX = cast<MacroQualifiedType>(X),
14701 *MY = cast<MacroQualifiedType>(Y);
14702 const IdentifierInfo *IX = MX->getMacroIdentifier();
14703 if (IX != MY->getMacroIdentifier())
14704 return QualType();
14705 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14706 }
14707 case Type::SubstTemplateTypeParm: {
14708 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14710 Decl *CD =
14711 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14712 if (!CD)
14713 return QualType();
14714 unsigned Index = SX->getIndex();
14715 if (Index != SY->getIndex())
14716 return QualType();
14717 auto PackIndex = SX->getPackIndex();
14718 if (PackIndex != SY->getPackIndex())
14719 return QualType();
14720 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14721 CD, Index, PackIndex,
14722 SX->getFinal() && SY->getFinal());
14723 }
14724 case Type::ObjCTypeParam:
14725 // FIXME: Try to merge these.
14726 return QualType();
14727 case Type::Paren:
14728 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14729
14730 case Type::TemplateSpecialization: {
14731 const auto *TX = cast<TemplateSpecializationType>(X),
14733 TemplateName CTN =
14734 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14735 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14736 if (!CTN.getAsVoidPointer())
14737 return QualType();
14739 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14740 TY->template_arguments()))
14741 return QualType();
14743 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14744 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14745 }
14746 case Type::Typedef: {
14747 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14748 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14749 if (!CD)
14750 return QualType();
14751 return Ctx.getTypedefType(
14752 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14753 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14754 Ctx.getQualifiedType(Underlying));
14755 }
14756 case Type::TypeOf: {
14757 // The common sugar between two typeof expressions, where one is
14758 // potentially a typeof_unqual and the other is not, we unify to the
14759 // qualified type as that retains the most information along with the type.
14760 // We only return a typeof_unqual type when both types are unqual types.
14765 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14766 }
14767 case Type::TypeOfExpr:
14768 return QualType();
14769
14770 case Type::UnaryTransform: {
14771 const auto *UX = cast<UnaryTransformType>(X),
14772 *UY = cast<UnaryTransformType>(Y);
14773 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14774 if (KX != UY->getUTTKind())
14775 return QualType();
14776 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14777 if (!Ctx.hasSameType(BX, BY))
14778 return QualType();
14779 // FIXME: It's inefficient to have to unify the base types.
14780 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14781 Ctx.getQualifiedType(Underlying), KX);
14782 }
14783 case Type::Using: {
14784 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14785 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14786 if (!CD)
14787 return QualType();
14788 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14789 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14790 CD, Ctx.getQualifiedType(Underlying));
14791 }
14792 case Type::MemberPointer: {
14793 const auto *PX = cast<MemberPointerType>(X),
14794 *PY = cast<MemberPointerType>(Y);
14795 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14796 assert(Cls == PY->getMostRecentCXXRecordDecl());
14797 return Ctx.getMemberPointerType(
14798 ::getCommonPointeeType(Ctx, PX, PY),
14799 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14800 }
14801 case Type::CountAttributed: {
14802 const auto *DX = cast<CountAttributedType>(X),
14804 if (DX->isCountInBytes() != DY->isCountInBytes())
14805 return QualType();
14806 if (DX->isOrNull() != DY->isOrNull())
14807 return QualType();
14808 Expr *CEX = DX->getCountExpr();
14809 Expr *CEY = DY->getCountExpr();
14810 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14811 if (Ctx.hasSameExpr(CEX, CEY))
14812 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14813 DX->isCountInBytes(), DX->isOrNull(),
14814 CDX);
14815 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14816 return QualType();
14817 // Two declarations with the same integer constant may still differ in their
14818 // expression pointers, so we need to evaluate them.
14819 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14820 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14821 if (VX != VY)
14822 return QualType();
14823 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14824 DX->isCountInBytes(), DX->isOrNull(),
14825 CDX);
14826 }
14827 case Type::PredefinedSugar:
14828 assert(cast<PredefinedSugarType>(X)->getKind() !=
14830 return QualType();
14831 }
14832 llvm_unreachable("Unhandled Type Class");
14833}
14834
14835static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14837 while (true) {
14838 QTotal.addConsistentQualifiers(T.Quals);
14840 if (NT == QualType(T.Ty, 0))
14841 break;
14842 R.push_back(T);
14843 T = NT.split();
14844 }
14845 return R;
14846}
14847
14849 bool Unqualified) const {
14850 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14851 if (X == Y)
14852 return X;
14853 if (!Unqualified) {
14854 if (X.isCanonical())
14855 return X;
14856 if (Y.isCanonical())
14857 return Y;
14858 }
14859
14860 SplitQualType SX = X.split(), SY = Y.split();
14861 Qualifiers QX, QY;
14862 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14863 // until we reach their underlying "canonical nodes". Note these are not
14864 // necessarily canonical types, as they may still have sugared properties.
14865 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14866 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14867
14868 // If this is an ArrayType, the element qualifiers are interchangeable with
14869 // the top level qualifiers.
14870 // * In case the canonical nodes are the same, the elements types are already
14871 // the same.
14872 // * Otherwise, the element types will be made the same, and any different
14873 // element qualifiers will be moved up to the top level qualifiers, per
14874 // 'getCommonArrayElementType'.
14875 // In both cases, this means there may be top level qualifiers which differ
14876 // between X and Y. If so, these differing qualifiers are redundant with the
14877 // element qualifiers, and can be removed without changing the canonical type.
14878 // The desired behaviour is the same as for the 'Unqualified' case here:
14879 // treat the redundant qualifiers as sugar, remove the ones which are not
14880 // common to both sides.
14881 bool KeepCommonQualifiers =
14883
14884 if (SX.Ty != SY.Ty) {
14885 // The canonical nodes differ. Build a common canonical node out of the two,
14886 // unifying their sugar. This may recurse back here.
14887 SX.Ty =
14888 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14889 } else {
14890 // The canonical nodes were identical: We may have desugared too much.
14891 // Add any common sugar back in.
14892 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14893 QX -= SX.Quals;
14894 QY -= SY.Quals;
14895 SX = Xs.pop_back_val();
14896 SY = Ys.pop_back_val();
14897 }
14898 }
14899 if (KeepCommonQualifiers)
14901 else
14902 assert(QX == QY);
14903
14904 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14905 // related. Walk up these nodes, unifying them and adding the result.
14906 while (!Xs.empty() && !Ys.empty()) {
14907 auto Underlying = SplitQualType(
14908 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14909 SX = Xs.pop_back_val();
14910 SY = Ys.pop_back_val();
14911 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14913 // Stop at the first pair which is unrelated.
14914 if (!SX.Ty) {
14915 SX.Ty = Underlying.Ty;
14916 break;
14917 }
14918 QX -= Underlying.Quals;
14919 };
14920
14921 // Add back the missing accumulated qualifiers, which were stripped off
14922 // with the sugar nodes we could not unify.
14923 QualType R = getQualifiedType(SX.Ty, QX);
14924 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14925 return R;
14926}
14927
14929 assert(Ty->isFixedPointType());
14930
14932 return Ty;
14933
14934 switch (Ty->castAs<BuiltinType>()->getKind()) {
14935 default:
14936 llvm_unreachable("Not a saturated fixed point type!");
14937 case BuiltinType::SatShortAccum:
14938 return ShortAccumTy;
14939 case BuiltinType::SatAccum:
14940 return AccumTy;
14941 case BuiltinType::SatLongAccum:
14942 return LongAccumTy;
14943 case BuiltinType::SatUShortAccum:
14944 return UnsignedShortAccumTy;
14945 case BuiltinType::SatUAccum:
14946 return UnsignedAccumTy;
14947 case BuiltinType::SatULongAccum:
14948 return UnsignedLongAccumTy;
14949 case BuiltinType::SatShortFract:
14950 return ShortFractTy;
14951 case BuiltinType::SatFract:
14952 return FractTy;
14953 case BuiltinType::SatLongFract:
14954 return LongFractTy;
14955 case BuiltinType::SatUShortFract:
14956 return UnsignedShortFractTy;
14957 case BuiltinType::SatUFract:
14958 return UnsignedFractTy;
14959 case BuiltinType::SatULongFract:
14960 return UnsignedLongFractTy;
14961 }
14962}
14963
14965 assert(Ty->isFixedPointType());
14966
14967 if (Ty->isSaturatedFixedPointType()) return Ty;
14968
14969 switch (Ty->castAs<BuiltinType>()->getKind()) {
14970 default:
14971 llvm_unreachable("Not a fixed point type!");
14972 case BuiltinType::ShortAccum:
14973 return SatShortAccumTy;
14974 case BuiltinType::Accum:
14975 return SatAccumTy;
14976 case BuiltinType::LongAccum:
14977 return SatLongAccumTy;
14978 case BuiltinType::UShortAccum:
14980 case BuiltinType::UAccum:
14981 return SatUnsignedAccumTy;
14982 case BuiltinType::ULongAccum:
14984 case BuiltinType::ShortFract:
14985 return SatShortFractTy;
14986 case BuiltinType::Fract:
14987 return SatFractTy;
14988 case BuiltinType::LongFract:
14989 return SatLongFractTy;
14990 case BuiltinType::UShortFract:
14992 case BuiltinType::UFract:
14993 return SatUnsignedFractTy;
14994 case BuiltinType::ULongFract:
14996 }
14997}
14998
15000 if (LangOpts.OpenCL)
15002
15003 if (LangOpts.CUDA)
15005
15006 return getLangASFromTargetAS(AS);
15007}
15008
15009// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15010// doesn't include ASTContext.h
15011template
15013 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15015 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15016 const clang::ASTContext &Ctx, Decl *Value);
15017
15019 assert(Ty->isFixedPointType());
15020
15021 const TargetInfo &Target = getTargetInfo();
15022 switch (Ty->castAs<BuiltinType>()->getKind()) {
15023 default:
15024 llvm_unreachable("Not a fixed point type!");
15025 case BuiltinType::ShortAccum:
15026 case BuiltinType::SatShortAccum:
15027 return Target.getShortAccumScale();
15028 case BuiltinType::Accum:
15029 case BuiltinType::SatAccum:
15030 return Target.getAccumScale();
15031 case BuiltinType::LongAccum:
15032 case BuiltinType::SatLongAccum:
15033 return Target.getLongAccumScale();
15034 case BuiltinType::UShortAccum:
15035 case BuiltinType::SatUShortAccum:
15036 return Target.getUnsignedShortAccumScale();
15037 case BuiltinType::UAccum:
15038 case BuiltinType::SatUAccum:
15039 return Target.getUnsignedAccumScale();
15040 case BuiltinType::ULongAccum:
15041 case BuiltinType::SatULongAccum:
15042 return Target.getUnsignedLongAccumScale();
15043 case BuiltinType::ShortFract:
15044 case BuiltinType::SatShortFract:
15045 return Target.getShortFractScale();
15046 case BuiltinType::Fract:
15047 case BuiltinType::SatFract:
15048 return Target.getFractScale();
15049 case BuiltinType::LongFract:
15050 case BuiltinType::SatLongFract:
15051 return Target.getLongFractScale();
15052 case BuiltinType::UShortFract:
15053 case BuiltinType::SatUShortFract:
15054 return Target.getUnsignedShortFractScale();
15055 case BuiltinType::UFract:
15056 case BuiltinType::SatUFract:
15057 return Target.getUnsignedFractScale();
15058 case BuiltinType::ULongFract:
15059 case BuiltinType::SatULongFract:
15060 return Target.getUnsignedLongFractScale();
15061 }
15062}
15063
15065 assert(Ty->isFixedPointType());
15066
15067 const TargetInfo &Target = getTargetInfo();
15068 switch (Ty->castAs<BuiltinType>()->getKind()) {
15069 default:
15070 llvm_unreachable("Not a fixed point type!");
15071 case BuiltinType::ShortAccum:
15072 case BuiltinType::SatShortAccum:
15073 return Target.getShortAccumIBits();
15074 case BuiltinType::Accum:
15075 case BuiltinType::SatAccum:
15076 return Target.getAccumIBits();
15077 case BuiltinType::LongAccum:
15078 case BuiltinType::SatLongAccum:
15079 return Target.getLongAccumIBits();
15080 case BuiltinType::UShortAccum:
15081 case BuiltinType::SatUShortAccum:
15082 return Target.getUnsignedShortAccumIBits();
15083 case BuiltinType::UAccum:
15084 case BuiltinType::SatUAccum:
15085 return Target.getUnsignedAccumIBits();
15086 case BuiltinType::ULongAccum:
15087 case BuiltinType::SatULongAccum:
15088 return Target.getUnsignedLongAccumIBits();
15089 case BuiltinType::ShortFract:
15090 case BuiltinType::SatShortFract:
15091 case BuiltinType::Fract:
15092 case BuiltinType::SatFract:
15093 case BuiltinType::LongFract:
15094 case BuiltinType::SatLongFract:
15095 case BuiltinType::UShortFract:
15096 case BuiltinType::SatUShortFract:
15097 case BuiltinType::UFract:
15098 case BuiltinType::SatUFract:
15099 case BuiltinType::ULongFract:
15100 case BuiltinType::SatULongFract:
15101 return 0;
15102 }
15103}
15104
15105llvm::FixedPointSemantics
15107 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15108 "Can only get the fixed point semantics for a "
15109 "fixed point or integer type.");
15110 if (Ty->isIntegerType())
15111 return llvm::FixedPointSemantics::GetIntegerSemantics(
15112 getIntWidth(Ty), Ty->isSignedIntegerType());
15113
15114 bool isSigned = Ty->isSignedFixedPointType();
15115 return llvm::FixedPointSemantics(
15116 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15118 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15119}
15120
15121llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15122 assert(Ty->isFixedPointType());
15123 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15124}
15125
15126llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15127 assert(Ty->isFixedPointType());
15128 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15129}
15130
15132 assert(Ty->isUnsignedFixedPointType() &&
15133 "Expected unsigned fixed point type");
15134
15135 switch (Ty->castAs<BuiltinType>()->getKind()) {
15136 case BuiltinType::UShortAccum:
15137 return ShortAccumTy;
15138 case BuiltinType::UAccum:
15139 return AccumTy;
15140 case BuiltinType::ULongAccum:
15141 return LongAccumTy;
15142 case BuiltinType::SatUShortAccum:
15143 return SatShortAccumTy;
15144 case BuiltinType::SatUAccum:
15145 return SatAccumTy;
15146 case BuiltinType::SatULongAccum:
15147 return SatLongAccumTy;
15148 case BuiltinType::UShortFract:
15149 return ShortFractTy;
15150 case BuiltinType::UFract:
15151 return FractTy;
15152 case BuiltinType::ULongFract:
15153 return LongFractTy;
15154 case BuiltinType::SatUShortFract:
15155 return SatShortFractTy;
15156 case BuiltinType::SatUFract:
15157 return SatFractTy;
15158 case BuiltinType::SatULongFract:
15159 return SatLongFractTy;
15160 default:
15161 llvm_unreachable("Unexpected unsigned fixed point type");
15162 }
15163}
15164
15165// Given a list of FMV features, return a concatenated list of the
15166// corresponding backend features (which may contain duplicates).
15167static std::vector<std::string> getFMVBackendFeaturesFor(
15168 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15169 std::vector<std::string> BackendFeats;
15170 llvm::AArch64::ExtensionSet FeatureBits;
15171 for (StringRef F : FMVFeatStrings)
15172 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15173 if (FMVExt->ID)
15174 FeatureBits.enable(*FMVExt->ID);
15175 FeatureBits.toLLVMFeatureList(BackendFeats);
15176 return BackendFeats;
15177}
15178
15179ParsedTargetAttr
15180ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15181 assert(TD != nullptr);
15182 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15183
15184 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15185 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15186 });
15187 return ParsedAttr;
15188}
15189
15190void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15191 const FunctionDecl *FD) const {
15192 if (FD)
15193 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15194 else
15195 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15196 Target->getTargetOpts().CPU,
15197 Target->getTargetOpts().Features);
15198}
15199
15200// Fills in the supplied string map with the set of target features for the
15201// passed in function.
15202void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15203 GlobalDecl GD) const {
15204 StringRef TargetCPU = Target->getTargetOpts().CPU;
15205 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15206 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15208
15209 // Make a copy of the features as passed on the command line into the
15210 // beginning of the additional features from the function to override.
15211 // AArch64 handles command line option features in parseTargetAttr().
15212 if (!Target->getTriple().isAArch64())
15213 ParsedAttr.Features.insert(
15214 ParsedAttr.Features.begin(),
15215 Target->getTargetOpts().FeaturesAsWritten.begin(),
15216 Target->getTargetOpts().FeaturesAsWritten.end());
15217
15218 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15219 TargetCPU = ParsedAttr.CPU;
15220
15221 // Now populate the feature map, first with the TargetCPU which is either
15222 // the default or a new one from the target attribute string. Then we'll use
15223 // the passed in features (FeaturesAsWritten) along with the new ones from
15224 // the attribute.
15225 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15226 ParsedAttr.Features);
15227 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15229 Target->getCPUSpecificCPUDispatchFeatures(
15230 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15231 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15232 Features.insert(Features.begin(),
15233 Target->getTargetOpts().FeaturesAsWritten.begin(),
15234 Target->getTargetOpts().FeaturesAsWritten.end());
15235 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15236 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15237 if (Target->getTriple().isAArch64()) {
15239 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15240 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15241 Features.insert(Features.begin(),
15242 Target->getTargetOpts().FeaturesAsWritten.begin(),
15243 Target->getTargetOpts().FeaturesAsWritten.end());
15244 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15245 } else if (Target->getTriple().isRISCV()) {
15246 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15247 std::vector<std::string> Features;
15248 if (VersionStr != "default") {
15249 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15250 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15251 ParsedAttr.Features.end());
15252 }
15253 Features.insert(Features.begin(),
15254 Target->getTargetOpts().FeaturesAsWritten.begin(),
15255 Target->getTargetOpts().FeaturesAsWritten.end());
15256 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15257 } else if (Target->getTriple().isOSAIX()) {
15258 std::vector<std::string> Features;
15259 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15260 if (VersionStr.starts_with("cpu="))
15261 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15262 else
15263 assert(VersionStr == "default");
15264 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15265 } else {
15266 std::vector<std::string> Features;
15267 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15268 if (VersionStr.starts_with("arch="))
15269 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15270 else if (VersionStr != "default")
15271 Features.push_back((StringRef{"+"} + VersionStr).str());
15272 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15273 }
15274 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15275 std::vector<std::string> Features;
15276 if (Target->getTriple().isRISCV()) {
15277 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15278 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15279 ParsedAttr.Features.end());
15280 } else {
15281 assert(Target->getTriple().isAArch64());
15283 TV->getFeatures(Feats);
15284 Features = getFMVBackendFeaturesFor(Feats);
15285 }
15286 Features.insert(Features.begin(),
15287 Target->getTargetOpts().FeaturesAsWritten.begin(),
15288 Target->getTargetOpts().FeaturesAsWritten.end());
15289 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15290 } else {
15291 FeatureMap = Target->getTargetOpts().FeatureMap;
15292 }
15293}
15294
15296 CanQualType KernelNameType,
15297 const FunctionDecl *FD) {
15298 // Host and device compilation may use different ABIs and different ABIs
15299 // may allocate name mangling discriminators differently. A discriminator
15300 // override is used to ensure consistent discriminator allocation across
15301 // host and device compilation.
15302 auto DeviceDiscriminatorOverrider =
15303 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15304 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15305 if (RD->isLambda())
15306 return RD->getDeviceLambdaManglingNumber();
15307 return std::nullopt;
15308 };
15309 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15310 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15311
15312 // Construct a mangled name for the SYCL kernel caller offload entry point.
15313 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15314 // name the SYCL kernel caller offload entry point function. This mangling
15315 // does not suffice to clearly identify symbols that correspond to SYCL
15316 // kernel caller functions, nor is this mangling natural for targets that
15317 // use a non-Itanium ABI.
15318 std::string Buffer;
15319 Buffer.reserve(128);
15320 llvm::raw_string_ostream Out(Buffer);
15321 MC->mangleCanonicalTypeName(KernelNameType, Out);
15322 std::string KernelName = Out.str();
15323
15324 return {KernelNameType, FD, KernelName};
15325}
15326
15328 // If the function declaration to register is invalid or dependent, the
15329 // registration attempt is ignored.
15330 if (FD->isInvalidDecl() || FD->isTemplated())
15331 return;
15332
15333 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15334 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15335
15336 // Be tolerant of multiple registration attempts so long as each attempt
15337 // is for the same entity. Callers are obligated to detect and diagnose
15338 // conflicting kernel names prior to calling this function.
15339 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15340 auto IT = SYCLKernels.find(KernelNameType);
15341 assert((IT == SYCLKernels.end() ||
15342 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15343 "SYCL kernel name conflict");
15344 (void)IT;
15345 SYCLKernels.insert(std::make_pair(
15346 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15347}
15348
15350 CanQualType KernelNameType = getCanonicalType(T);
15351 return SYCLKernels.at(KernelNameType);
15352}
15353
15355 CanQualType KernelNameType = getCanonicalType(T);
15356 auto IT = SYCLKernels.find(KernelNameType);
15357 if (IT != SYCLKernels.end())
15358 return &IT->second;
15359 return nullptr;
15360}
15361
15363 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15364 return *OMPTraitInfoVector.back();
15365}
15366
15369 const ASTContext::SectionInfo &Section) {
15370 if (Section.Decl)
15371 return DB << Section.Decl;
15372 return DB << "a prior #pragma section";
15373}
15374
15375bool ASTContext::mayExternalize(const Decl *D) const {
15376 bool IsInternalVar =
15377 isa<VarDecl>(D) &&
15379 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15380 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15381 (D->hasAttr<CUDAConstantAttr>() &&
15382 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15383 // CUDA/HIP: managed variables need to be externalized since it is
15384 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15385 // anonymous name space needs to be externalized to avoid duplicate symbols.
15386 return (IsInternalVar &&
15387 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15388 (D->hasAttr<CUDAGlobalAttr>() &&
15390 GVA_Internal);
15391}
15392
15394 return mayExternalize(D) &&
15395 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15397}
15398
15399StringRef ASTContext::getCUIDHash() const {
15400 if (!CUIDHash.empty())
15401 return CUIDHash;
15402 if (LangOpts.CUID.empty())
15403 return StringRef();
15404 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15405 return CUIDHash;
15406}
15407
15408const CXXRecordDecl *
15410 assert(ThisClass);
15411 assert(ThisClass->isPolymorphic());
15412 const CXXRecordDecl *PrimaryBase = ThisClass;
15413 while (1) {
15414 assert(PrimaryBase);
15415 assert(PrimaryBase->isPolymorphic());
15416 auto &Layout = getASTRecordLayout(PrimaryBase);
15417 auto Base = Layout.getPrimaryBase();
15418 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15419 break;
15420 PrimaryBase = Base;
15421 }
15422 return PrimaryBase;
15423}
15424
15426 StringRef MangledName) {
15427 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15428 assert(Method->isVirtual());
15429 bool DefaultIncludesPointerAuth =
15430 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15431
15432 if (!DefaultIncludesPointerAuth)
15433 return true;
15434
15435 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15436 if (Existing != ThunksToBeAbbreviated.end())
15437 return Existing->second.contains(MangledName.str());
15438
15439 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15440 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15441 auto VtableContext = getVTableContext();
15442 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15443 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15444 for (const auto &Thunk : *ThunkInfos) {
15445 SmallString<256> ElidedName;
15446 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15447 if (Destructor)
15448 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15449 Thunk, /* elideOverrideInfo */ true,
15450 ElidedNameStream);
15451 else
15452 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15453 ElidedNameStream);
15454 SmallString<256> MangledName;
15455 llvm::raw_svector_ostream mangledNameStream(MangledName);
15456 if (Destructor)
15457 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15458 Thunk, /* elideOverrideInfo */ false,
15459 mangledNameStream);
15460 else
15461 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15462 mangledNameStream);
15463
15464 Thunks[ElidedName].push_back(std::string(MangledName));
15465 }
15466 }
15467 llvm::StringSet<> SimplifiedThunkNames;
15468 for (auto &ThunkList : Thunks) {
15469 llvm::sort(ThunkList.second);
15470 SimplifiedThunkNames.insert(ThunkList.second[0]);
15471 }
15472 bool Result = SimplifiedThunkNames.contains(MangledName);
15473 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15474 return Result;
15475}
15476
15478 // Check for trivially-destructible here because non-trivially-destructible
15479 // types will always cause the type and any types derived from it to be
15480 // considered non-trivially-copyable. The same cannot be said for
15481 // trivially-copyable because deleting special members of a type derived from
15482 // a non-trivially-copyable type can cause the derived type to be considered
15483 // trivially copyable.
15484 if (getLangOpts().PointerFieldProtectionTagged)
15485 return !isa<CXXRecordDecl>(RD) ||
15486 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15487 return true;
15488}
15489
15490static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15491 std::vector<PFPField> &Fields, bool IncludeVBases) {
15492 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15493 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15494 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15495 for (unsigned i = 0; i != AT->getSize(); ++i)
15496 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15497 Fields, true);
15498 }
15499 }
15500 auto *Decl = Ty->getAsCXXRecordDecl();
15501 // isPFPType() is inherited from bases and members (including via arrays), so
15502 // we can early exit if it is false. Unions are excluded per the API
15503 // documentation.
15504 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15505 return;
15506 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15507 for (FieldDecl *Field : Decl->fields()) {
15508 CharUnits FieldOffset =
15509 Offset +
15510 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15511 if (Ctx.isPFPField(Field))
15512 Fields.push_back({FieldOffset, Field});
15513 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15514 /*IncludeVBases=*/true);
15515 }
15516 // Pass false for IncludeVBases below because vbases are only included in
15517 // layout for top-level types, i.e. not bases or vbases.
15518 for (CXXBaseSpecifier &Base : Decl->bases()) {
15519 if (Base.isVirtual())
15520 continue;
15521 CharUnits BaseOffset =
15522 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15523 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15524 /*IncludeVBases=*/false);
15525 }
15526 if (IncludeVBases) {
15527 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15528 CharUnits BaseOffset =
15529 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15530 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15531 /*IncludeVBases=*/false);
15532 }
15533 }
15534}
15535
15536std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15537 std::vector<PFPField> PFPFields;
15538 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15539 return PFPFields;
15540}
15541
15543 return !findPFPFields(Ty).empty();
15544}
15545
15546bool ASTContext::isPFPField(const FieldDecl *FD) const {
15547 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15548 return RD->isPFPType() && FD->getType()->isPointerType() &&
15549 !FD->hasAttr<NoFieldProtectionAttr>();
15550 return false;
15551}
15552
15554 auto *FD = dyn_cast<FieldDecl>(VD);
15555 if (!FD)
15556 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15557 if (isPFPField(FD))
15559}
15560
15562 if (E->getNumComponents() == 0)
15563 return;
15564 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15565 if (Comp.getKind() != OffsetOfNode::Field)
15566 return;
15567 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15569}
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 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 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 bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
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 QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
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:474
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:2848
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::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:115
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
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.
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:1105
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1098
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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.
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.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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.
bool isPFPField(const FieldDecl *Field) const
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 getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
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.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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:802
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.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
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 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:803
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,...
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 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.
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)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:798
Builtin::Context & BuiltinInfo
Definition ASTContext.h:800
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:952
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:799
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:987
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 getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:918
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:582
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:801
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 arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
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:990
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
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:227
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
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:804
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.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
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.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:851
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:574
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...
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:996
CanQualType OCLSamplerTy
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:872
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
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
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 ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
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 classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
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:917
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
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.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
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
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.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
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.
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
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
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.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
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
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
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.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
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)
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
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:3539
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3560
Represents a loop initializing the elements of an array.
Definition Expr.h:5971
llvm::APInt getArraySize() const
Definition Expr.h:5993
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3942
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3772
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3786
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3790
QualType getElementType() const
Definition TypeBase.h:3784
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3794
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:6927
Expr * getPtr() const
Definition Expr.h:6958
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8235
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8283
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8300
unsigned getNumBits() const
Definition TypeBase.h:8295
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4689
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Pointer to a block type.
Definition TypeBase.h:3592
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3609
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:3214
Kind getKind() const
Definition TypeBase.h:3262
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:235
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2624
Represents a C++ destructor within a class.
Definition DeclCXX.h:2889
CXXDestructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2937
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2245
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
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3340
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3810
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3906
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3866
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3925
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3886
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4456
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4502
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4453
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3486
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3522
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3575
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool isFileContext() const
Definition DeclBase.h:2193
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2138
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:2115
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
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:341
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:561
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:867
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:997
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:850
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1062
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:931
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
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:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
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:4111
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4133
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8328
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4061
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4090
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4151
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4176
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4523
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4543
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:6302
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6307
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4277
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4302
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4028
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4246
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4260
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4144
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4201
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:3095
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:447
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:4229
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
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:3070
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:4068
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:437
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:1723
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1770
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5550
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:3175
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3278
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4754
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3260
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3411
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:4702
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:2015
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2704
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3764
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2936
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3893
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3749
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:4419
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2425
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:4080
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5325
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5747
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5785
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5157
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5191
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4935
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4951
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5861
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5664
unsigned getNumParams() const
Definition TypeBase.h:5635
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4030
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5670
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5830
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5826
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4664
CallingConv getCC() const
Definition TypeBase.h:4723
unsigned getRegParm() const
Definition TypeBase.h:4716
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4712
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4735
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4579
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4619
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
QualType getReturnType() const
Definition TypeBase.h:4893
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:5070
Represents a C array with an unspecified size.
Definition TypeBase.h:3959
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3976
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
@ 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.
@ PostDecrInWhile
while (count–)
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
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
A global _GUID constant.
Definition DeclCXX.h:4414
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4451
MSGuidDeclParts Parts
Definition DeclCXX.h:4416
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6236
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4408
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4401
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3746
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:246
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:329
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
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:340
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:317
bool isExternallyVisible() const
Definition Decl.h:433
Represent a C++ namespace.
Definition Decl.h:592
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3366
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
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)
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:7993
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:953
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:8049
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8130
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:960
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8124
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8206
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8086
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8107
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8061
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8101
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1854
qual_range quals() const
Definition TypeBase.h:8168
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8113
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
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2530
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2577
unsigned getNumComponents() const
Definition Expr.h:2585
Helper class for OffsetOfExpr.
Definition Expr.h:2424
@ Field
A field.
Definition Expr.h:2431
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:4363
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3352
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3366
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1805
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1869
QualType getOriginalType() const
Definition Decl.cpp:2968
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8266
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:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3393
PredefinedSugarKind Kind
Definition TypeBase.h:8342
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:1463
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8515
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2914
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8562
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1302
QualType withConst() const
Definition TypeBase.h:1165
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:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8452
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3623
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8504
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
bool isCanonical() const
Definition TypeBase.h:8488
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8435
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
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:3057
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8463
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:8371
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8378
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:3685
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:4342
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5248
bool hasFlexibleArrayMember() const
Definition Decl.h:4375
field_range fields() const
Definition Decl.h:4545
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5234
RecordDecl * getMostRecentDecl()
Definition Decl.h:4368
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5293
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4526
bool field_empty() const
Definition Decl.h:4553
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:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3649
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:1802
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:1188
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:3732
TagTypeKind TagKind
Definition Decl.h:3737
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3969
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4908
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4901
bool isUnion() const
Definition Decl.h:3943
TagKind getTagKind() const
Definition Decl.h:3932
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:227
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:859
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:752
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:334
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:343
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:348
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:357
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:339
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:352
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:506
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:408
IntType getSizeType() const
Definition TargetInfo.h:389
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:979
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:760
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:390
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...
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:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3528
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:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6268
A container of type source information.
Definition TypeBase.h:8402
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isVoidType() const
Definition TypeBase.h:9034
bool isObjCBuiltinType() const
Definition TypeBase.h:8898
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2724
bool isIncompleteArrayType() const
Definition TypeBase.h:8775
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2231
bool isFloat16Type() const
Definition TypeBase.h:9043
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:8771
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:2470
bool isArrayType() const
Definition TypeBase.h:8767
bool isCharType() const
Definition Type.cpp:2158
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition Type.cpp:523
bool isPointerType() const
Definition TypeBase.h:8668
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8783
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9078
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
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:9122
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8868
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2949
bool isBitIntType() const
Definition TypeBase.h:8943
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9094
bool isHalfType() const
Definition TypeBase.h:9038
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2453
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3169
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2328
@ SizeT
The "size_t" type.
Definition TypeBase.h:2322
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2325
bool isObjCIdType() const
Definition TypeBase.h:8880
bool isOverflowBehaviorType() const
Definition TypeBase.h:8839
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9118
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9314
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:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
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:9136
bool isVectorType() const
Definition TypeBase.h:8807
bool isObjCClassType() const
Definition TypeBase.h:8886
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2706
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2641
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
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:2285
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2459
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:655
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
bool isObjCRetainableType() const
Definition Type.cpp:5369
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5100
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3682
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5763
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
QualType getUnderlyingType() const
Definition Decl.h:3632
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6212
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Opcode getOpcode() const
Definition Expr.h:2283
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4471
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4499
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6073
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6110
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4053
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4118
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3808
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3415
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3479
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3479
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6150
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5583
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:926
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2823
bool hasInit() const
Definition Decl.cpp:2411
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:2474
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1298
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:1208
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1566
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1310
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2388
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:2792
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4016
Expr * getSizeExpr() const
Definition TypeBase.h:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4225
unsigned getNumElements() const
Definition TypeBase.h:4240
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4249
VectorKind getVectorKind() const
Definition TypeBase.h:4245
QualType getElementType() const
Definition TypeBase.h:4239
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:47
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:1825
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:213
@ OCLTK_ReserveID
Definition TargetInfo.h:220
@ OCLTK_Sampler
Definition TargetInfo.h:221
@ OCLTK_Pipe
Definition TargetInfo.h:218
@ OCLTK_ClkEvent
Definition TargetInfo.h:215
@ OCLTK_Event
Definition TargetInfo.h:216
@ OCLTK_Default
Definition TargetInfo.h:214
@ OCLTK_Queue
Definition TargetInfo.h:219
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8566
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ 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:125
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:258
@ SC_Static
Definition Specifiers.h:253
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
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:3769
OptionalUnsigned< unsigned > UnsignedOrNone
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5986
@ Struct
The "struct" keyword.
Definition TypeBase.h:5983
@ Class
The "class" keyword.
Definition TypeBase.h:5992
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:490
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1798
@ Deduced
The normal deduced case.
Definition TypeBase.h:1805
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1800
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1821
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:300
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ 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:4195
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4204
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4192
@ Generic
not a target-specific vector type
Definition TypeBase.h:4186
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4210
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4213
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4207
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:177
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:188
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:182
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:185
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5956
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5961
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5958
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5964
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5974
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
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6717
Expr * getCopyExpr() const
Definition Expr.h:6724
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:5414
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5416
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5419
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5422
Extra information about a function prototype.
Definition TypeBase.h:5442
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5488
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5447
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5492
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5481
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:3333
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:147
AlignRequirementKind AlignRequirement
Definition ASTContext.h:208
bool isAlignRequired()
Definition ASTContext.h:200
AlignRequirementKind AlignRequirement
Definition ASTContext.h:194
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