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 XRayFilter.reset();
947 NoSanitizeL.reset();
948}
949
951
952void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
953 TraversalScope = TopLevelDecls;
955}
956
957void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
958 Deallocations.push_back({Callback, Data});
959}
960
961void
965
967 llvm::errs() << "\n*** AST Context Stats:\n";
968 llvm::errs() << " " << Types.size() << " types total.\n";
969
970 unsigned counts[] = {
971#define TYPE(Name, Parent) 0,
972#define ABSTRACT_TYPE(Name, Parent)
973#include "clang/AST/TypeNodes.inc"
974 0 // Extra
975 };
976
977 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
978 Type *T = Types[i];
979 counts[(unsigned)T->getTypeClass()]++;
980 }
981
982 unsigned Idx = 0;
983 unsigned TotalBytes = 0;
984#define TYPE(Name, Parent) \
985 if (counts[Idx]) \
986 llvm::errs() << " " << counts[Idx] << " " << #Name \
987 << " types, " << sizeof(Name##Type) << " each " \
988 << "(" << counts[Idx] * sizeof(Name##Type) \
989 << " bytes)\n"; \
990 TotalBytes += counts[Idx] * sizeof(Name##Type); \
991 ++Idx;
992#define ABSTRACT_TYPE(Name, Parent)
993#include "clang/AST/TypeNodes.inc"
994
995 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
996
997 // Implicit special member functions.
998 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1000 << " implicit default constructors created\n";
1001 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1003 << " implicit copy constructors created\n";
1004 if (getLangOpts().CPlusPlus)
1005 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1007 << " implicit move constructors created\n";
1008 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1010 << " implicit copy assignment operators created\n";
1011 if (getLangOpts().CPlusPlus)
1012 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1014 << " implicit move assignment operators created\n";
1015 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1017 << " implicit destructors created\n";
1018
1019 if (ExternalSource) {
1020 llvm::errs() << "\n";
1021 ExternalSource->PrintStats();
1022 }
1023
1024 BumpAlloc.PrintStats();
1025}
1026
1028 bool NotifyListeners) {
1029 if (NotifyListeners)
1030 if (auto *Listener = getASTMutationListener();
1032 Listener->RedefinedHiddenDefinition(ND, M);
1033
1034 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1035}
1036
1038 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1039 if (It == MergedDefModules.end())
1040 return;
1041
1042 auto &Merged = It->second;
1043 llvm::DenseSet<Module*> Found;
1044 for (Module *&M : Merged)
1045 if (!Found.insert(M).second)
1046 M = nullptr;
1047 llvm::erase(Merged, nullptr);
1048}
1049
1052 auto MergedIt =
1053 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1054 if (MergedIt == MergedDefModules.end())
1055 return {};
1056 return MergedIt->second;
1057}
1058
1059void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1060 if (LazyInitializers.empty())
1061 return;
1062
1063 auto *Source = Ctx.getExternalSource();
1064 assert(Source && "lazy initializers but no external source");
1065
1066 auto LazyInits = std::move(LazyInitializers);
1067 LazyInitializers.clear();
1068
1069 for (auto ID : LazyInits)
1070 Initializers.push_back(Source->GetExternalDecl(ID));
1071
1072 assert(LazyInitializers.empty() &&
1073 "GetExternalDecl for lazy module initializer added more inits");
1074}
1075
1077 // One special case: if we add a module initializer that imports another
1078 // module, and that module's only initializer is an ImportDecl, simplify.
1079 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1080 auto It = ModuleInitializers.find(ID->getImportedModule());
1081
1082 // Maybe the ImportDecl does nothing at all. (Common case.)
1083 if (It == ModuleInitializers.end())
1084 return;
1085
1086 // Maybe the ImportDecl only imports another ImportDecl.
1087 auto &Imported = *It->second;
1088 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1089 Imported.resolve(*this);
1090 auto *OnlyDecl = Imported.Initializers.front();
1091 if (isa<ImportDecl>(OnlyDecl))
1092 D = OnlyDecl;
1093 }
1094 }
1095
1096 auto *&Inits = ModuleInitializers[M];
1097 if (!Inits)
1098 Inits = new (*this) PerModuleInitializers;
1099 Inits->Initializers.push_back(D);
1100}
1101
1104 auto *&Inits = ModuleInitializers[M];
1105 if (!Inits)
1106 Inits = new (*this) PerModuleInitializers;
1107 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1108 IDs.begin(), IDs.end());
1109}
1110
1112 auto It = ModuleInitializers.find(M);
1113 if (It == ModuleInitializers.end())
1114 return {};
1115
1116 auto *Inits = It->second;
1117 Inits->resolve(*this);
1118 return Inits->Initializers;
1119}
1120
1122 assert(M->isNamedModule());
1123 assert(!CurrentCXXNamedModule &&
1124 "We should set named module for ASTContext for only once");
1125 CurrentCXXNamedModule = M;
1126}
1127
1128bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1129 if (!M1 != !M2)
1130 return false;
1131
1132 /// Get the representative module for M. The representative module is the
1133 /// first module unit for a specific primary module name. So that the module
1134 /// units have the same representative module belongs to the same module.
1135 ///
1136 /// The process is helpful to reduce the expensive string operations.
1137 auto GetRepresentativeModule = [this](const Module *M) {
1138 auto Iter = SameModuleLookupSet.find(M);
1139 if (Iter != SameModuleLookupSet.end())
1140 return Iter->second;
1141
1142 const Module *RepresentativeModule =
1143 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1144 .first->second;
1145 SameModuleLookupSet[M] = RepresentativeModule;
1146 return RepresentativeModule;
1147 };
1148
1149 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1150 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1151}
1152
1154 if (!ExternCContext)
1155 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1156
1157 return ExternCContext;
1158}
1159
1170
1171#define BuiltinTemplate(BTName) \
1172 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1173 if (!Decl##BTName) \
1174 Decl##BTName = \
1175 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1176 return Decl##BTName; \
1177 }
1178#include "clang/Basic/BuiltinTemplates.inc"
1179
1181 RecordDecl::TagKind TK) const {
1182 SourceLocation Loc;
1183 RecordDecl *NewDecl;
1184 if (getLangOpts().CPlusPlus)
1185 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1186 Loc, &Idents.get(Name));
1187 else
1188 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1189 &Idents.get(Name));
1190 NewDecl->setImplicit();
1191 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1192 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1193 return NewDecl;
1194}
1195
1197 StringRef Name) const {
1200 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1201 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1202 NewDecl->setImplicit();
1203 return NewDecl;
1204}
1205
1207 if (!Int128Decl)
1208 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1209 return Int128Decl;
1210}
1211
1213 if (!UInt128Decl)
1214 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1215 return UInt128Decl;
1216}
1217
1218void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1219 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1221 Types.push_back(Ty);
1222}
1223
1225 const TargetInfo *AuxTarget) {
1226 assert((!this->Target || this->Target == &Target) &&
1227 "Incorrect target reinitialization");
1228 assert(VoidTy.isNull() && "Context reinitialized?");
1229
1230 this->Target = &Target;
1231 this->AuxTarget = AuxTarget;
1232
1233 ABI.reset(createCXXABI(Target));
1234 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1235
1236 // C99 6.2.5p19.
1237 InitBuiltinType(VoidTy, BuiltinType::Void);
1238
1239 // C99 6.2.5p2.
1240 InitBuiltinType(BoolTy, BuiltinType::Bool);
1241 // C99 6.2.5p3.
1242 if (LangOpts.CharIsSigned)
1243 InitBuiltinType(CharTy, BuiltinType::Char_S);
1244 else
1245 InitBuiltinType(CharTy, BuiltinType::Char_U);
1246 // C99 6.2.5p4.
1247 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1248 InitBuiltinType(ShortTy, BuiltinType::Short);
1249 InitBuiltinType(IntTy, BuiltinType::Int);
1250 InitBuiltinType(LongTy, BuiltinType::Long);
1251 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1252
1253 // C99 6.2.5p6.
1254 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1255 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1256 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1257 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1258 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1259
1260 // C99 6.2.5p10.
1261 InitBuiltinType(FloatTy, BuiltinType::Float);
1262 InitBuiltinType(DoubleTy, BuiltinType::Double);
1263 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1264
1265 // GNU extension, __float128 for IEEE quadruple precision
1266 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1267
1268 // __ibm128 for IBM extended precision
1269 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1270
1271 // C11 extension ISO/IEC TS 18661-3
1272 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1273
1274 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1275 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1276 InitBuiltinType(AccumTy, BuiltinType::Accum);
1277 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1278 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1279 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1280 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1281 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1282 InitBuiltinType(FractTy, BuiltinType::Fract);
1283 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1284 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1285 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1286 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1287 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1288 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1289 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1290 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1291 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1292 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1293 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1294 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1295 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1296 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1297 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1298 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1299
1300 // GNU extension, 128-bit integers.
1301 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1302 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1303
1304 // C++ 3.9.1p5
1305 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1306 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1307 else // -fshort-wchar makes wchar_t be unsigned.
1308 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1309 if (LangOpts.CPlusPlus && LangOpts.WChar)
1311 else {
1312 // C99 (or C++ using -fno-wchar).
1313 WideCharTy = getFromTargetType(Target.getWCharType());
1314 }
1315
1316 WIntTy = getFromTargetType(Target.getWIntType());
1317
1318 // C++20 (proposed)
1319 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1320
1321 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1322 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1323 else // C99
1324 Char16Ty = getFromTargetType(Target.getChar16Type());
1325
1326 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1327 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1328 else // C99
1329 Char32Ty = getFromTargetType(Target.getChar32Type());
1330
1331 // Placeholder type for type-dependent expressions whose type is
1332 // completely unknown. No code should ever check a type against
1333 // DependentTy and users should never see it; however, it is here to
1334 // help diagnose failures to properly check for type-dependent
1335 // expressions.
1336 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1337
1338 // Placeholder type for functions.
1339 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1340
1341 // Placeholder type for bound members.
1342 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1343
1344 // Placeholder type for unresolved templates.
1345 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1346
1347 // Placeholder type for pseudo-objects.
1348 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1349
1350 // "any" type; useful for debugger-like clients.
1351 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1352
1353 // Placeholder type for unbridged ARC casts.
1354 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1355
1356 // Placeholder type for builtin functions.
1357 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1358
1359 // Placeholder type for OMP array sections.
1360 if (LangOpts.OpenMP) {
1361 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1362 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1363 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1364 }
1365 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1366 // don't bother, as we're just using the same type as OMP.
1367 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1368 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1369 }
1370 if (LangOpts.MatrixTypes)
1371 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1372
1373 // Builtin types for 'id', 'Class', and 'SEL'.
1374 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1375 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1376 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1377
1378 if (LangOpts.OpenCL) {
1379#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1380 InitBuiltinType(SingletonId, BuiltinType::Id);
1381#include "clang/Basic/OpenCLImageTypes.def"
1382
1383 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1384 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1385 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1386 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1387 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1388
1389#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1390 InitBuiltinType(Id##Ty, BuiltinType::Id);
1391#include "clang/Basic/OpenCLExtensionTypes.def"
1392 }
1393
1394 if (LangOpts.HLSL) {
1395#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1396 InitBuiltinType(SingletonId, BuiltinType::Id);
1397#include "clang/Basic/HLSLIntangibleTypes.def"
1398 }
1399
1400 if (Target.hasAArch64ACLETypes() ||
1401 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1402#define SVE_TYPE(Name, Id, SingletonId) \
1403 InitBuiltinType(SingletonId, BuiltinType::Id);
1404#include "clang/Basic/AArch64ACLETypes.def"
1405 }
1406
1407 if (Target.getTriple().isPPC64()) {
1408#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1409 InitBuiltinType(Id##Ty, BuiltinType::Id);
1410#include "clang/Basic/PPCTypes.def"
1411#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1412 InitBuiltinType(Id##Ty, BuiltinType::Id);
1413#include "clang/Basic/PPCTypes.def"
1414 }
1415
1416 if (Target.hasRISCVVTypes()) {
1417#define RVV_TYPE(Name, Id, SingletonId) \
1418 InitBuiltinType(SingletonId, BuiltinType::Id);
1419#include "clang/Basic/RISCVVTypes.def"
1420 }
1421
1422 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1423#define WASM_TYPE(Name, Id, SingletonId) \
1424 InitBuiltinType(SingletonId, BuiltinType::Id);
1425#include "clang/Basic/WebAssemblyReferenceTypes.def"
1426 }
1427
1428 if (Target.getTriple().isAMDGPU() ||
1429 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1430#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1431 InitBuiltinType(SingletonId, BuiltinType::Id);
1432#include "clang/Basic/AMDGPUTypes.def"
1433 }
1434
1435 // Builtin type for __objc_yes and __objc_no
1436 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1438
1439 ObjCConstantStringType = QualType();
1440
1441 ObjCSuperType = QualType();
1442
1443 // void * type
1444 if (LangOpts.OpenCLGenericAddressSpace) {
1445 auto Q = VoidTy.getQualifiers();
1446 Q.setAddressSpace(LangAS::opencl_generic);
1448 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1449 } else {
1451 }
1452
1453 // nullptr type (C++0x 2.14.7)
1454 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1455
1456 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1457 InitBuiltinType(HalfTy, BuiltinType::Half);
1458
1459 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1460
1461 // Builtin type used to help define __builtin_va_list.
1462 VaListTagDecl = nullptr;
1463
1464 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1465 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1468 }
1469}
1470
1472 return SourceMgr.getDiagnostics();
1473}
1474
1476 AttrVec *&Result = DeclAttrs[D];
1477 if (!Result) {
1478 void *Mem = Allocate(sizeof(AttrVec));
1479 Result = new (Mem) AttrVec;
1480 }
1481
1482 return *Result;
1483}
1484
1485/// Erase the attributes corresponding to the given declaration.
1487 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1488 if (Pos != DeclAttrs.end()) {
1489 Pos->second->~AttrVec();
1490 DeclAttrs.erase(Pos);
1491 }
1492}
1493
1494// FIXME: Remove ?
1497 assert(Var->isStaticDataMember() && "Not a static data member");
1499 .dyn_cast<MemberSpecializationInfo *>();
1500}
1501
1504 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1505 TemplateOrInstantiation.find(Var);
1506 if (Pos == TemplateOrInstantiation.end())
1507 return {};
1508
1509 return Pos->second;
1510}
1511
1512void
1515 SourceLocation PointOfInstantiation) {
1516 assert(Inst->isStaticDataMember() && "Not a static data member");
1517 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1519 Tmpl, TSK, PointOfInstantiation));
1520}
1521
1522void
1525 assert(!TemplateOrInstantiation[Inst] &&
1526 "Already noted what the variable was instantiated from");
1527 TemplateOrInstantiation[Inst] = TSI;
1528}
1529
1530NamedDecl *
1532 return InstantiatedFromUsingDecl.lookup(UUD);
1533}
1534
1535void
1537 assert((isa<UsingDecl>(Pattern) ||
1540 "pattern decl is not a using decl");
1541 assert((isa<UsingDecl>(Inst) ||
1544 "instantiation did not produce a using decl");
1545 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1546 InstantiatedFromUsingDecl[Inst] = Pattern;
1547}
1548
1551 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1552}
1553
1555 UsingEnumDecl *Pattern) {
1556 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1557 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1558}
1559
1562 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1563}
1564
1565void
1567 UsingShadowDecl *Pattern) {
1568 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1569 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1570}
1571
1572FieldDecl *
1574 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1575}
1576
1578 FieldDecl *Tmpl) {
1579 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1580 "Instantiated field decl is not unnamed");
1581 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1582 "Template field decl is not unnamed");
1583 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1584 "Already noted what unnamed field was instantiated from");
1585
1586 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1587}
1588
1593
1598
1599unsigned
1601 auto Range = overridden_methods(Method);
1602 return Range.end() - Range.begin();
1603}
1604
1607 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1608 OverriddenMethods.find(Method->getCanonicalDecl());
1609 if (Pos == OverriddenMethods.end())
1610 return overridden_method_range(nullptr, nullptr);
1611 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1612}
1613
1615 const CXXMethodDecl *Overridden) {
1616 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1617 OverriddenMethods[Method].push_back(Overridden);
1618}
1619
1621 const NamedDecl *D,
1622 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1623 assert(D);
1624
1625 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1626 Overridden.append(overridden_methods_begin(CXXMethod),
1627 overridden_methods_end(CXXMethod));
1628 return;
1629 }
1630
1631 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1632 if (!Method)
1633 return;
1634
1636 Method->getOverriddenMethods(OverDecls);
1637 Overridden.append(OverDecls.begin(), OverDecls.end());
1638}
1639
1640std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1642 assert(RD);
1643 CXXRecordDecl *D = RD->getDefinition();
1644 auto it = RelocatableClasses.find(D);
1645 if (it != RelocatableClasses.end())
1646 return it->getSecond();
1647 return std::nullopt;
1648}
1649
1652 assert(RD);
1653 CXXRecordDecl *D = RD->getDefinition();
1654 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1655 RelocatableClasses.insert({D, Info});
1656}
1657
1659 const ASTContext &Context, const CXXRecordDecl *Class) {
1660 if (!Class->isPolymorphic())
1661 return false;
1662 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1663 using AuthAttr = VTablePointerAuthenticationAttr;
1664 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1665 if (!ExplicitAuth)
1666 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1667 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1668 ExplicitAuth->getAddressDiscrimination();
1669 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1670 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1671 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1672}
1673
1674ASTContext::PointerAuthContent
1675ASTContext::findPointerAuthContent(QualType T) const {
1676 assert(isPointerAuthenticationAvailable());
1677
1678 T = T.getCanonicalType();
1679 if (T->isDependentType())
1680 return PointerAuthContent::None;
1681
1683 return PointerAuthContent::AddressDiscriminatedData;
1684 const RecordDecl *RD = T->getAsRecordDecl();
1685 if (!RD)
1686 return PointerAuthContent::None;
1687
1688 if (RD->isInvalidDecl())
1689 return PointerAuthContent::None;
1690
1691 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1692 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1693 return Existing->second;
1694
1695 PointerAuthContent Result = PointerAuthContent::None;
1696
1697 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1698 auto [ResultIter, DidAdd] =
1699 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1700 (void)ResultIter;
1701 (void)DidAdd;
1702 assert(DidAdd);
1703 return Result;
1704 };
1705 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1706 static_assert(PointerAuthContent::None <
1707 PointerAuthContent::AddressDiscriminatedVTable);
1708 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1709 PointerAuthContent::AddressDiscriminatedData);
1710 if (NewResult > Result)
1711 Result = NewResult;
1712 return Result != PointerAuthContent::AddressDiscriminatedData;
1713 };
1714 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1716 !ShouldContinueAfterUpdate(
1717 PointerAuthContent::AddressDiscriminatedVTable))
1718 return SaveResultAndReturn();
1719 for (auto Base : CXXRD->bases()) {
1720 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1721 return SaveResultAndReturn();
1722 }
1723 }
1724 for (auto *FieldDecl : RD->fields()) {
1725 if (!ShouldContinueAfterUpdate(
1726 findPointerAuthContent(FieldDecl->getType())))
1727 return SaveResultAndReturn();
1728 }
1729 return SaveResultAndReturn();
1730}
1731
1733 assert(!Import->getNextLocalImport() &&
1734 "Import declaration already in the chain");
1735 assert(!Import->isFromASTFile() && "Non-local import declaration");
1736 if (!FirstLocalImport) {
1737 FirstLocalImport = Import;
1738 LastLocalImport = Import;
1739 return;
1740 }
1741
1742 LastLocalImport->setNextLocalImport(Import);
1743 LastLocalImport = Import;
1744}
1745
1746//===----------------------------------------------------------------------===//
1747// Type Sizing and Analysis
1748//===----------------------------------------------------------------------===//
1749
1750/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1751/// scalar floating point type.
1752const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1753 switch (T->castAs<BuiltinType>()->getKind()) {
1754 default:
1755 llvm_unreachable("Not a floating point type!");
1756 case BuiltinType::BFloat16:
1757 return Target->getBFloat16Format();
1758 case BuiltinType::Float16:
1759 return Target->getHalfFormat();
1760 case BuiltinType::Half:
1761 return Target->getHalfFormat();
1762 case BuiltinType::Float: return Target->getFloatFormat();
1763 case BuiltinType::Double: return Target->getDoubleFormat();
1764 case BuiltinType::Ibm128:
1765 return Target->getIbm128Format();
1766 case BuiltinType::LongDouble:
1767 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1768 return AuxTarget->getLongDoubleFormat();
1769 return Target->getLongDoubleFormat();
1770 case BuiltinType::Float128:
1771 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1772 return AuxTarget->getFloat128Format();
1773 return Target->getFloat128Format();
1774 }
1775}
1776
1777CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1778 unsigned Align = Target->getCharWidth();
1779
1780 const unsigned AlignFromAttr = D->getMaxAlignment();
1781 if (AlignFromAttr)
1782 Align = AlignFromAttr;
1783
1784 // __attribute__((aligned)) can increase or decrease alignment
1785 // *except* on a struct or struct member, where it only increases
1786 // alignment unless 'packed' is also specified.
1787 //
1788 // It is an error for alignas to decrease alignment, so we can
1789 // ignore that possibility; Sema should diagnose it.
1790 bool UseAlignAttrOnly;
1791 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1792 UseAlignAttrOnly =
1793 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1794 else
1795 UseAlignAttrOnly = AlignFromAttr != 0;
1796 // If we're using the align attribute only, just ignore everything
1797 // else about the declaration and its type.
1798 if (UseAlignAttrOnly) {
1799 // do nothing
1800 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1801 QualType T = VD->getType();
1802 if (const auto *RT = T->getAs<ReferenceType>()) {
1803 if (ForAlignof)
1804 T = RT->getPointeeType();
1805 else
1806 T = getPointerType(RT->getPointeeType());
1807 }
1808 QualType BaseT = getBaseElementType(T);
1809 if (T->isFunctionType())
1810 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1811 else if (!BaseT->isIncompleteType()) {
1812 // Adjust alignments of declarations with array type by the
1813 // large-array alignment on the target.
1814 if (const ArrayType *arrayType = getAsArrayType(T)) {
1815 unsigned MinWidth = Target->getLargeArrayMinWidth();
1816 if (!ForAlignof && MinWidth) {
1818 Align = std::max(Align, Target->getLargeArrayAlign());
1821 Align = std::max(Align, Target->getLargeArrayAlign());
1822 }
1823 }
1824 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1825 if (BaseT.getQualifiers().hasUnaligned())
1826 Align = Target->getCharWidth();
1827 }
1828
1829 // Ensure minimum alignment for global variables.
1830 if (const auto *VD = dyn_cast<VarDecl>(D))
1831 if (VD->hasGlobalStorage() && !ForAlignof) {
1832 uint64_t TypeSize =
1833 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1834 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1835 }
1836
1837 // Fields can be subject to extra alignment constraints, like if
1838 // the field is packed, the struct is packed, or the struct has a
1839 // a max-field-alignment constraint (#pragma pack). So calculate
1840 // the actual alignment of the field within the struct, and then
1841 // (as we're expected to) constrain that by the alignment of the type.
1842 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1843 const RecordDecl *Parent = Field->getParent();
1844 // We can only produce a sensible answer if the record is valid.
1845 if (!Parent->isInvalidDecl()) {
1846 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1847
1848 // Start with the record's overall alignment.
1849 unsigned FieldAlign = toBits(Layout.getAlignment());
1850
1851 // Use the GCD of that and the offset within the record.
1852 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1853 if (Offset > 0) {
1854 // Alignment is always a power of 2, so the GCD will be a power of 2,
1855 // which means we get to do this crazy thing instead of Euclid's.
1856 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1857 if (LowBitOfOffset < FieldAlign)
1858 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1859 }
1860
1861 Align = std::min(Align, FieldAlign);
1862 }
1863 }
1864 }
1865
1866 // Some targets have hard limitation on the maximum requestable alignment in
1867 // aligned attribute for static variables.
1868 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1869 const auto *VD = dyn_cast<VarDecl>(D);
1870 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1871 Align = std::min(Align, MaxAlignedAttr);
1872
1873 return toCharUnitsFromBits(Align);
1874}
1875
1877 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1878}
1879
1880// getTypeInfoDataSizeInChars - Return the size of a type, in
1881// chars. If the type is a record, its data size is returned. This is
1882// the size of the memcpy that's performed when assigning this type
1883// using a trivial copy/move assignment operator.
1886
1887 // In C++, objects can sometimes be allocated into the tail padding
1888 // of a base-class subobject. We decide whether that's possible
1889 // during class layout, so here we can just trust the layout results.
1890 if (getLangOpts().CPlusPlus) {
1891 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1892 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1893 Info.Width = layout.getDataSize();
1894 }
1895 }
1896
1897 return Info;
1898}
1899
1900/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1901/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1904 const ConstantArrayType *CAT) {
1905 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1906 uint64_t Size = CAT->getZExtSize();
1907 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1908 (uint64_t)(-1)/Size) &&
1909 "Overflow in array type char size evaluation");
1910 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1911 unsigned Align = EltInfo.Align.getQuantity();
1912 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1913 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1914 Width = llvm::alignTo(Width, Align);
1917 EltInfo.AlignRequirement);
1918}
1919
1921 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1922 return getConstantArrayInfoInChars(*this, CAT);
1923 TypeInfo Info = getTypeInfo(T);
1926}
1927
1929 return getTypeInfoInChars(T.getTypePtr());
1930}
1931
1933 // HLSL doesn't promote all small integer types to int, it
1934 // just uses the rank-based promotion rules for all types.
1935 if (getLangOpts().HLSL)
1936 return false;
1937
1938 if (const auto *BT = T->getAs<BuiltinType>())
1939 switch (BT->getKind()) {
1940 case BuiltinType::Bool:
1941 case BuiltinType::Char_S:
1942 case BuiltinType::Char_U:
1943 case BuiltinType::SChar:
1944 case BuiltinType::UChar:
1945 case BuiltinType::Short:
1946 case BuiltinType::UShort:
1947 case BuiltinType::WChar_S:
1948 case BuiltinType::WChar_U:
1949 case BuiltinType::Char8:
1950 case BuiltinType::Char16:
1951 case BuiltinType::Char32:
1952 return true;
1953 default:
1954 return false;
1955 }
1956
1957 // Enumerated types are promotable to their compatible integer types
1958 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1959 if (const auto *ED = T->getAsEnumDecl()) {
1960 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1961 ED->isScoped())
1962 return false;
1963
1964 return true;
1965 }
1966
1967 // OverflowBehaviorTypes are promotable if their underlying type is promotable
1968 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
1969 return isPromotableIntegerType(OBT->getUnderlyingType());
1970 }
1971
1972 return false;
1973}
1974
1978
1980 return isAlignmentRequired(T.getTypePtr());
1981}
1982
1984 bool NeedsPreferredAlignment) const {
1985 // An alignment on a typedef overrides anything else.
1986 if (const auto *TT = T->getAs<TypedefType>())
1987 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1988 return Align;
1989
1990 // If we have an (array of) complete type, we're done.
1991 T = getBaseElementType(T);
1992 if (!T->isIncompleteType())
1993 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1994
1995 // If we had an array type, its element type might be a typedef
1996 // type with an alignment attribute.
1997 if (const auto *TT = T->getAs<TypedefType>())
1998 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1999 return Align;
2000
2001 // Otherwise, see if the declaration of the type had an attribute.
2002 if (const auto *TD = T->getAsTagDecl())
2003 return TD->getMaxAlignment();
2004
2005 return 0;
2006}
2007
2009 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2010 if (I != MemoizedTypeInfo.end())
2011 return I->second;
2012
2013 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2014 TypeInfo TI = getTypeInfoImpl(T);
2015 MemoizedTypeInfo[T] = TI;
2016 return TI;
2017}
2018
2019/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2020/// method does not work on incomplete types.
2021///
2022/// FIXME: Pointers into different addr spaces could have different sizes and
2023/// alignment requirements: getPointerInfo should take an AddrSpace, this
2024/// should take a QualType, &c.
2025TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2026 uint64_t Width = 0;
2027 unsigned Align = 8;
2030 switch (T->getTypeClass()) {
2031#define TYPE(Class, Base)
2032#define ABSTRACT_TYPE(Class, Base)
2033#define NON_CANONICAL_TYPE(Class, Base)
2034#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2035#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2036 case Type::Class: \
2037 assert(!T->isDependentType() && "should not see dependent types here"); \
2038 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2039#include "clang/AST/TypeNodes.inc"
2040 llvm_unreachable("Should not see dependent types");
2041
2042 case Type::FunctionNoProto:
2043 case Type::FunctionProto:
2044 // GCC extension: alignof(function) = 32 bits
2045 Width = 0;
2046 Align = 32;
2047 break;
2048
2049 case Type::IncompleteArray:
2050 case Type::VariableArray:
2051 case Type::ConstantArray:
2052 case Type::ArrayParameter: {
2053 // Model non-constant sized arrays as size zero, but track the alignment.
2054 uint64_t Size = 0;
2055 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2056 Size = CAT->getZExtSize();
2057
2058 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2059 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2060 "Overflow in array type bit size evaluation");
2061 Width = EltInfo.Width * Size;
2062 Align = EltInfo.Align;
2063 AlignRequirement = EltInfo.AlignRequirement;
2064 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2065 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2066 Width = llvm::alignTo(Width, Align);
2067 break;
2068 }
2069
2070 case Type::ExtVector:
2071 case Type::Vector: {
2072 const auto *VT = cast<VectorType>(T);
2073 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2074 Width = VT->isPackedVectorBoolType(*this)
2075 ? VT->getNumElements()
2076 : EltInfo.Width * VT->getNumElements();
2077 // Enforce at least byte size and alignment.
2078 Width = std::max<unsigned>(8, Width);
2079 Align = std::max<unsigned>(8, Width);
2080
2081 // If the alignment is not a power of 2, round up to the next power of 2.
2082 // This happens for non-power-of-2 length vectors.
2083 if (Align & (Align-1)) {
2084 Align = llvm::bit_ceil(Align);
2085 Width = llvm::alignTo(Width, Align);
2086 }
2087 // Adjust the alignment based on the target max.
2088 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2089 if (TargetVectorAlign && TargetVectorAlign < Align)
2090 Align = TargetVectorAlign;
2091 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2092 // Adjust the alignment for fixed-length SVE vectors. This is important
2093 // for non-power-of-2 vector lengths.
2094 Align = 128;
2095 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2096 // Adjust the alignment for fixed-length SVE predicates.
2097 Align = 16;
2098 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2099 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2100 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2101 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2102 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2103 // Adjust the alignment for fixed-length RVV vectors.
2104 Align = std::min<unsigned>(64, Width);
2105 break;
2106 }
2107
2108 case Type::ConstantMatrix: {
2109 const auto *MT = cast<ConstantMatrixType>(T);
2110 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2111 // The internal layout of a matrix value is implementation defined.
2112 // Initially be ABI compatible with arrays with respect to alignment and
2113 // size.
2114 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2115 Align = ElementInfo.Align;
2116 break;
2117 }
2118
2119 case Type::Builtin:
2120 switch (cast<BuiltinType>(T)->getKind()) {
2121 default: llvm_unreachable("Unknown builtin type!");
2122 case BuiltinType::Void:
2123 // GCC extension: alignof(void) = 8 bits.
2124 Width = 0;
2125 Align = 8;
2126 break;
2127 case BuiltinType::Bool:
2128 Width = Target->getBoolWidth();
2129 Align = Target->getBoolAlign();
2130 break;
2131 case BuiltinType::Char_S:
2132 case BuiltinType::Char_U:
2133 case BuiltinType::UChar:
2134 case BuiltinType::SChar:
2135 case BuiltinType::Char8:
2136 Width = Target->getCharWidth();
2137 Align = Target->getCharAlign();
2138 break;
2139 case BuiltinType::WChar_S:
2140 case BuiltinType::WChar_U:
2141 Width = Target->getWCharWidth();
2142 Align = Target->getWCharAlign();
2143 break;
2144 case BuiltinType::Char16:
2145 Width = Target->getChar16Width();
2146 Align = Target->getChar16Align();
2147 break;
2148 case BuiltinType::Char32:
2149 Width = Target->getChar32Width();
2150 Align = Target->getChar32Align();
2151 break;
2152 case BuiltinType::UShort:
2153 case BuiltinType::Short:
2154 Width = Target->getShortWidth();
2155 Align = Target->getShortAlign();
2156 break;
2157 case BuiltinType::UInt:
2158 case BuiltinType::Int:
2159 Width = Target->getIntWidth();
2160 Align = Target->getIntAlign();
2161 break;
2162 case BuiltinType::ULong:
2163 case BuiltinType::Long:
2164 Width = Target->getLongWidth();
2165 Align = Target->getLongAlign();
2166 break;
2167 case BuiltinType::ULongLong:
2168 case BuiltinType::LongLong:
2169 Width = Target->getLongLongWidth();
2170 Align = Target->getLongLongAlign();
2171 break;
2172 case BuiltinType::Int128:
2173 case BuiltinType::UInt128:
2174 Width = 128;
2175 Align = Target->getInt128Align();
2176 break;
2177 case BuiltinType::ShortAccum:
2178 case BuiltinType::UShortAccum:
2179 case BuiltinType::SatShortAccum:
2180 case BuiltinType::SatUShortAccum:
2181 Width = Target->getShortAccumWidth();
2182 Align = Target->getShortAccumAlign();
2183 break;
2184 case BuiltinType::Accum:
2185 case BuiltinType::UAccum:
2186 case BuiltinType::SatAccum:
2187 case BuiltinType::SatUAccum:
2188 Width = Target->getAccumWidth();
2189 Align = Target->getAccumAlign();
2190 break;
2191 case BuiltinType::LongAccum:
2192 case BuiltinType::ULongAccum:
2193 case BuiltinType::SatLongAccum:
2194 case BuiltinType::SatULongAccum:
2195 Width = Target->getLongAccumWidth();
2196 Align = Target->getLongAccumAlign();
2197 break;
2198 case BuiltinType::ShortFract:
2199 case BuiltinType::UShortFract:
2200 case BuiltinType::SatShortFract:
2201 case BuiltinType::SatUShortFract:
2202 Width = Target->getShortFractWidth();
2203 Align = Target->getShortFractAlign();
2204 break;
2205 case BuiltinType::Fract:
2206 case BuiltinType::UFract:
2207 case BuiltinType::SatFract:
2208 case BuiltinType::SatUFract:
2209 Width = Target->getFractWidth();
2210 Align = Target->getFractAlign();
2211 break;
2212 case BuiltinType::LongFract:
2213 case BuiltinType::ULongFract:
2214 case BuiltinType::SatLongFract:
2215 case BuiltinType::SatULongFract:
2216 Width = Target->getLongFractWidth();
2217 Align = Target->getLongFractAlign();
2218 break;
2219 case BuiltinType::BFloat16:
2220 if (Target->hasBFloat16Type()) {
2221 Width = Target->getBFloat16Width();
2222 Align = Target->getBFloat16Align();
2223 } else if ((getLangOpts().SYCLIsDevice ||
2224 (getLangOpts().OpenMP &&
2225 getLangOpts().OpenMPIsTargetDevice)) &&
2226 AuxTarget->hasBFloat16Type()) {
2227 Width = AuxTarget->getBFloat16Width();
2228 Align = AuxTarget->getBFloat16Align();
2229 }
2230 break;
2231 case BuiltinType::Float16:
2232 case BuiltinType::Half:
2233 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2234 !getLangOpts().OpenMPIsTargetDevice) {
2235 Width = Target->getHalfWidth();
2236 Align = Target->getHalfAlign();
2237 } else {
2238 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2239 "Expected OpenMP device compilation.");
2240 Width = AuxTarget->getHalfWidth();
2241 Align = AuxTarget->getHalfAlign();
2242 }
2243 break;
2244 case BuiltinType::Float:
2245 Width = Target->getFloatWidth();
2246 Align = Target->getFloatAlign();
2247 break;
2248 case BuiltinType::Double:
2249 Width = Target->getDoubleWidth();
2250 Align = Target->getDoubleAlign();
2251 break;
2252 case BuiltinType::Ibm128:
2253 Width = Target->getIbm128Width();
2254 Align = Target->getIbm128Align();
2255 break;
2256 case BuiltinType::LongDouble:
2257 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2258 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2259 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2260 Width = AuxTarget->getLongDoubleWidth();
2261 Align = AuxTarget->getLongDoubleAlign();
2262 } else {
2263 Width = Target->getLongDoubleWidth();
2264 Align = Target->getLongDoubleAlign();
2265 }
2266 break;
2267 case BuiltinType::Float128:
2268 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2269 !getLangOpts().OpenMPIsTargetDevice) {
2270 Width = Target->getFloat128Width();
2271 Align = Target->getFloat128Align();
2272 } else {
2273 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2274 "Expected OpenMP device compilation.");
2275 Width = AuxTarget->getFloat128Width();
2276 Align = AuxTarget->getFloat128Align();
2277 }
2278 break;
2279 case BuiltinType::NullPtr:
2280 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2281 Width = Target->getPointerWidth(LangAS::Default);
2282 Align = Target->getPointerAlign(LangAS::Default);
2283 break;
2284 case BuiltinType::ObjCId:
2285 case BuiltinType::ObjCClass:
2286 case BuiltinType::ObjCSel:
2287 Width = Target->getPointerWidth(LangAS::Default);
2288 Align = Target->getPointerAlign(LangAS::Default);
2289 break;
2290 case BuiltinType::OCLSampler:
2291 case BuiltinType::OCLEvent:
2292 case BuiltinType::OCLClkEvent:
2293 case BuiltinType::OCLQueue:
2294 case BuiltinType::OCLReserveID:
2295#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2296 case BuiltinType::Id:
2297#include "clang/Basic/OpenCLImageTypes.def"
2298#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2299 case BuiltinType::Id:
2300#include "clang/Basic/OpenCLExtensionTypes.def"
2301 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2302 Width = Target->getPointerWidth(AS);
2303 Align = Target->getPointerAlign(AS);
2304 break;
2305 // The SVE types are effectively target-specific. The length of an
2306 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2307 // of 128 bits. There is one predicate bit for each vector byte, so the
2308 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2309 //
2310 // Because the length is only known at runtime, we use a dummy value
2311 // of 0 for the static length. The alignment values are those defined
2312 // by the Procedure Call Standard for the Arm Architecture.
2313#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2314 case BuiltinType::Id: \
2315 Width = 0; \
2316 Align = 128; \
2317 break;
2318#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2319 case BuiltinType::Id: \
2320 Width = 0; \
2321 Align = 16; \
2322 break;
2323#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2324 case BuiltinType::Id: \
2325 Width = 0; \
2326 Align = 16; \
2327 break;
2328#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2329 case BuiltinType::Id: \
2330 Width = Bits; \
2331 Align = Bits; \
2332 break;
2333#include "clang/Basic/AArch64ACLETypes.def"
2334#define PPC_VECTOR_TYPE(Name, Id, Size) \
2335 case BuiltinType::Id: \
2336 Width = Size; \
2337 Align = Size; \
2338 break;
2339#include "clang/Basic/PPCTypes.def"
2340#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2341 IsFP, IsBF) \
2342 case BuiltinType::Id: \
2343 Width = 0; \
2344 Align = ElBits; \
2345 break;
2346#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2347 case BuiltinType::Id: \
2348 Width = 0; \
2349 Align = 8; \
2350 break;
2351#include "clang/Basic/RISCVVTypes.def"
2352#define WASM_TYPE(Name, Id, SingletonId) \
2353 case BuiltinType::Id: \
2354 Width = 0; \
2355 Align = 8; \
2356 break;
2357#include "clang/Basic/WebAssemblyReferenceTypes.def"
2358#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2359 case BuiltinType::ID: \
2360 Width = WIDTH; \
2361 Align = ALIGN; \
2362 break;
2363#include "clang/Basic/AMDGPUTypes.def"
2364#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2365#include "clang/Basic/HLSLIntangibleTypes.def"
2366 Width = Target->getPointerWidth(LangAS::Default);
2367 Align = Target->getPointerAlign(LangAS::Default);
2368 break;
2369 }
2370 break;
2371 case Type::ObjCObjectPointer:
2372 Width = Target->getPointerWidth(LangAS::Default);
2373 Align = Target->getPointerAlign(LangAS::Default);
2374 break;
2375 case Type::BlockPointer:
2376 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2377 Width = Target->getPointerWidth(AS);
2378 Align = Target->getPointerAlign(AS);
2379 break;
2380 case Type::LValueReference:
2381 case Type::RValueReference:
2382 // alignof and sizeof should never enter this code path here, so we go
2383 // the pointer route.
2384 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2385 Width = Target->getPointerWidth(AS);
2386 Align = Target->getPointerAlign(AS);
2387 break;
2388 case Type::Pointer:
2389 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2390 Width = Target->getPointerWidth(AS);
2391 Align = Target->getPointerAlign(AS);
2392 break;
2393 case Type::MemberPointer: {
2394 const auto *MPT = cast<MemberPointerType>(T);
2395 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2396 Width = MPI.Width;
2397 Align = MPI.Align;
2398 break;
2399 }
2400 case Type::Complex: {
2401 // Complex types have the same alignment as their elements, but twice the
2402 // size.
2403 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2404 Width = EltInfo.Width * 2;
2405 Align = EltInfo.Align;
2406 break;
2407 }
2408 case Type::ObjCObject:
2409 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2410 case Type::Adjusted:
2411 case Type::Decayed:
2412 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2413 case Type::ObjCInterface: {
2414 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2415 if (ObjCI->getDecl()->isInvalidDecl()) {
2416 Width = 8;
2417 Align = 8;
2418 break;
2419 }
2420 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2421 Width = toBits(Layout.getSize());
2422 Align = toBits(Layout.getAlignment());
2423 break;
2424 }
2425 case Type::BitInt: {
2426 const auto *EIT = cast<BitIntType>(T);
2427 Align = Target->getBitIntAlign(EIT->getNumBits());
2428 Width = Target->getBitIntWidth(EIT->getNumBits());
2429 break;
2430 }
2431 case Type::Record:
2432 case Type::Enum: {
2433 const auto *TT = cast<TagType>(T);
2434 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2435
2436 if (TD->isInvalidDecl()) {
2437 Width = 8;
2438 Align = 8;
2439 break;
2440 }
2441
2442 if (isa<EnumType>(TT)) {
2443 const EnumDecl *ED = cast<EnumDecl>(TD);
2444 TypeInfo Info =
2446 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2447 Info.Align = AttrAlign;
2449 }
2450 return Info;
2451 }
2452
2453 const auto *RD = cast<RecordDecl>(TD);
2454 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2455 Width = toBits(Layout.getSize());
2456 Align = toBits(Layout.getAlignment());
2457 AlignRequirement = RD->hasAttr<AlignedAttr>()
2459 : AlignRequirementKind::None;
2460 break;
2461 }
2462
2463 case Type::SubstTemplateTypeParm:
2465 getReplacementType().getTypePtr());
2466
2467 case Type::Auto:
2468 case Type::DeducedTemplateSpecialization: {
2469 const auto *A = cast<DeducedType>(T);
2470 assert(!A->getDeducedType().isNull() &&
2471 "cannot request the size of an undeduced or dependent auto type");
2472 return getTypeInfo(A->getDeducedType().getTypePtr());
2473 }
2474
2475 case Type::Paren:
2476 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2477
2478 case Type::MacroQualified:
2479 return getTypeInfo(
2480 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2481
2482 case Type::ObjCTypeParam:
2483 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2484
2485 case Type::Using:
2486 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2487
2488 case Type::Typedef: {
2489 const auto *TT = cast<TypedefType>(T);
2490 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2491 // If the typedef has an aligned attribute on it, it overrides any computed
2492 // alignment we have. This violates the GCC documentation (which says that
2493 // attribute(aligned) can only round up) but matches its implementation.
2494 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2495 Align = AttrAlign;
2496 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2497 } else {
2498 Align = Info.Align;
2499 AlignRequirement = Info.AlignRequirement;
2500 }
2501 Width = Info.Width;
2502 break;
2503 }
2504
2505 case Type::Attributed:
2506 return getTypeInfo(
2507 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2508
2509 case Type::CountAttributed:
2510 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2511
2512 case Type::BTFTagAttributed:
2513 return getTypeInfo(
2514 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2515
2516 case Type::OverflowBehavior:
2517 return getTypeInfo(
2519
2520 case Type::HLSLAttributedResource:
2521 return getTypeInfo(
2522 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2523
2524 case Type::HLSLInlineSpirv: {
2525 const auto *ST = cast<HLSLInlineSpirvType>(T);
2526 // Size is specified in bytes, convert to bits
2527 Width = ST->getSize() * 8;
2528 Align = ST->getAlignment();
2529 if (Width == 0 && Align == 0) {
2530 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2531 Width = 32;
2532 Align = 32;
2533 }
2534 break;
2535 }
2536
2537 case Type::Atomic: {
2538 // Start with the base type information.
2539 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2540 Width = Info.Width;
2541 Align = Info.Align;
2542
2543 if (!Width) {
2544 // An otherwise zero-sized type should still generate an
2545 // atomic operation.
2546 Width = Target->getCharWidth();
2547 assert(Align);
2548 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2549 // If the size of the type doesn't exceed the platform's max
2550 // atomic promotion width, make the size and alignment more
2551 // favorable to atomic operations:
2552
2553 // Round the size up to a power of 2.
2554 Width = llvm::bit_ceil(Width);
2555
2556 // Set the alignment equal to the size.
2557 Align = static_cast<unsigned>(Width);
2558 }
2559 }
2560 break;
2561
2562 case Type::PredefinedSugar:
2563 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2564
2565 case Type::Pipe:
2566 Width = Target->getPointerWidth(LangAS::opencl_global);
2567 Align = Target->getPointerAlign(LangAS::opencl_global);
2568 break;
2569 }
2570
2571 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2572 return TypeInfo(Width, Align, AlignRequirement);
2573}
2574
2576 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2577 if (I != MemoizedUnadjustedAlign.end())
2578 return I->second;
2579
2580 unsigned UnadjustedAlign;
2581 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2582 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2583 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2584 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2585 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2586 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2587 } else {
2588 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2589 }
2590
2591 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2592 return UnadjustedAlign;
2593}
2594
2596 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2597 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2598 return SimdAlign;
2599}
2600
2601/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2603 return CharUnits::fromQuantity(BitSize / getCharWidth());
2604}
2605
2606/// toBits - Convert a size in characters to a size in characters.
2607int64_t ASTContext::toBits(CharUnits CharSize) const {
2608 return CharSize.getQuantity() * getCharWidth();
2609}
2610
2611/// getTypeSizeInChars - Return the size of the specified type, in characters.
2612/// This method does not work on incomplete types.
2619
2620/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2621/// characters. This method does not work on incomplete types.
2628
2629/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2630/// type, in characters, before alignment adjustments. This method does
2631/// not work on incomplete types.
2638
2639/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2640/// type for the current target in bits. This can be different than the ABI
2641/// alignment in cases where it is beneficial for performance or backwards
2642/// compatibility preserving to overalign a data type. (Note: despite the name,
2643/// the preferred alignment is ABI-impacting, and not an optimization.)
2644unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2645 TypeInfo TI = getTypeInfo(T);
2646 unsigned ABIAlign = TI.Align;
2647
2648 T = T->getBaseElementTypeUnsafe();
2649
2650 // The preferred alignment of member pointers is that of a pointer.
2651 if (T->isMemberPointerType())
2652 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2653
2654 if (!Target->allowsLargerPreferedTypeAlignment())
2655 return ABIAlign;
2656
2657 if (const auto *RD = T->getAsRecordDecl()) {
2658 // When used as part of a typedef, or together with a 'packed' attribute,
2659 // the 'aligned' attribute can be used to decrease alignment. Note that the
2660 // 'packed' case is already taken into consideration when computing the
2661 // alignment, we only need to handle the typedef case here.
2663 RD->isInvalidDecl())
2664 return ABIAlign;
2665
2666 unsigned PreferredAlign = static_cast<unsigned>(
2667 toBits(getASTRecordLayout(RD).PreferredAlignment));
2668 assert(PreferredAlign >= ABIAlign &&
2669 "PreferredAlign should be at least as large as ABIAlign.");
2670 return PreferredAlign;
2671 }
2672
2673 // Double (and, for targets supporting AIX `power` alignment, long double) and
2674 // long long should be naturally aligned (despite requiring less alignment) if
2675 // possible.
2676 if (const auto *CT = T->getAs<ComplexType>())
2677 T = CT->getElementType().getTypePtr();
2678 if (const auto *ED = T->getAsEnumDecl())
2679 T = ED->getIntegerType().getTypePtr();
2680 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2681 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2682 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2683 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2684 Target->defaultsToAIXPowerAlignment()))
2685 // Don't increase the alignment if an alignment attribute was specified on a
2686 // typedef declaration.
2687 if (!TI.isAlignRequired())
2688 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2689
2690 return ABIAlign;
2691}
2692
2693/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2694/// for __attribute__((aligned)) on this target, to be used if no alignment
2695/// value is specified.
2699
2700/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2701/// to a global variable of the specified type.
2703 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2704 return std::max(getPreferredTypeAlign(T),
2705 getMinGlobalAlignOfVar(TypeSize, VD));
2706}
2707
2708/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2709/// should be given to a global variable of the specified type.
2714
2716 const VarDecl *VD) const {
2717 // Make the default handling as that of a non-weak definition in the
2718 // current translation unit.
2719 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2720 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2721}
2722
2724 CharUnits Offset = CharUnits::Zero();
2725 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2726 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2727 Offset += Layout->getBaseClassOffset(Base);
2728 Layout = &getASTRecordLayout(Base);
2729 }
2730 return Offset;
2731}
2732
2734 const ValueDecl *MPD = MP.getMemberPointerDecl();
2737 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2739 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2740 const CXXRecordDecl *Base = RD;
2741 const CXXRecordDecl *Derived = Path[I];
2742 if (DerivedMember)
2743 std::swap(Base, Derived);
2745 RD = Path[I];
2746 }
2747 if (DerivedMember)
2749 return ThisAdjustment;
2750}
2751
2752/// DeepCollectObjCIvars -
2753/// This routine first collects all declared, but not synthesized, ivars in
2754/// super class and then collects all ivars, including those synthesized for
2755/// current class. This routine is used for implementation of current class
2756/// when all ivars, declared and synthesized are known.
2758 bool leafClass,
2760 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2761 DeepCollectObjCIvars(SuperClass, false, Ivars);
2762 if (!leafClass) {
2763 llvm::append_range(Ivars, OI->ivars());
2764 } else {
2765 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2766 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2767 Iv= Iv->getNextIvar())
2768 Ivars.push_back(Iv);
2769 }
2770}
2771
2772/// CollectInheritedProtocols - Collect all protocols in current class and
2773/// those inherited by it.
2776 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2777 // We can use protocol_iterator here instead of
2778 // all_referenced_protocol_iterator since we are walking all categories.
2779 for (auto *Proto : OI->all_referenced_protocols()) {
2780 CollectInheritedProtocols(Proto, Protocols);
2781 }
2782
2783 // Categories of this Interface.
2784 for (const auto *Cat : OI->visible_categories())
2785 CollectInheritedProtocols(Cat, Protocols);
2786
2787 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2788 while (SD) {
2789 CollectInheritedProtocols(SD, Protocols);
2790 SD = SD->getSuperClass();
2791 }
2792 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2793 for (auto *Proto : OC->protocols()) {
2794 CollectInheritedProtocols(Proto, Protocols);
2795 }
2796 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2797 // Insert the protocol.
2798 if (!Protocols.insert(
2799 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2800 return;
2801
2802 for (auto *Proto : OP->protocols())
2803 CollectInheritedProtocols(Proto, Protocols);
2804 }
2805}
2806
2808 const RecordDecl *RD,
2809 bool CheckIfTriviallyCopyable) {
2810 assert(RD->isUnion() && "Must be union type");
2811 CharUnits UnionSize =
2812 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2813
2814 for (const auto *Field : RD->fields()) {
2815 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2816 CheckIfTriviallyCopyable))
2817 return false;
2818 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2819 if (FieldSize != UnionSize)
2820 return false;
2821 }
2822 return !RD->field_empty();
2823}
2824
2825static int64_t getSubobjectOffset(const FieldDecl *Field,
2826 const ASTContext &Context,
2827 const clang::ASTRecordLayout & /*Layout*/) {
2828 return Context.getFieldOffset(Field);
2829}
2830
2831static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2832 const ASTContext &Context,
2833 const clang::ASTRecordLayout &Layout) {
2834 return Context.toBits(Layout.getBaseClassOffset(RD));
2835}
2836
2837static std::optional<int64_t>
2839 const RecordDecl *RD,
2840 bool CheckIfTriviallyCopyable);
2841
2842static std::optional<int64_t>
2843getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2844 bool CheckIfTriviallyCopyable) {
2845 if (const auto *RD = Field->getType()->getAsRecordDecl();
2846 RD && !RD->isUnion())
2847 return structHasUniqueObjectRepresentations(Context, RD,
2848 CheckIfTriviallyCopyable);
2849
2850 // A _BitInt type may not be unique if it has padding bits
2851 // but if it is a bitfield the padding bits are not used.
2852 bool IsBitIntType = Field->getType()->isBitIntType();
2853 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2854 !Context.hasUniqueObjectRepresentations(Field->getType(),
2855 CheckIfTriviallyCopyable))
2856 return std::nullopt;
2857
2858 int64_t FieldSizeInBits =
2859 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2860 if (Field->isBitField()) {
2861 // If we have explicit padding bits, they don't contribute bits
2862 // to the actual object representation, so return 0.
2863 if (Field->isUnnamedBitField())
2864 return 0;
2865
2866 int64_t BitfieldSize = Field->getBitWidthValue();
2867 if (IsBitIntType) {
2868 if ((unsigned)BitfieldSize >
2869 cast<BitIntType>(Field->getType())->getNumBits())
2870 return std::nullopt;
2871 } else if (BitfieldSize > FieldSizeInBits) {
2872 return std::nullopt;
2873 }
2874 FieldSizeInBits = BitfieldSize;
2875 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2876 Field->getType(), CheckIfTriviallyCopyable)) {
2877 return std::nullopt;
2878 }
2879 return FieldSizeInBits;
2880}
2881
2882static std::optional<int64_t>
2884 bool CheckIfTriviallyCopyable) {
2885 return structHasUniqueObjectRepresentations(Context, RD,
2886 CheckIfTriviallyCopyable);
2887}
2888
2889template <typename RangeT>
2891 const RangeT &Subobjects, int64_t CurOffsetInBits,
2892 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2893 bool CheckIfTriviallyCopyable) {
2894 for (const auto *Subobject : Subobjects) {
2895 std::optional<int64_t> SizeInBits =
2896 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2897 if (!SizeInBits)
2898 return std::nullopt;
2899 if (*SizeInBits != 0) {
2900 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2901 if (Offset != CurOffsetInBits)
2902 return std::nullopt;
2903 CurOffsetInBits += *SizeInBits;
2904 }
2905 }
2906 return CurOffsetInBits;
2907}
2908
2909static std::optional<int64_t>
2911 const RecordDecl *RD,
2912 bool CheckIfTriviallyCopyable) {
2913 assert(!RD->isUnion() && "Must be struct/class type");
2914 const auto &Layout = Context.getASTRecordLayout(RD);
2915
2916 int64_t CurOffsetInBits = 0;
2917 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2918 if (ClassDecl->isDynamicClass())
2919 return std::nullopt;
2920
2922 for (const auto &Base : ClassDecl->bases()) {
2923 // Empty types can be inherited from, and non-empty types can potentially
2924 // have tail padding, so just make sure there isn't an error.
2925 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2926 }
2927
2928 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2929 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2930 });
2931
2932 std::optional<int64_t> OffsetAfterBases =
2934 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2935 if (!OffsetAfterBases)
2936 return std::nullopt;
2937 CurOffsetInBits = *OffsetAfterBases;
2938 }
2939
2940 std::optional<int64_t> OffsetAfterFields =
2942 RD->fields(), CurOffsetInBits, Context, Layout,
2943 CheckIfTriviallyCopyable);
2944 if (!OffsetAfterFields)
2945 return std::nullopt;
2946 CurOffsetInBits = *OffsetAfterFields;
2947
2948 return CurOffsetInBits;
2949}
2950
2952 QualType Ty, bool CheckIfTriviallyCopyable) const {
2953 // C++17 [meta.unary.prop]:
2954 // The predicate condition for a template specialization
2955 // has_unique_object_representations<T> shall be satisfied if and only if:
2956 // (9.1) - T is trivially copyable, and
2957 // (9.2) - any two objects of type T with the same value have the same
2958 // object representation, where:
2959 // - two objects of array or non-union class type are considered to have
2960 // the same value if their respective sequences of direct subobjects
2961 // have the same values, and
2962 // - two objects of union type are considered to have the same value if
2963 // they have the same active member and the corresponding members have
2964 // the same value.
2965 // The set of scalar types for which this condition holds is
2966 // implementation-defined. [ Note: If a type has padding bits, the condition
2967 // does not hold; otherwise, the condition holds true for unsigned integral
2968 // types. -- end note ]
2969 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2970
2971 // Arrays are unique only if their element type is unique.
2972 if (Ty->isArrayType())
2974 CheckIfTriviallyCopyable);
2975
2976 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2977 "hasUniqueObjectRepresentations should not be called with an "
2978 "incomplete type");
2979
2980 // (9.1) - T is trivially copyable...
2981 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2982 return false;
2983
2984 // All integrals and enums are unique.
2985 if (Ty->isIntegralOrEnumerationType()) {
2986 // Address discriminated integer types are not unique.
2988 return false;
2989 // Except _BitInt types that have padding bits.
2990 if (const auto *BIT = Ty->getAs<BitIntType>())
2991 return getTypeSize(BIT) == BIT->getNumBits();
2992
2993 return true;
2994 }
2995
2996 // All other pointers are unique.
2997 if (Ty->isPointerType())
2999
3000 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3001 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3002
3003 if (const auto *Record = Ty->getAsRecordDecl()) {
3004 if (Record->isInvalidDecl())
3005 return false;
3006
3007 if (Record->isUnion())
3009 CheckIfTriviallyCopyable);
3010
3011 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3012 *this, Record, CheckIfTriviallyCopyable);
3013
3014 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3015 }
3016
3017 // FIXME: More cases to handle here (list by rsmith):
3018 // vectors (careful about, eg, vector of 3 foo)
3019 // _Complex int and friends
3020 // _Atomic T
3021 // Obj-C block pointers
3022 // Obj-C object pointers
3023 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3024 // clk_event_t, queue_t, reserve_id_t)
3025 // There're also Obj-C class types and the Obj-C selector type, but I think it
3026 // makes sense for those to return false here.
3027
3028 return false;
3029}
3030
3032 unsigned count = 0;
3033 // Count ivars declared in class extension.
3034 for (const auto *Ext : OI->known_extensions())
3035 count += Ext->ivar_size();
3036
3037 // Count ivar defined in this class's implementation. This
3038 // includes synthesized ivars.
3039 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3040 count += ImplDecl->ivar_size();
3041
3042 return count;
3043}
3044
3046 if (!E)
3047 return false;
3048
3049 // nullptr_t is always treated as null.
3050 if (E->getType()->isNullPtrType()) return true;
3051
3052 if (E->getType()->isAnyPointerType() &&
3055 return true;
3056
3057 // Unfortunately, __null has type 'int'.
3058 if (isa<GNUNullExpr>(E)) return true;
3059
3060 return false;
3061}
3062
3063/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3064/// exists.
3066 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3067 I = ObjCImpls.find(D);
3068 if (I != ObjCImpls.end())
3069 return cast<ObjCImplementationDecl>(I->second);
3070 return nullptr;
3071}
3072
3073/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3074/// exists.
3076 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3077 I = ObjCImpls.find(D);
3078 if (I != ObjCImpls.end())
3079 return cast<ObjCCategoryImplDecl>(I->second);
3080 return nullptr;
3081}
3082
3083/// Set the implementation of ObjCInterfaceDecl.
3085 ObjCImplementationDecl *ImplD) {
3086 assert(IFaceD && ImplD && "Passed null params");
3087 ObjCImpls[IFaceD] = ImplD;
3088}
3089
3090/// Set the implementation of ObjCCategoryDecl.
3092 ObjCCategoryImplDecl *ImplD) {
3093 assert(CatD && ImplD && "Passed null params");
3094 ObjCImpls[CatD] = ImplD;
3095}
3096
3097const ObjCMethodDecl *
3099 return ObjCMethodRedecls.lookup(MD);
3100}
3101
3103 const ObjCMethodDecl *Redecl) {
3104 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3105 ObjCMethodRedecls[MD] = Redecl;
3106}
3107
3109 const NamedDecl *ND) const {
3110 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3111 return ID;
3112 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3113 return CD->getClassInterface();
3114 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3115 return IMD->getClassInterface();
3116
3117 return nullptr;
3118}
3119
3120/// Get the copy initialization expression of VarDecl, or nullptr if
3121/// none exists.
3123 assert(VD && "Passed null params");
3124 assert(VD->hasAttr<BlocksAttr>() &&
3125 "getBlockVarCopyInits - not __block var");
3126 auto I = BlockVarCopyInits.find(VD);
3127 if (I != BlockVarCopyInits.end())
3128 return I->second;
3129 return {nullptr, false};
3130}
3131
3132/// Set the copy initialization expression of a block var decl.
3134 bool CanThrow) {
3135 assert(VD && CopyExpr && "Passed null params");
3136 assert(VD->hasAttr<BlocksAttr>() &&
3137 "setBlockVarCopyInits - not __block var");
3138 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3139}
3140
3142 unsigned DataSize) const {
3143 if (!DataSize)
3144 DataSize = TypeLoc::getFullDataSizeForType(T);
3145 else
3146 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3147 "incorrect data size provided to CreateTypeSourceInfo!");
3148
3149 auto *TInfo =
3150 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3151 new (TInfo) TypeSourceInfo(T, DataSize);
3152 return TInfo;
3153}
3154
3156 SourceLocation L) const {
3158 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3159 return TSI;
3160}
3161
3162const ASTRecordLayout &
3164 return getObjCLayout(D);
3165}
3166
3169 bool &AnyNonCanonArgs) {
3170 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3171 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3172 return CanonArgs;
3173}
3174
3177 bool AnyNonCanonArgs = false;
3178 for (auto &Arg : Args) {
3179 TemplateArgument OrigArg = Arg;
3181 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3182 }
3183 return AnyNonCanonArgs;
3184}
3185
3186//===----------------------------------------------------------------------===//
3187// Type creation/memoization methods
3188//===----------------------------------------------------------------------===//
3189
3191ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3192 unsigned fastQuals = quals.getFastQualifiers();
3193 quals.removeFastQualifiers();
3194
3195 // Check if we've already instantiated this type.
3196 llvm::FoldingSetNodeID ID;
3197 ExtQuals::Profile(ID, baseType, quals);
3198 void *insertPos = nullptr;
3199 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3200 assert(eq->getQualifiers() == quals);
3201 return QualType(eq, fastQuals);
3202 }
3203
3204 // If the base type is not canonical, make the appropriate canonical type.
3205 QualType canon;
3206 if (!baseType->isCanonicalUnqualified()) {
3207 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3208 canonSplit.Quals.addConsistentQualifiers(quals);
3209 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3210
3211 // Re-find the insert position.
3212 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3213 }
3214
3215 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3216 ExtQualNodes.InsertNode(eq, insertPos);
3217 return QualType(eq, fastQuals);
3218}
3219
3221 LangAS AddressSpace) const {
3222 QualType CanT = getCanonicalType(T);
3223 if (CanT.getAddressSpace() == AddressSpace)
3224 return T;
3225
3226 // If we are composing extended qualifiers together, merge together
3227 // into one ExtQuals node.
3228 QualifierCollector Quals;
3229 const Type *TypeNode = Quals.strip(T);
3230
3231 // If this type already has an address space specified, it cannot get
3232 // another one.
3233 assert(!Quals.hasAddressSpace() &&
3234 "Type cannot be in multiple addr spaces!");
3235 Quals.addAddressSpace(AddressSpace);
3236
3237 return getExtQualType(TypeNode, Quals);
3238}
3239
3241 // If the type is not qualified with an address space, just return it
3242 // immediately.
3243 if (!T.hasAddressSpace())
3244 return T;
3245
3246 QualifierCollector Quals;
3247 const Type *TypeNode;
3248 // For arrays, strip the qualifier off the element type, then reconstruct the
3249 // array type
3250 if (T.getTypePtr()->isArrayType()) {
3251 T = getUnqualifiedArrayType(T, Quals);
3252 TypeNode = T.getTypePtr();
3253 } else {
3254 // If we are composing extended qualifiers together, merge together
3255 // into one ExtQuals node.
3256 while (T.hasAddressSpace()) {
3257 TypeNode = Quals.strip(T);
3258
3259 // If the type no longer has an address space after stripping qualifiers,
3260 // jump out.
3261 if (!QualType(TypeNode, 0).hasAddressSpace())
3262 break;
3263
3264 // There might be sugar in the way. Strip it and try again.
3265 T = T.getSingleStepDesugaredType(*this);
3266 }
3267 }
3268
3269 Quals.removeAddressSpace();
3270
3271 // Removal of the address space can mean there are no longer any
3272 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3273 // or required.
3274 if (Quals.hasNonFastQualifiers())
3275 return getExtQualType(TypeNode, Quals);
3276 else
3277 return QualType(TypeNode, Quals.getFastQualifiers());
3278}
3279
3280uint16_t
3282 assert(RD->isPolymorphic() &&
3283 "Attempted to get vtable pointer discriminator on a monomorphic type");
3284 std::unique_ptr<MangleContext> MC(createMangleContext());
3285 SmallString<256> Str;
3286 llvm::raw_svector_ostream Out(Str);
3287 MC->mangleCXXVTable(RD, Out);
3288 return llvm::getPointerAuthStableSipHash(Str);
3289}
3290
3291/// Encode a function type for use in the discriminator of a function pointer
3292/// type. We can't use the itanium scheme for this since C has quite permissive
3293/// rules for type compatibility that we need to be compatible with.
3294///
3295/// Formally, this function associates every function pointer type T with an
3296/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3297/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3298/// compatibility requires equivalent treatment under the ABI, so
3299/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3300/// a subset of ~. Crucially, however, it must be a proper subset because
3301/// CCompatible is not an equivalence relation: for example, int[] is compatible
3302/// with both int[1] and int[2], but the latter are not compatible with each
3303/// other. Therefore this encoding function must be careful to only distinguish
3304/// types if there is no third type with which they are both required to be
3305/// compatible.
3307 raw_ostream &OS, QualType QT) {
3308 // FIXME: Consider address space qualifiers.
3309 const Type *T = QT.getCanonicalType().getTypePtr();
3310
3311 // FIXME: Consider using the C++ type mangling when we encounter a construct
3312 // that is incompatible with C.
3313
3314 switch (T->getTypeClass()) {
3315 case Type::Atomic:
3317 Ctx, OS, cast<AtomicType>(T)->getValueType());
3318
3319 case Type::LValueReference:
3320 OS << "R";
3323 return;
3324 case Type::RValueReference:
3325 OS << "O";
3328 return;
3329
3330 case Type::Pointer:
3331 // C11 6.7.6.1p2:
3332 // For two pointer types to be compatible, both shall be identically
3333 // qualified and both shall be pointers to compatible types.
3334 // FIXME: we should also consider pointee types.
3335 OS << "P";
3336 return;
3337
3338 case Type::ObjCObjectPointer:
3339 case Type::BlockPointer:
3340 OS << "P";
3341 return;
3342
3343 case Type::Complex:
3344 OS << "C";
3346 Ctx, OS, cast<ComplexType>(T)->getElementType());
3347
3348 case Type::VariableArray:
3349 case Type::ConstantArray:
3350 case Type::IncompleteArray:
3351 case Type::ArrayParameter:
3352 // C11 6.7.6.2p6:
3353 // For two array types to be compatible, both shall have compatible
3354 // element types, and if both size specifiers are present, and are integer
3355 // constant expressions, then both size specifiers shall have the same
3356 // constant value [...]
3357 //
3358 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3359 // width of the array.
3360 OS << "A";
3362 Ctx, OS, cast<ArrayType>(T)->getElementType());
3363
3364 case Type::ObjCInterface:
3365 case Type::ObjCObject:
3366 OS << "<objc_object>";
3367 return;
3368
3369 case Type::Enum: {
3370 // C11 6.7.2.2p4:
3371 // Each enumerated type shall be compatible with char, a signed integer
3372 // type, or an unsigned integer type.
3373 //
3374 // So we have to treat enum types as integers.
3375 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3377 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3378 }
3379
3380 case Type::FunctionNoProto:
3381 case Type::FunctionProto: {
3382 // C11 6.7.6.3p15:
3383 // For two function types to be compatible, both shall specify compatible
3384 // return types. Moreover, the parameter type lists, if both are present,
3385 // shall agree in the number of parameters and in the use of the ellipsis
3386 // terminator; corresponding parameters shall have compatible types.
3387 //
3388 // That paragraph goes on to describe how unprototyped functions are to be
3389 // handled, which we ignore here. Unprototyped function pointers are hashed
3390 // as though they were prototyped nullary functions since thats probably
3391 // what the user meant. This behavior is non-conforming.
3392 // FIXME: If we add a "custom discriminator" function type attribute we
3393 // should encode functions as their discriminators.
3394 OS << "F";
3395 const auto *FuncType = cast<FunctionType>(T);
3396 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3397 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3398 for (QualType Param : FPT->param_types()) {
3399 Param = Ctx.getSignatureParameterType(Param);
3400 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3401 }
3402 if (FPT->isVariadic())
3403 OS << "z";
3404 }
3405 OS << "E";
3406 return;
3407 }
3408
3409 case Type::MemberPointer: {
3410 OS << "M";
3411 const auto *MPT = T->castAs<MemberPointerType>();
3413 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3414 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3415 return;
3416 }
3417 case Type::ExtVector:
3418 case Type::Vector:
3419 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3420 break;
3421
3422 // Don't bother discriminating based on these types.
3423 case Type::Pipe:
3424 case Type::BitInt:
3425 case Type::ConstantMatrix:
3426 OS << "?";
3427 return;
3428
3429 case Type::Builtin: {
3430 const auto *BTy = T->castAs<BuiltinType>();
3431 switch (BTy->getKind()) {
3432#define SIGNED_TYPE(Id, SingletonId) \
3433 case BuiltinType::Id: \
3434 OS << "i"; \
3435 return;
3436#define UNSIGNED_TYPE(Id, SingletonId) \
3437 case BuiltinType::Id: \
3438 OS << "i"; \
3439 return;
3440#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3441#define BUILTIN_TYPE(Id, SingletonId)
3442#include "clang/AST/BuiltinTypes.def"
3443 llvm_unreachable("placeholder types should not appear here.");
3444
3445 case BuiltinType::Half:
3446 OS << "Dh";
3447 return;
3448 case BuiltinType::Float:
3449 OS << "f";
3450 return;
3451 case BuiltinType::Double:
3452 OS << "d";
3453 return;
3454 case BuiltinType::LongDouble:
3455 OS << "e";
3456 return;
3457 case BuiltinType::Float16:
3458 OS << "DF16_";
3459 return;
3460 case BuiltinType::Float128:
3461 OS << "g";
3462 return;
3463
3464 case BuiltinType::Void:
3465 OS << "v";
3466 return;
3467
3468 case BuiltinType::ObjCId:
3469 case BuiltinType::ObjCClass:
3470 case BuiltinType::ObjCSel:
3471 case BuiltinType::NullPtr:
3472 OS << "P";
3473 return;
3474
3475 // Don't bother discriminating based on OpenCL types.
3476 case BuiltinType::OCLSampler:
3477 case BuiltinType::OCLEvent:
3478 case BuiltinType::OCLClkEvent:
3479 case BuiltinType::OCLQueue:
3480 case BuiltinType::OCLReserveID:
3481 case BuiltinType::BFloat16:
3482 case BuiltinType::VectorQuad:
3483 case BuiltinType::VectorPair:
3484 case BuiltinType::DMR1024:
3485 case BuiltinType::DMR2048:
3486 OS << "?";
3487 return;
3488
3489 // Don't bother discriminating based on these seldom-used types.
3490 case BuiltinType::Ibm128:
3491 return;
3492#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3493 case BuiltinType::Id: \
3494 return;
3495#include "clang/Basic/OpenCLImageTypes.def"
3496#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3497 case BuiltinType::Id: \
3498 return;
3499#include "clang/Basic/OpenCLExtensionTypes.def"
3500#define SVE_TYPE(Name, Id, SingletonId) \
3501 case BuiltinType::Id: \
3502 return;
3503#include "clang/Basic/AArch64ACLETypes.def"
3504#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3505 case BuiltinType::Id: \
3506 return;
3507#include "clang/Basic/HLSLIntangibleTypes.def"
3508 case BuiltinType::Dependent:
3509 llvm_unreachable("should never get here");
3510#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3511#include "clang/Basic/AMDGPUTypes.def"
3512 case BuiltinType::WasmExternRef:
3513#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3514#include "clang/Basic/RISCVVTypes.def"
3515 llvm_unreachable("not yet implemented");
3516 }
3517 llvm_unreachable("should never get here");
3518 }
3519 case Type::Record: {
3520 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3521 const IdentifierInfo *II = RD->getIdentifier();
3522
3523 // In C++, an immediate typedef of an anonymous struct or union
3524 // is considered to name it for ODR purposes, but C's specification
3525 // of type compatibility does not have a similar rule. Using the typedef
3526 // name in function type discriminators anyway, as we do here,
3527 // therefore technically violates the C standard: two function pointer
3528 // types defined in terms of two typedef'd anonymous structs with
3529 // different names are formally still compatible, but we are assigning
3530 // them different discriminators and therefore incompatible ABIs.
3531 //
3532 // This is a relatively minor violation that significantly improves
3533 // discrimination in some cases and has not caused problems in
3534 // practice. Regardless, it is now part of the ABI in places where
3535 // function type discrimination is used, and it can no longer be
3536 // changed except on new platforms.
3537
3538 if (!II)
3539 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3540 II = Typedef->getDeclName().getAsIdentifierInfo();
3541
3542 if (!II) {
3543 OS << "<anonymous_record>";
3544 return;
3545 }
3546 OS << II->getLength() << II->getName();
3547 return;
3548 }
3549 case Type::HLSLAttributedResource:
3550 case Type::HLSLInlineSpirv:
3551 llvm_unreachable("should never get here");
3552 break;
3553 case Type::OverflowBehavior:
3554 llvm_unreachable("should never get here");
3555 break;
3556 case Type::DeducedTemplateSpecialization:
3557 case Type::Auto:
3558#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3559#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3560#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3561#define ABSTRACT_TYPE(Class, Base)
3562#define TYPE(Class, Base)
3563#include "clang/AST/TypeNodes.inc"
3564 llvm_unreachable("unexpected non-canonical or dependent type!");
3565 return;
3566 }
3567}
3568
3570 assert(!T->isDependentType() &&
3571 "cannot compute type discriminator of a dependent type");
3572 SmallString<256> Str;
3573 llvm::raw_svector_ostream Out(Str);
3574
3575 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3576 T = T->getPointeeType();
3577
3578 if (T->isFunctionType()) {
3579 encodeTypeForFunctionPointerAuth(*this, Out, T);
3580 } else {
3581 T = T.getUnqualifiedType();
3582 // Calls to member function pointers don't need to worry about
3583 // language interop or the laxness of the C type compatibility rules.
3584 // We just mangle the member pointer type directly, which is
3585 // implicitly much stricter about type matching. However, we do
3586 // strip any top-level exception specification before this mangling.
3587 // C++23 requires calls to work when the function type is convertible
3588 // to the pointer type by a function pointer conversion, which can
3589 // change the exception specification. This does not technically
3590 // require the exception specification to not affect representation,
3591 // because the function pointer conversion is still always a direct
3592 // value conversion and therefore an opportunity to resign the
3593 // pointer. (This is in contrast to e.g. qualification conversions,
3594 // which can be applied in nested pointer positions, effectively
3595 // requiring qualified and unqualified representations to match.)
3596 // However, it is pragmatic to ignore exception specifications
3597 // because it allows a certain amount of `noexcept` mismatching
3598 // to not become a visible ODR problem. This also leaves some
3599 // room for the committee to add laxness to function pointer
3600 // conversions in future standards.
3601 if (auto *MPT = T->getAs<MemberPointerType>())
3602 if (MPT->isMemberFunctionPointer()) {
3603 QualType PointeeType = MPT->getPointeeType();
3604 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3605 EST_None) {
3607 T = getMemberPointerType(FT, MPT->getQualifier(),
3608 MPT->getMostRecentCXXRecordDecl());
3609 }
3610 }
3611 std::unique_ptr<MangleContext> MC(createMangleContext());
3612 MC->mangleCanonicalTypeName(T, Out);
3613 }
3614
3615 return llvm::getPointerAuthStableSipHash(Str);
3616}
3617
3619 Qualifiers::GC GCAttr) const {
3620 QualType CanT = getCanonicalType(T);
3621 if (CanT.getObjCGCAttr() == GCAttr)
3622 return T;
3623
3624 if (const auto *ptr = T->getAs<PointerType>()) {
3625 QualType Pointee = ptr->getPointeeType();
3626 if (Pointee->isAnyPointerType()) {
3627 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3628 return getPointerType(ResultType);
3629 }
3630 }
3631
3632 // If we are composing extended qualifiers together, merge together
3633 // into one ExtQuals node.
3634 QualifierCollector Quals;
3635 const Type *TypeNode = Quals.strip(T);
3636
3637 // If this type already has an ObjCGC specified, it cannot get
3638 // another one.
3639 assert(!Quals.hasObjCGCAttr() &&
3640 "Type cannot have multiple ObjCGCs!");
3641 Quals.addObjCGCAttr(GCAttr);
3642
3643 return getExtQualType(TypeNode, Quals);
3644}
3645
3647 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3648 QualType Pointee = Ptr->getPointeeType();
3649 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3650 return getPointerType(removeAddrSpaceQualType(Pointee));
3651 }
3652 }
3653 return T;
3654}
3655
3657 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3658 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3659 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3660
3661 llvm::FoldingSetNodeID ID;
3662 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3663
3664 void *InsertPos = nullptr;
3665 CountAttributedType *CATy =
3666 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3667 if (CATy)
3668 return QualType(CATy, 0);
3669
3670 QualType CanonTy = getCanonicalType(WrappedTy);
3671 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3672 DependentDecls.size());
3674 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3675 OrNull, DependentDecls);
3676 Types.push_back(CATy);
3677 CountAttributedTypes.InsertNode(CATy, InsertPos);
3678
3679 return QualType(CATy, 0);
3680}
3681
3684 llvm::function_ref<QualType(QualType)> Adjust) const {
3685 switch (Orig->getTypeClass()) {
3686 case Type::Attributed: {
3687 const auto *AT = cast<AttributedType>(Orig);
3688 return getAttributedType(AT->getAttrKind(),
3689 adjustType(AT->getModifiedType(), Adjust),
3690 adjustType(AT->getEquivalentType(), Adjust),
3691 AT->getAttr());
3692 }
3693
3694 case Type::BTFTagAttributed: {
3695 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3696 return getBTFTagAttributedType(BTFT->getAttr(),
3697 adjustType(BTFT->getWrappedType(), Adjust));
3698 }
3699
3700 case Type::OverflowBehavior: {
3701 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3702 return getOverflowBehaviorType(OB->getBehaviorKind(),
3703 adjustType(OB->getUnderlyingType(), Adjust));
3704 }
3705
3706 case Type::Paren:
3707 return getParenType(
3708 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3709
3710 case Type::Adjusted: {
3711 const auto *AT = cast<AdjustedType>(Orig);
3712 return getAdjustedType(AT->getOriginalType(),
3713 adjustType(AT->getAdjustedType(), Adjust));
3714 }
3715
3716 case Type::MacroQualified: {
3717 const auto *MQT = cast<MacroQualifiedType>(Orig);
3718 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3719 MQT->getMacroIdentifier());
3720 }
3721
3722 default:
3723 return Adjust(Orig);
3724 }
3725}
3726
3728 FunctionType::ExtInfo Info) {
3729 if (T->getExtInfo() == Info)
3730 return T;
3731
3733 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3734 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3735 } else {
3736 const auto *FPT = cast<FunctionProtoType>(T);
3737 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3738 EPI.ExtInfo = Info;
3739 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3740 }
3741
3742 return cast<FunctionType>(Result.getTypePtr());
3743}
3744
3746 QualType ResultType) {
3747 return adjustType(FunctionType, [&](QualType Orig) {
3748 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3749 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3750
3751 const auto *FPT = Orig->castAs<FunctionProtoType>();
3752 return getFunctionType(ResultType, FPT->getParamTypes(),
3753 FPT->getExtProtoInfo());
3754 });
3755}
3756
3758 QualType ResultType) {
3759 FD = FD->getMostRecentDecl();
3760 while (true) {
3761 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3762 if (FunctionDecl *Next = FD->getPreviousDecl())
3763 FD = Next;
3764 else
3765 break;
3766 }
3768 L->DeducedReturnType(FD, ResultType);
3769}
3770
3771/// Get a function type and produce the equivalent function type with the
3772/// specified exception specification. Type sugar that can be present on a
3773/// declaration of a function with an exception specification is permitted
3774/// and preserved. Other type sugar (for instance, typedefs) is not.
3776 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3777 return adjustType(Orig, [&](QualType Ty) {
3778 const auto *Proto = Ty->castAs<FunctionProtoType>();
3779 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3780 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3781 });
3782}
3783
3791
3793 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3794 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3795 SmallVector<QualType, 16> Args(Proto->param_types().size());
3796 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3797 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3798 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3799 }
3800
3801 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3802 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3803 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3804 }
3805
3806 return T;
3807}
3808
3814
3816 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3817 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3818 EPI.ExtParameterInfos = nullptr;
3819 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3820 }
3821 return T;
3822}
3823
3829
3832 bool AsWritten) {
3833 // Update the type.
3834 QualType Updated =
3836 FD->setType(Updated);
3837
3838 if (!AsWritten)
3839 return;
3840
3841 // Update the type in the type source information too.
3842 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3843 // If the type and the type-as-written differ, we may need to update
3844 // the type-as-written too.
3845 if (TSInfo->getType() != FD->getType())
3846 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3847
3848 // FIXME: When we get proper type location information for exceptions,
3849 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3850 // up the TypeSourceInfo;
3851 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3852 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3853 "TypeLoc size mismatch from updating exception specification");
3854 TSInfo->overrideType(Updated);
3855 }
3856}
3857
3858/// getComplexType - Return the uniqued reference to the type for a complex
3859/// number with the specified element type.
3861 // Unique pointers, to guarantee there is only one pointer of a particular
3862 // structure.
3863 llvm::FoldingSetNodeID ID;
3864 ComplexType::Profile(ID, T);
3865
3866 void *InsertPos = nullptr;
3867 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3868 return QualType(CT, 0);
3869
3870 // If the pointee type isn't canonical, this won't be a canonical type either,
3871 // so fill in the canonical type field.
3872 QualType Canonical;
3873 if (!T.isCanonical()) {
3874 Canonical = getComplexType(getCanonicalType(T));
3875
3876 // Get the new insert position for the node we care about.
3877 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3878 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3879 }
3880 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3881 Types.push_back(New);
3882 ComplexTypes.InsertNode(New, InsertPos);
3883 return QualType(New, 0);
3884}
3885
3886/// getPointerType - Return the uniqued reference to the type for a pointer to
3887/// the specified type.
3889 // Unique pointers, to guarantee there is only one pointer of a particular
3890 // structure.
3891 llvm::FoldingSetNodeID ID;
3892 PointerType::Profile(ID, T);
3893
3894 void *InsertPos = nullptr;
3895 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3896 return QualType(PT, 0);
3897
3898 // If the pointee type isn't canonical, this won't be a canonical type either,
3899 // so fill in the canonical type field.
3900 QualType Canonical;
3901 if (!T.isCanonical()) {
3902 Canonical = getPointerType(getCanonicalType(T));
3903
3904 // Get the new insert position for the node we care about.
3905 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3906 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3907 }
3908 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3909 Types.push_back(New);
3910 PointerTypes.InsertNode(New, InsertPos);
3911 return QualType(New, 0);
3912}
3913
3915 llvm::FoldingSetNodeID ID;
3916 AdjustedType::Profile(ID, Orig, New);
3917 void *InsertPos = nullptr;
3918 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3919 if (AT)
3920 return QualType(AT, 0);
3921
3922 QualType Canonical = getCanonicalType(New);
3923
3924 // Get the new insert position for the node we care about.
3925 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3926 assert(!AT && "Shouldn't be in the map!");
3927
3928 AT = new (*this, alignof(AdjustedType))
3929 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3930 Types.push_back(AT);
3931 AdjustedTypes.InsertNode(AT, InsertPos);
3932 return QualType(AT, 0);
3933}
3934
3936 llvm::FoldingSetNodeID ID;
3937 AdjustedType::Profile(ID, Orig, Decayed);
3938 void *InsertPos = nullptr;
3939 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3940 if (AT)
3941 return QualType(AT, 0);
3942
3943 QualType Canonical = getCanonicalType(Decayed);
3944
3945 // Get the new insert position for the node we care about.
3946 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3947 assert(!AT && "Shouldn't be in the map!");
3948
3949 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3950 Types.push_back(AT);
3951 AdjustedTypes.InsertNode(AT, InsertPos);
3952 return QualType(AT, 0);
3953}
3954
3956 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3957
3958 QualType Decayed;
3959
3960 // C99 6.7.5.3p7:
3961 // A declaration of a parameter as "array of type" shall be
3962 // adjusted to "qualified pointer to type", where the type
3963 // qualifiers (if any) are those specified within the [ and ] of
3964 // the array type derivation.
3965 if (T->isArrayType())
3966 Decayed = getArrayDecayedType(T);
3967
3968 // C99 6.7.5.3p8:
3969 // A declaration of a parameter as "function returning type"
3970 // shall be adjusted to "pointer to function returning type", as
3971 // in 6.3.2.1.
3972 if (T->isFunctionType())
3973 Decayed = getPointerType(T);
3974
3975 return getDecayedType(T, Decayed);
3976}
3977
3979 if (Ty->isArrayParameterType())
3980 return Ty;
3981 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3982 QualType DTy = Ty.getDesugaredType(*this);
3983 const auto *ATy = cast<ConstantArrayType>(DTy);
3984 llvm::FoldingSetNodeID ID;
3985 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3986 ATy->getSizeExpr(), ATy->getSizeModifier(),
3987 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3988 void *InsertPos = nullptr;
3989 ArrayParameterType *AT =
3990 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3991 if (AT)
3992 return QualType(AT, 0);
3993
3994 QualType Canonical;
3995 if (!DTy.isCanonical()) {
3996 Canonical = getArrayParameterType(getCanonicalType(Ty));
3997
3998 // Get the new insert position for the node we care about.
3999 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4000 assert(!AT && "Shouldn't be in the map!");
4001 }
4002
4003 AT = new (*this, alignof(ArrayParameterType))
4004 ArrayParameterType(ATy, Canonical);
4005 Types.push_back(AT);
4006 ArrayParameterTypes.InsertNode(AT, InsertPos);
4007 return QualType(AT, 0);
4008}
4009
4010/// getBlockPointerType - Return the uniqued reference to the type for
4011/// a pointer to the specified block.
4013 assert(T->isFunctionType() && "block of function types only");
4014 // Unique pointers, to guarantee there is only one block of a particular
4015 // structure.
4016 llvm::FoldingSetNodeID ID;
4018
4019 void *InsertPos = nullptr;
4020 if (BlockPointerType *PT =
4021 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4022 return QualType(PT, 0);
4023
4024 // If the block pointee type isn't canonical, this won't be a canonical
4025 // type either so fill in the canonical type field.
4026 QualType Canonical;
4027 if (!T.isCanonical()) {
4028 Canonical = getBlockPointerType(getCanonicalType(T));
4029
4030 // Get the new insert position for the node we care about.
4031 BlockPointerType *NewIP =
4032 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4033 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4034 }
4035 auto *New =
4036 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4037 Types.push_back(New);
4038 BlockPointerTypes.InsertNode(New, InsertPos);
4039 return QualType(New, 0);
4040}
4041
4042/// getLValueReferenceType - Return the uniqued reference to the type for an
4043/// lvalue reference to the specified type.
4045ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4046 assert((!T->isPlaceholderType() ||
4047 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4048 "Unresolved placeholder type");
4049
4050 // Unique pointers, to guarantee there is only one pointer of a particular
4051 // structure.
4052 llvm::FoldingSetNodeID ID;
4053 ReferenceType::Profile(ID, T, SpelledAsLValue);
4054
4055 void *InsertPos = nullptr;
4056 if (LValueReferenceType *RT =
4057 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4058 return QualType(RT, 0);
4059
4060 const auto *InnerRef = T->getAs<ReferenceType>();
4061
4062 // If the referencee type isn't canonical, this won't be a canonical type
4063 // either, so fill in the canonical type field.
4064 QualType Canonical;
4065 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4066 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4067 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4068
4069 // Get the new insert position for the node we care about.
4070 LValueReferenceType *NewIP =
4071 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4072 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4073 }
4074
4075 auto *New = new (*this, alignof(LValueReferenceType))
4076 LValueReferenceType(T, Canonical, SpelledAsLValue);
4077 Types.push_back(New);
4078 LValueReferenceTypes.InsertNode(New, InsertPos);
4079
4080 return QualType(New, 0);
4081}
4082
4083/// getRValueReferenceType - Return the uniqued reference to the type for an
4084/// rvalue reference to the specified type.
4086 assert((!T->isPlaceholderType() ||
4087 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4088 "Unresolved placeholder type");
4089
4090 // Unique pointers, to guarantee there is only one pointer of a particular
4091 // structure.
4092 llvm::FoldingSetNodeID ID;
4093 ReferenceType::Profile(ID, T, false);
4094
4095 void *InsertPos = nullptr;
4096 if (RValueReferenceType *RT =
4097 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4098 return QualType(RT, 0);
4099
4100 const auto *InnerRef = T->getAs<ReferenceType>();
4101
4102 // If the referencee type isn't canonical, this won't be a canonical type
4103 // either, so fill in the canonical type field.
4104 QualType Canonical;
4105 if (InnerRef || !T.isCanonical()) {
4106 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4107 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4108
4109 // Get the new insert position for the node we care about.
4110 RValueReferenceType *NewIP =
4111 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4112 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4113 }
4114
4115 auto *New = new (*this, alignof(RValueReferenceType))
4116 RValueReferenceType(T, Canonical);
4117 Types.push_back(New);
4118 RValueReferenceTypes.InsertNode(New, InsertPos);
4119 return QualType(New, 0);
4120}
4121
4123 NestedNameSpecifier Qualifier,
4124 const CXXRecordDecl *Cls) const {
4125 if (!Qualifier) {
4126 assert(Cls && "At least one of Qualifier or Cls must be provided");
4127 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4128 } else if (!Cls) {
4129 Cls = Qualifier.getAsRecordDecl();
4130 }
4131 // Unique pointers, to guarantee there is only one pointer of a particular
4132 // structure.
4133 llvm::FoldingSetNodeID ID;
4134 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4135
4136 void *InsertPos = nullptr;
4137 if (MemberPointerType *PT =
4138 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4139 return QualType(PT, 0);
4140
4141 NestedNameSpecifier CanonicalQualifier = [&] {
4142 if (!Cls)
4143 return Qualifier.getCanonical();
4144 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4145 assert(R.isCanonical());
4146 return R;
4147 }();
4148 // If the pointee or class type isn't canonical, this won't be a canonical
4149 // type either, so fill in the canonical type field.
4150 QualType Canonical;
4151 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4152 Canonical =
4153 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4154 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4155 // Get the new insert position for the node we care about.
4156 [[maybe_unused]] MemberPointerType *NewIP =
4157 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4158 assert(!NewIP && "Shouldn't be in the map!");
4159 }
4160 auto *New = new (*this, alignof(MemberPointerType))
4161 MemberPointerType(T, Qualifier, Canonical);
4162 Types.push_back(New);
4163 MemberPointerTypes.InsertNode(New, InsertPos);
4164 return QualType(New, 0);
4165}
4166
4167/// getConstantArrayType - Return the unique reference to the type for an
4168/// array of the specified element type.
4170 const llvm::APInt &ArySizeIn,
4171 const Expr *SizeExpr,
4173 unsigned IndexTypeQuals) const {
4174 assert((EltTy->isDependentType() ||
4175 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4176 "Constant array of VLAs is illegal!");
4177
4178 // We only need the size as part of the type if it's instantiation-dependent.
4179 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4180 SizeExpr = nullptr;
4181
4182 // Convert the array size into a canonical width matching the pointer size for
4183 // the target.
4184 llvm::APInt ArySize(ArySizeIn);
4185 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4186
4187 llvm::FoldingSetNodeID ID;
4188 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4189 ASM, IndexTypeQuals);
4190
4191 void *InsertPos = nullptr;
4192 if (ConstantArrayType *ATP =
4193 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4194 return QualType(ATP, 0);
4195
4196 // If the element type isn't canonical or has qualifiers, or the array bound
4197 // is instantiation-dependent, this won't be a canonical type either, so fill
4198 // in the canonical type field.
4199 QualType Canon;
4200 // FIXME: Check below should look for qualifiers behind sugar.
4201 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4202 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4203 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4204 ASM, IndexTypeQuals);
4205 Canon = getQualifiedType(Canon, canonSplit.Quals);
4206
4207 // Get the new insert position for the node we care about.
4208 ConstantArrayType *NewIP =
4209 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4210 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4211 }
4212
4213 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4214 ASM, IndexTypeQuals);
4215 ConstantArrayTypes.InsertNode(New, InsertPos);
4216 Types.push_back(New);
4217 return QualType(New, 0);
4218}
4219
4220/// getVariableArrayDecayedType - Turns the given type, which may be
4221/// variably-modified, into the corresponding type with all the known
4222/// sizes replaced with [*].
4224 // Vastly most common case.
4225 if (!type->isVariablyModifiedType()) return type;
4226
4227 QualType result;
4228
4229 SplitQualType split = type.getSplitDesugaredType();
4230 const Type *ty = split.Ty;
4231 switch (ty->getTypeClass()) {
4232#define TYPE(Class, Base)
4233#define ABSTRACT_TYPE(Class, Base)
4234#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4235#include "clang/AST/TypeNodes.inc"
4236 llvm_unreachable("didn't desugar past all non-canonical types?");
4237
4238 // These types should never be variably-modified.
4239 case Type::Builtin:
4240 case Type::Complex:
4241 case Type::Vector:
4242 case Type::DependentVector:
4243 case Type::ExtVector:
4244 case Type::DependentSizedExtVector:
4245 case Type::ConstantMatrix:
4246 case Type::DependentSizedMatrix:
4247 case Type::DependentAddressSpace:
4248 case Type::ObjCObject:
4249 case Type::ObjCInterface:
4250 case Type::ObjCObjectPointer:
4251 case Type::Record:
4252 case Type::Enum:
4253 case Type::UnresolvedUsing:
4254 case Type::TypeOfExpr:
4255 case Type::TypeOf:
4256 case Type::Decltype:
4257 case Type::UnaryTransform:
4258 case Type::DependentName:
4259 case Type::InjectedClassName:
4260 case Type::TemplateSpecialization:
4261 case Type::TemplateTypeParm:
4262 case Type::SubstTemplateTypeParmPack:
4263 case Type::SubstBuiltinTemplatePack:
4264 case Type::Auto:
4265 case Type::DeducedTemplateSpecialization:
4266 case Type::PackExpansion:
4267 case Type::PackIndexing:
4268 case Type::BitInt:
4269 case Type::DependentBitInt:
4270 case Type::ArrayParameter:
4271 case Type::HLSLAttributedResource:
4272 case Type::HLSLInlineSpirv:
4273 case Type::OverflowBehavior:
4274 llvm_unreachable("type should never be variably-modified");
4275
4276 // These types can be variably-modified but should never need to
4277 // further decay.
4278 case Type::FunctionNoProto:
4279 case Type::FunctionProto:
4280 case Type::BlockPointer:
4281 case Type::MemberPointer:
4282 case Type::Pipe:
4283 return type;
4284
4285 // These types can be variably-modified. All these modifications
4286 // preserve structure except as noted by comments.
4287 // TODO: if we ever care about optimizing VLAs, there are no-op
4288 // optimizations available here.
4289 case Type::Pointer:
4292 break;
4293
4294 case Type::LValueReference: {
4295 const auto *lv = cast<LValueReferenceType>(ty);
4296 result = getLValueReferenceType(
4297 getVariableArrayDecayedType(lv->getPointeeType()),
4298 lv->isSpelledAsLValue());
4299 break;
4300 }
4301
4302 case Type::RValueReference: {
4303 const auto *lv = cast<RValueReferenceType>(ty);
4304 result = getRValueReferenceType(
4305 getVariableArrayDecayedType(lv->getPointeeType()));
4306 break;
4307 }
4308
4309 case Type::Atomic: {
4310 const auto *at = cast<AtomicType>(ty);
4311 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4312 break;
4313 }
4314
4315 case Type::ConstantArray: {
4316 const auto *cat = cast<ConstantArrayType>(ty);
4317 result = getConstantArrayType(
4318 getVariableArrayDecayedType(cat->getElementType()),
4319 cat->getSize(),
4320 cat->getSizeExpr(),
4321 cat->getSizeModifier(),
4322 cat->getIndexTypeCVRQualifiers());
4323 break;
4324 }
4325
4326 case Type::DependentSizedArray: {
4327 const auto *dat = cast<DependentSizedArrayType>(ty);
4329 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4330 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4331 break;
4332 }
4333
4334 // Turn incomplete types into [*] types.
4335 case Type::IncompleteArray: {
4336 const auto *iat = cast<IncompleteArrayType>(ty);
4337 result =
4339 /*size*/ nullptr, ArraySizeModifier::Normal,
4340 iat->getIndexTypeCVRQualifiers());
4341 break;
4342 }
4343
4344 // Turn VLA types into [*] types.
4345 case Type::VariableArray: {
4346 const auto *vat = cast<VariableArrayType>(ty);
4347 result =
4349 /*size*/ nullptr, ArraySizeModifier::Star,
4350 vat->getIndexTypeCVRQualifiers());
4351 break;
4352 }
4353 }
4354
4355 // Apply the top-level qualifiers from the original.
4356 return getQualifiedType(result, split.Quals);
4357}
4358
4359/// getVariableArrayType - Returns a non-unique reference to the type for a
4360/// variable array of the specified element type.
4363 unsigned IndexTypeQuals) const {
4364 // Since we don't unique expressions, it isn't possible to unique VLA's
4365 // that have an expression provided for their size.
4366 QualType Canon;
4367
4368 // Be sure to pull qualifiers off the element type.
4369 // FIXME: Check below should look for qualifiers behind sugar.
4370 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4371 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4372 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4373 IndexTypeQuals);
4374 Canon = getQualifiedType(Canon, canonSplit.Quals);
4375 }
4376
4377 auto *New = new (*this, alignof(VariableArrayType))
4378 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4379
4380 VariableArrayTypes.push_back(New);
4381 Types.push_back(New);
4382 return QualType(New, 0);
4383}
4384
4385/// getDependentSizedArrayType - Returns a non-unique reference to
4386/// the type for a dependently-sized array of the specified element
4387/// type.
4391 unsigned elementTypeQuals) const {
4392 assert((!numElements || numElements->isTypeDependent() ||
4393 numElements->isValueDependent()) &&
4394 "Size must be type- or value-dependent!");
4395
4396 SplitQualType canonElementType = getCanonicalType(elementType).split();
4397
4398 void *insertPos = nullptr;
4399 llvm::FoldingSetNodeID ID;
4401 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4402 ASM, elementTypeQuals, numElements);
4403
4404 // Look for an existing type with these properties.
4405 DependentSizedArrayType *canonTy =
4406 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4407
4408 // Dependently-sized array types that do not have a specified number
4409 // of elements will have their sizes deduced from a dependent
4410 // initializer.
4411 if (!numElements) {
4412 if (canonTy)
4413 return QualType(canonTy, 0);
4414
4415 auto *newType = new (*this, alignof(DependentSizedArrayType))
4416 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4417 elementTypeQuals);
4418 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4419 Types.push_back(newType);
4420 return QualType(newType, 0);
4421 }
4422
4423 // If we don't have one, build one.
4424 if (!canonTy) {
4425 canonTy = new (*this, alignof(DependentSizedArrayType))
4426 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4427 numElements, ASM, elementTypeQuals);
4428 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4429 Types.push_back(canonTy);
4430 }
4431
4432 // Apply qualifiers from the element type to the array.
4433 QualType canon = getQualifiedType(QualType(canonTy,0),
4434 canonElementType.Quals);
4435
4436 // If we didn't need extra canonicalization for the element type or the size
4437 // expression, then just use that as our result.
4438 if (QualType(canonElementType.Ty, 0) == elementType &&
4439 canonTy->getSizeExpr() == numElements)
4440 return canon;
4441
4442 // Otherwise, we need to build a type which follows the spelling
4443 // of the element type.
4444 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4445 DependentSizedArrayType(elementType, canon, numElements, ASM,
4446 elementTypeQuals);
4447 Types.push_back(sugaredType);
4448 return QualType(sugaredType, 0);
4449}
4450
4453 unsigned elementTypeQuals) const {
4454 llvm::FoldingSetNodeID ID;
4455 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4456
4457 void *insertPos = nullptr;
4458 if (IncompleteArrayType *iat =
4459 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4460 return QualType(iat, 0);
4461
4462 // If the element type isn't canonical, this won't be a canonical type
4463 // either, so fill in the canonical type field. We also have to pull
4464 // qualifiers off the element type.
4465 QualType canon;
4466
4467 // FIXME: Check below should look for qualifiers behind sugar.
4468 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4469 SplitQualType canonSplit = getCanonicalType(elementType).split();
4470 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4471 ASM, elementTypeQuals);
4472 canon = getQualifiedType(canon, canonSplit.Quals);
4473
4474 // Get the new insert position for the node we care about.
4475 IncompleteArrayType *existing =
4476 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4477 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4478 }
4479
4480 auto *newType = new (*this, alignof(IncompleteArrayType))
4481 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4482
4483 IncompleteArrayTypes.InsertNode(newType, insertPos);
4484 Types.push_back(newType);
4485 return QualType(newType, 0);
4486}
4487
4490#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4491 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4492 NUMVECTORS};
4493
4494#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4495 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4496
4497 switch (Ty->getKind()) {
4498 default:
4499 llvm_unreachable("Unsupported builtin vector type");
4500
4501#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4502 ElBits, NF, IsSigned) \
4503 case BuiltinType::Id: \
4504 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4505 llvm::ElementCount::getScalable(NumEls), NF};
4506#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4507 ElBits, NF) \
4508 case BuiltinType::Id: \
4509 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4510 llvm::ElementCount::getScalable(NumEls), NF};
4511#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4512 ElBits, NF) \
4513 case BuiltinType::Id: \
4514 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4515#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4516 ElBits, NF) \
4517 case BuiltinType::Id: \
4518 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4519#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4520 case BuiltinType::Id: \
4521 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4522#include "clang/Basic/AArch64ACLETypes.def"
4523
4524#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4525 IsSigned) \
4526 case BuiltinType::Id: \
4527 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4528 llvm::ElementCount::getScalable(NumEls), NF};
4529#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4530 case BuiltinType::Id: \
4531 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4532 llvm::ElementCount::getScalable(NumEls), NF};
4533#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4534 case BuiltinType::Id: \
4535 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4536#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4537 case BuiltinType::Id: \
4538 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4539#include "clang/Basic/RISCVVTypes.def"
4540 }
4541}
4542
4543/// getExternrefType - Return a WebAssembly externref type, which represents an
4544/// opaque reference to a host value.
4546 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4547#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4548 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4549 return SingletonId;
4550#include "clang/Basic/WebAssemblyReferenceTypes.def"
4551 }
4552 llvm_unreachable(
4553 "shouldn't try to generate type externref outside WebAssembly target");
4554}
4555
4556/// getScalableVectorType - Return the unique reference to a scalable vector
4557/// type of the specified element type and size. VectorType must be a built-in
4558/// type.
4560 unsigned NumFields) const {
4561 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4562 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4563 return It->second;
4564
4565 if (Target->hasAArch64ACLETypes()) {
4566 uint64_t EltTySize = getTypeSize(EltTy);
4567
4568#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4569 ElBits, NF, IsSigned) \
4570 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4571 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4572 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4573 return ScalableVecTyMap[K] = SingletonId; \
4574 }
4575#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4576 ElBits, NF) \
4577 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4578 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4579 return ScalableVecTyMap[K] = SingletonId; \
4580 }
4581#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4582 ElBits, NF) \
4583 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4584 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4585 return ScalableVecTyMap[K] = SingletonId; \
4586 }
4587#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4588 ElBits, NF) \
4589 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4590 NumElts == (NumEls * NF) && NumFields == 1) { \
4591 return ScalableVecTyMap[K] = SingletonId; \
4592 }
4593#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4594 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4595 return ScalableVecTyMap[K] = SingletonId;
4596#include "clang/Basic/AArch64ACLETypes.def"
4597 } else if (Target->hasRISCVVTypes()) {
4598 uint64_t EltTySize = getTypeSize(EltTy);
4599#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4600 IsFP, IsBF) \
4601 if (!EltTy->isBooleanType() && \
4602 ((EltTy->hasIntegerRepresentation() && \
4603 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4604 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4605 IsFP && !IsBF) || \
4606 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4607 IsBF && !IsFP)) && \
4608 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4609 return ScalableVecTyMap[K] = SingletonId;
4610#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4611 if (EltTy->isBooleanType() && NumElts == NumEls) \
4612 return ScalableVecTyMap[K] = SingletonId;
4613#include "clang/Basic/RISCVVTypes.def"
4614 }
4615 return QualType();
4616}
4617
4618/// getVectorType - Return the unique reference to a vector type of
4619/// the specified element type and size. VectorType must be a built-in type.
4621 VectorKind VecKind) const {
4622 assert(vecType->isBuiltinType() ||
4623 (vecType->isBitIntType() &&
4624 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4625 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4626
4627 // Check if we've already instantiated a vector of this type.
4628 llvm::FoldingSetNodeID ID;
4629 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4630
4631 void *InsertPos = nullptr;
4632 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4633 return QualType(VTP, 0);
4634
4635 // If the element type isn't canonical, this won't be a canonical type either,
4636 // so fill in the canonical type field.
4637 QualType Canonical;
4638 if (!vecType.isCanonical()) {
4639 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4640
4641 // Get the new insert position for the node we care about.
4642 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4643 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4644 }
4645 auto *New = new (*this, alignof(VectorType))
4646 VectorType(vecType, NumElts, Canonical, VecKind);
4647 VectorTypes.InsertNode(New, InsertPos);
4648 Types.push_back(New);
4649 return QualType(New, 0);
4650}
4651
4653 SourceLocation AttrLoc,
4654 VectorKind VecKind) const {
4655 llvm::FoldingSetNodeID ID;
4656 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4657 VecKind);
4658 void *InsertPos = nullptr;
4659 DependentVectorType *Canon =
4660 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4662
4663 if (Canon) {
4664 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4665 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4666 } else {
4667 QualType CanonVecTy = getCanonicalType(VecType);
4668 if (CanonVecTy == VecType) {
4669 New = new (*this, alignof(DependentVectorType))
4670 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4671
4672 DependentVectorType *CanonCheck =
4673 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4674 assert(!CanonCheck &&
4675 "Dependent-sized vector_size canonical type broken");
4676 (void)CanonCheck;
4677 DependentVectorTypes.InsertNode(New, InsertPos);
4678 } else {
4679 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4680 SourceLocation(), VecKind);
4681 New = new (*this, alignof(DependentVectorType))
4682 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4683 }
4684 }
4685
4686 Types.push_back(New);
4687 return QualType(New, 0);
4688}
4689
4690/// getExtVectorType - Return the unique reference to an extended vector type of
4691/// the specified element type and size. VectorType must be a built-in type.
4693 unsigned NumElts) const {
4694 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4695 (vecType->isBitIntType() &&
4696 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4697 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4698
4699 // Check if we've already instantiated a vector of this type.
4700 llvm::FoldingSetNodeID ID;
4701 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4703 void *InsertPos = nullptr;
4704 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4705 return QualType(VTP, 0);
4706
4707 // If the element type isn't canonical, this won't be a canonical type either,
4708 // so fill in the canonical type field.
4709 QualType Canonical;
4710 if (!vecType.isCanonical()) {
4711 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4712
4713 // Get the new insert position for the node we care about.
4714 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4715 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4716 }
4717 auto *New = new (*this, alignof(ExtVectorType))
4718 ExtVectorType(vecType, NumElts, Canonical);
4719 VectorTypes.InsertNode(New, InsertPos);
4720 Types.push_back(New);
4721 return QualType(New, 0);
4722}
4723
4726 Expr *SizeExpr,
4727 SourceLocation AttrLoc) const {
4728 llvm::FoldingSetNodeID ID;
4730 SizeExpr);
4731
4732 void *InsertPos = nullptr;
4734 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4736 if (Canon) {
4737 // We already have a canonical version of this array type; use it as
4738 // the canonical type for a newly-built type.
4739 New = new (*this, alignof(DependentSizedExtVectorType))
4740 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4741 AttrLoc);
4742 } else {
4743 QualType CanonVecTy = getCanonicalType(vecType);
4744 if (CanonVecTy == vecType) {
4745 New = new (*this, alignof(DependentSizedExtVectorType))
4746 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4747
4748 DependentSizedExtVectorType *CanonCheck
4749 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4750 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4751 (void)CanonCheck;
4752 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4753 } else {
4754 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4755 SourceLocation());
4756 New = new (*this, alignof(DependentSizedExtVectorType))
4757 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4758 }
4759 }
4760
4761 Types.push_back(New);
4762 return QualType(New, 0);
4763}
4764
4766 unsigned NumColumns) const {
4767 llvm::FoldingSetNodeID ID;
4768 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4769 Type::ConstantMatrix);
4770
4771 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4772 "need a valid element type");
4773 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4774 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4775 "need valid matrix dimensions");
4776 void *InsertPos = nullptr;
4777 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4778 return QualType(MTP, 0);
4779
4780 QualType Canonical;
4781 if (!ElementTy.isCanonical()) {
4782 Canonical =
4783 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4784
4785 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4786 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4787 (void)NewIP;
4788 }
4789
4790 auto *New = new (*this, alignof(ConstantMatrixType))
4791 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4792 MatrixTypes.InsertNode(New, InsertPos);
4793 Types.push_back(New);
4794 return QualType(New, 0);
4795}
4796
4798 Expr *RowExpr,
4799 Expr *ColumnExpr,
4800 SourceLocation AttrLoc) const {
4801 QualType CanonElementTy = getCanonicalType(ElementTy);
4802 llvm::FoldingSetNodeID ID;
4803 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4804 ColumnExpr);
4805
4806 void *InsertPos = nullptr;
4808 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4809
4810 if (!Canon) {
4811 Canon = new (*this, alignof(DependentSizedMatrixType))
4812 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4813 ColumnExpr, AttrLoc);
4814#ifndef NDEBUG
4815 DependentSizedMatrixType *CanonCheck =
4816 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4817 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4818#endif
4819 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4820 Types.push_back(Canon);
4821 }
4822
4823 // Already have a canonical version of the matrix type
4824 //
4825 // If it exactly matches the requested type, use it directly.
4826 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4827 Canon->getRowExpr() == ColumnExpr)
4828 return QualType(Canon, 0);
4829
4830 // Use Canon as the canonical type for newly-built type.
4832 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4833 ColumnExpr, AttrLoc);
4834 Types.push_back(New);
4835 return QualType(New, 0);
4836}
4837
4839 Expr *AddrSpaceExpr,
4840 SourceLocation AttrLoc) const {
4841 assert(AddrSpaceExpr->isInstantiationDependent());
4842
4843 QualType canonPointeeType = getCanonicalType(PointeeType);
4844
4845 void *insertPos = nullptr;
4846 llvm::FoldingSetNodeID ID;
4847 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4848 AddrSpaceExpr);
4849
4850 DependentAddressSpaceType *canonTy =
4851 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4852
4853 if (!canonTy) {
4854 canonTy = new (*this, alignof(DependentAddressSpaceType))
4855 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4856 AttrLoc);
4857 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4858 Types.push_back(canonTy);
4859 }
4860
4861 if (canonPointeeType == PointeeType &&
4862 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4863 return QualType(canonTy, 0);
4864
4865 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4866 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4867 AddrSpaceExpr, AttrLoc);
4868 Types.push_back(sugaredType);
4869 return QualType(sugaredType, 0);
4870}
4871
4872/// Determine whether \p T is canonical as the result type of a function.
4874 return T.isCanonical() &&
4875 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4876 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4877}
4878
4879/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4880QualType
4882 const FunctionType::ExtInfo &Info) const {
4883 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4884 // functionality creates a function without a prototype regardless of
4885 // language mode (so it makes them even in C++). Once the rewriter has been
4886 // fixed, this assertion can be enabled again.
4887 //assert(!LangOpts.requiresStrictPrototypes() &&
4888 // "strict prototypes are disabled");
4889
4890 // Unique functions, to guarantee there is only one function of a particular
4891 // structure.
4892 llvm::FoldingSetNodeID ID;
4893 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4894
4895 void *InsertPos = nullptr;
4896 if (FunctionNoProtoType *FT =
4897 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4898 return QualType(FT, 0);
4899
4900 QualType Canonical;
4901 if (!isCanonicalResultType(ResultTy)) {
4902 Canonical =
4904
4905 // Get the new insert position for the node we care about.
4906 FunctionNoProtoType *NewIP =
4907 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4908 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4909 }
4910
4911 auto *New = new (*this, alignof(FunctionNoProtoType))
4912 FunctionNoProtoType(ResultTy, Canonical, Info);
4913 Types.push_back(New);
4914 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4915 return QualType(New, 0);
4916}
4917
4920 CanQualType CanResultType = getCanonicalType(ResultType);
4921
4922 // Canonical result types do not have ARC lifetime qualifiers.
4923 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4924 Qualifiers Qs = CanResultType.getQualifiers();
4925 Qs.removeObjCLifetime();
4927 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4928 }
4929
4930 return CanResultType;
4931}
4932
4934 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4935 if (ESI.Type == EST_None)
4936 return true;
4937 if (!NoexceptInType)
4938 return false;
4939
4940 // C++17 onwards: exception specification is part of the type, as a simple
4941 // boolean "can this function type throw".
4942 if (ESI.Type == EST_BasicNoexcept)
4943 return true;
4944
4945 // A noexcept(expr) specification is (possibly) canonical if expr is
4946 // value-dependent.
4947 if (ESI.Type == EST_DependentNoexcept)
4948 return true;
4949
4950 // A dynamic exception specification is canonical if it only contains pack
4951 // expansions (so we can't tell whether it's non-throwing) and all its
4952 // contained types are canonical.
4953 if (ESI.Type == EST_Dynamic) {
4954 bool AnyPackExpansions = false;
4955 for (QualType ET : ESI.Exceptions) {
4956 if (!ET.isCanonical())
4957 return false;
4958 if (ET->getAs<PackExpansionType>())
4959 AnyPackExpansions = true;
4960 }
4961 return AnyPackExpansions;
4962 }
4963
4964 return false;
4965}
4966
4967QualType ASTContext::getFunctionTypeInternal(
4968 QualType ResultTy, ArrayRef<QualType> ArgArray,
4969 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4970 size_t NumArgs = ArgArray.size();
4971
4972 // Unique functions, to guarantee there is only one function of a particular
4973 // structure.
4974 llvm::FoldingSetNodeID ID;
4975 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4976 *this, true);
4977
4978 QualType Canonical;
4979 bool Unique = false;
4980
4981 void *InsertPos = nullptr;
4982 if (FunctionProtoType *FPT =
4983 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4984 QualType Existing = QualType(FPT, 0);
4985
4986 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4987 // it so long as our exception specification doesn't contain a dependent
4988 // noexcept expression, or we're just looking for a canonical type.
4989 // Otherwise, we're going to need to create a type
4990 // sugar node to hold the concrete expression.
4991 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4992 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4993 return Existing;
4994
4995 // We need a new type sugar node for this one, to hold the new noexcept
4996 // expression. We do no canonicalization here, but that's OK since we don't
4997 // expect to see the same noexcept expression much more than once.
4998 Canonical = getCanonicalType(Existing);
4999 Unique = true;
5000 }
5001
5002 bool NoexceptInType = getLangOpts().CPlusPlus17;
5003 bool IsCanonicalExceptionSpec =
5005
5006 // Determine whether the type being created is already canonical or not.
5007 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5008 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5009 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5010 if (!ArgArray[i].isCanonicalAsParam())
5011 isCanonical = false;
5012
5013 if (OnlyWantCanonical)
5014 assert(isCanonical &&
5015 "given non-canonical parameters constructing canonical type");
5016
5017 // If this type isn't canonical, get the canonical version of it if we don't
5018 // already have it. The exception spec is only partially part of the
5019 // canonical type, and only in C++17 onwards.
5020 if (!isCanonical && Canonical.isNull()) {
5021 SmallVector<QualType, 16> CanonicalArgs;
5022 CanonicalArgs.reserve(NumArgs);
5023 for (unsigned i = 0; i != NumArgs; ++i)
5024 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5025
5026 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5027 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5028 CanonicalEPI.HasTrailingReturn = false;
5029
5030 if (IsCanonicalExceptionSpec) {
5031 // Exception spec is already OK.
5032 } else if (NoexceptInType) {
5033 switch (EPI.ExceptionSpec.Type) {
5035 // We don't know yet. It shouldn't matter what we pick here; no-one
5036 // should ever look at this.
5037 [[fallthrough]];
5038 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5039 CanonicalEPI.ExceptionSpec.Type = EST_None;
5040 break;
5041
5042 // A dynamic exception specification is almost always "not noexcept",
5043 // with the exception that a pack expansion might expand to no types.
5044 case EST_Dynamic: {
5045 bool AnyPacks = false;
5046 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5047 if (ET->getAs<PackExpansionType>())
5048 AnyPacks = true;
5049 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5050 }
5051 if (!AnyPacks)
5052 CanonicalEPI.ExceptionSpec.Type = EST_None;
5053 else {
5054 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5055 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5056 }
5057 break;
5058 }
5059
5060 case EST_DynamicNone:
5061 case EST_BasicNoexcept:
5062 case EST_NoexceptTrue:
5063 case EST_NoThrow:
5064 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5065 break;
5066
5068 llvm_unreachable("dependent noexcept is already canonical");
5069 }
5070 } else {
5071 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5072 }
5073
5074 // Adjust the canonical function result type.
5075 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5076 Canonical =
5077 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5078
5079 // Get the new insert position for the node we care about.
5080 FunctionProtoType *NewIP =
5081 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5082 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5083 }
5084
5085 // Compute the needed size to hold this FunctionProtoType and the
5086 // various trailing objects.
5087 auto ESH = FunctionProtoType::getExceptionSpecSize(
5088 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5089 size_t Size = FunctionProtoType::totalSizeToAlloc<
5090 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5091 FunctionType::FunctionTypeExtraAttributeInfo,
5092 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5093 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5094 FunctionEffect, EffectConditionExpr>(
5097 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5098 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5099 EPI.ExtParameterInfos ? NumArgs : 0,
5101 EPI.FunctionEffects.conditions().size());
5102
5103 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5104 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5105 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5106 Types.push_back(FTP);
5107 if (!Unique)
5108 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5109 if (!EPI.FunctionEffects.empty())
5110 AnyFunctionEffects = true;
5111 return QualType(FTP, 0);
5112}
5113
5114QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5115 llvm::FoldingSetNodeID ID;
5116 PipeType::Profile(ID, T, ReadOnly);
5117
5118 void *InsertPos = nullptr;
5119 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5120 return QualType(PT, 0);
5121
5122 // If the pipe element type isn't canonical, this won't be a canonical type
5123 // either, so fill in the canonical type field.
5124 QualType Canonical;
5125 if (!T.isCanonical()) {
5126 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5127
5128 // Get the new insert position for the node we care about.
5129 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5130 assert(!NewIP && "Shouldn't be in the map!");
5131 (void)NewIP;
5132 }
5133 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5134 Types.push_back(New);
5135 PipeTypes.InsertNode(New, InsertPos);
5136 return QualType(New, 0);
5137}
5138
5140 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5141 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5142 : Ty;
5143}
5144
5146 return getPipeType(T, true);
5147}
5148
5150 return getPipeType(T, false);
5151}
5152
5153QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5154 llvm::FoldingSetNodeID ID;
5155 BitIntType::Profile(ID, IsUnsigned, NumBits);
5156
5157 void *InsertPos = nullptr;
5158 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5159 return QualType(EIT, 0);
5160
5161 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5162 BitIntTypes.InsertNode(New, InsertPos);
5163 Types.push_back(New);
5164 return QualType(New, 0);
5165}
5166
5168 Expr *NumBitsExpr) const {
5169 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5170 llvm::FoldingSetNodeID ID;
5171 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5172
5173 void *InsertPos = nullptr;
5174 if (DependentBitIntType *Existing =
5175 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5176 return QualType(Existing, 0);
5177
5178 auto *New = new (*this, alignof(DependentBitIntType))
5179 DependentBitIntType(IsUnsigned, NumBitsExpr);
5180 DependentBitIntTypes.InsertNode(New, InsertPos);
5181
5182 Types.push_back(New);
5183 return QualType(New, 0);
5184}
5185
5188 using Kind = PredefinedSugarType::Kind;
5189
5190 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5191 Target != nullptr)
5192 return QualType(Target, 0);
5193
5194 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5195 switch (KDI) {
5196 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5197 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5198 // are part of the core language and are widely used. Using
5199 // PredefinedSugarType makes these types as named sugar types rather than
5200 // standard integer types, enabling better hints and diagnostics.
5201 case Kind::SizeT:
5202 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5203 case Kind::SignedSizeT:
5204 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5205 case Kind::PtrdiffT:
5206 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5207 }
5208 llvm_unreachable("unexpected kind");
5209 };
5210 auto *New = new (*this, alignof(PredefinedSugarType))
5211 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5212 getCanonicalType(*this, static_cast<Kind>(KD)));
5213 Types.push_back(New);
5214 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5215 return QualType(New, 0);
5216}
5217
5219 NestedNameSpecifier Qualifier,
5220 const TypeDecl *Decl) const {
5221 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5222 return getTagType(Keyword, Qualifier, Tag,
5223 /*OwnsTag=*/false);
5224 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5225 return getTypedefType(Keyword, Qualifier, Typedef);
5226 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5227 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5228
5230 assert(!Qualifier);
5231 return QualType(Decl->TypeForDecl, 0);
5232}
5233
5235 if (auto *Tag = dyn_cast<TagDecl>(TD))
5236 return getCanonicalTagType(Tag);
5237 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5238 return getCanonicalType(TN->getUnderlyingType());
5239 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5241 assert(TD->TypeForDecl);
5242 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5243}
5244
5246 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5247 return getCanonicalTagType(TD);
5248 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5249 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5251 /*Qualifier=*/std::nullopt, TD);
5252 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5253 return getCanonicalUnresolvedUsingType(Using);
5254
5255 assert(Decl->TypeForDecl);
5256 return QualType(Decl->TypeForDecl, 0);
5257}
5258
5259/// getTypedefType - Return the unique reference to the type for the
5260/// specified typedef name decl.
5263 NestedNameSpecifier Qualifier,
5264 const TypedefNameDecl *Decl, QualType UnderlyingType,
5265 std::optional<bool> TypeMatchesDeclOrNone) const {
5266 if (!TypeMatchesDeclOrNone) {
5267 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5268 assert(!DeclUnderlyingType.isNull());
5269 if (UnderlyingType.isNull())
5270 UnderlyingType = DeclUnderlyingType;
5271 else
5272 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5273 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5274 } else {
5275 // FIXME: This is a workaround for a serialization cycle: assume the decl
5276 // underlying type is not available; don't touch it.
5277 assert(!UnderlyingType.isNull());
5278 }
5279
5280 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5281 *TypeMatchesDeclOrNone) {
5282 if (Decl->TypeForDecl)
5283 return QualType(Decl->TypeForDecl, 0);
5284
5285 auto *NewType = new (*this, alignof(TypedefType))
5286 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5287 !*TypeMatchesDeclOrNone);
5288
5289 Types.push_back(NewType);
5290 Decl->TypeForDecl = NewType;
5291 return QualType(NewType, 0);
5292 }
5293
5294 llvm::FoldingSetNodeID ID;
5295 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5296 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5297
5298 void *InsertPos = nullptr;
5299 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5300 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5301 return QualType(Placeholder->getType(), 0);
5302
5303 void *Mem =
5304 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5306 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5307 alignof(TypedefType));
5308 auto *NewType =
5309 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5310 UnderlyingType, !*TypeMatchesDeclOrNone);
5311 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5313 TypedefTypes.InsertNode(Placeholder, InsertPos);
5314 Types.push_back(NewType);
5315 return QualType(NewType, 0);
5316}
5317
5319 NestedNameSpecifier Qualifier,
5320 const UsingShadowDecl *D,
5321 QualType UnderlyingType) const {
5322 // FIXME: This is expensive to compute every time!
5323 if (UnderlyingType.isNull()) {
5324 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5325 UnderlyingType =
5328 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5329 }
5330
5331 llvm::FoldingSetNodeID ID;
5332 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5333
5334 void *InsertPos = nullptr;
5335 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5336 return QualType(T, 0);
5337
5338 assert(!UnderlyingType.hasLocalQualifiers());
5339
5340 assert(
5342 UnderlyingType));
5343
5344 void *Mem =
5345 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5346 alignof(UsingType));
5347 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5348 Types.push_back(T);
5349 UsingTypes.InsertNode(T, InsertPos);
5350 return QualType(T, 0);
5351}
5352
5353TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5354 NestedNameSpecifier Qualifier,
5355 const TagDecl *TD, bool OwnsTag,
5356 bool IsInjected,
5357 const Type *CanonicalType,
5358 bool WithFoldingSetNode) const {
5359 auto [TC, Size] = [&] {
5360 switch (TD->getDeclKind()) {
5361 case Decl::Enum:
5362 static_assert(alignof(EnumType) == alignof(TagType));
5363 return std::make_tuple(Type::Enum, sizeof(EnumType));
5364 case Decl::ClassTemplatePartialSpecialization:
5365 case Decl::ClassTemplateSpecialization:
5366 case Decl::CXXRecord:
5367 static_assert(alignof(RecordType) == alignof(TagType));
5368 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5369 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5370 return std::make_tuple(Type::InjectedClassName,
5371 sizeof(InjectedClassNameType));
5372 [[fallthrough]];
5373 case Decl::Record:
5374 return std::make_tuple(Type::Record, sizeof(RecordType));
5375 default:
5376 llvm_unreachable("unexpected decl kind");
5377 }
5378 }();
5379
5380 if (Qualifier) {
5381 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5382 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5383 sizeof(NestedNameSpecifier);
5384 }
5385 void *Mem;
5386 if (WithFoldingSetNode) {
5387 // FIXME: It would be more profitable to tail allocate the folding set node
5388 // from the type, instead of the other way around, due to the greater
5389 // alignment requirements of the type. But this makes it harder to deal with
5390 // the different type node sizes. This would require either uniquing from
5391 // different folding sets, or having the folding setaccept a
5392 // contextual parameter which is not fixed at construction.
5393 Mem = Allocate(
5394 sizeof(TagTypeFoldingSetPlaceholder) +
5395 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5396 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5397 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5398 Mem = T->getTagType();
5399 } else {
5400 Mem = Allocate(Size, alignof(TagType));
5401 }
5402
5403 auto *T = [&, TC = TC]() -> TagType * {
5404 switch (TC) {
5405 case Type::Enum: {
5406 assert(isa<EnumDecl>(TD));
5407 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5408 IsInjected, CanonicalType);
5409 assert(reinterpret_cast<void *>(T) ==
5410 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5411 "TagType must be the first base of EnumType");
5412 return T;
5413 }
5414 case Type::Record: {
5415 assert(isa<RecordDecl>(TD));
5416 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5417 IsInjected, CanonicalType);
5418 assert(reinterpret_cast<void *>(T) ==
5419 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5420 "TagType must be the first base of RecordType");
5421 return T;
5422 }
5423 case Type::InjectedClassName: {
5424 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5425 IsInjected, CanonicalType);
5426 assert(reinterpret_cast<void *>(T) ==
5427 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5428 "TagType must be the first base of InjectedClassNameType");
5429 return T;
5430 }
5431 default:
5432 llvm_unreachable("unexpected type class");
5433 }
5434 }();
5435 assert(T->getKeyword() == Keyword);
5436 assert(T->getQualifier() == Qualifier);
5437 assert(T->getDecl() == TD);
5438 assert(T->isInjected() == IsInjected);
5439 assert(T->isTagOwned() == OwnsTag);
5440 assert((T->isCanonicalUnqualified()
5441 ? QualType()
5442 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5443 Types.push_back(T);
5444 return T;
5445}
5446
5447static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5448 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5449 RD && RD->isInjectedClassName())
5450 return cast<TagDecl>(RD->getDeclContext());
5451 return TD;
5452}
5453
5456 if (TD->TypeForDecl)
5457 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5458
5459 const Type *CanonicalType = getTagTypeInternal(
5461 /*Qualifier=*/std::nullopt, TD,
5462 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5463 /*WithFoldingSetNode=*/false);
5464 TD->TypeForDecl = CanonicalType;
5465 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5466}
5467
5469 NestedNameSpecifier Qualifier,
5470 const TagDecl *TD, bool OwnsTag) const {
5471
5472 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5473 bool IsInjected = TD != NonInjectedTD;
5474
5475 ElaboratedTypeKeyword PreferredKeyword =
5478 NonInjectedTD->getTagKind());
5479
5480 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5481 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5482 return QualType(T, 0);
5483
5484 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5485 const Type *T =
5486 getTagTypeInternal(Keyword,
5487 /*Qualifier=*/std::nullopt, NonInjectedTD,
5488 /*OwnsTag=*/false, IsInjected, CanonicalType,
5489 /*WithFoldingSetNode=*/false);
5490 TD->TypeForDecl = T;
5491 return QualType(T, 0);
5492 }
5493
5494 llvm::FoldingSetNodeID ID;
5495 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5496 OwnsTag, IsInjected);
5497
5498 void *InsertPos = nullptr;
5499 if (TagTypeFoldingSetPlaceholder *T =
5500 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5501 return QualType(T->getTagType(), 0);
5502
5503 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5504 TagType *T =
5505 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5506 CanonicalType, /*WithFoldingSetNode=*/true);
5507 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5508 return QualType(T, 0);
5509}
5510
5511bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5512 unsigned NumPositiveBits,
5513 QualType &BestType,
5514 QualType &BestPromotionType) {
5515 unsigned IntWidth = Target->getIntWidth();
5516 unsigned CharWidth = Target->getCharWidth();
5517 unsigned ShortWidth = Target->getShortWidth();
5518 bool EnumTooLarge = false;
5519 unsigned BestWidth;
5520 if (NumNegativeBits) {
5521 // If there is a negative value, figure out the smallest integer type (of
5522 // int/long/longlong) that fits.
5523 // If it's packed, check also if it fits a char or a short.
5524 if (IsPacked && NumNegativeBits <= CharWidth &&
5525 NumPositiveBits < CharWidth) {
5526 BestType = SignedCharTy;
5527 BestWidth = CharWidth;
5528 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5529 NumPositiveBits < ShortWidth) {
5530 BestType = ShortTy;
5531 BestWidth = ShortWidth;
5532 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5533 BestType = IntTy;
5534 BestWidth = IntWidth;
5535 } else {
5536 BestWidth = Target->getLongWidth();
5537
5538 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5539 BestType = LongTy;
5540 } else {
5541 BestWidth = Target->getLongLongWidth();
5542
5543 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5544 EnumTooLarge = true;
5545 BestType = LongLongTy;
5546 }
5547 }
5548 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5549 } else {
5550 // If there is no negative value, figure out the smallest type that fits
5551 // all of the enumerator values.
5552 // If it's packed, check also if it fits a char or a short.
5553 if (IsPacked && NumPositiveBits <= CharWidth) {
5554 BestType = UnsignedCharTy;
5555 BestPromotionType = IntTy;
5556 BestWidth = CharWidth;
5557 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5558 BestType = UnsignedShortTy;
5559 BestPromotionType = IntTy;
5560 BestWidth = ShortWidth;
5561 } else if (NumPositiveBits <= IntWidth) {
5562 BestType = UnsignedIntTy;
5563 BestWidth = IntWidth;
5564 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5566 : IntTy;
5567 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5568 BestType = UnsignedLongTy;
5569 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5571 : LongTy;
5572 } else {
5573 BestWidth = Target->getLongLongWidth();
5574 if (NumPositiveBits > BestWidth) {
5575 // This can happen with bit-precise integer types, but those are not
5576 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5577 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5578 // a 128-bit integer, we should consider doing the same.
5579 EnumTooLarge = true;
5580 }
5581 BestType = UnsignedLongLongTy;
5582 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5584 : LongLongTy;
5585 }
5586 }
5587 return EnumTooLarge;
5588}
5589
5591 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5592 "Integral type required!");
5593 unsigned BitWidth = getIntWidth(T);
5594
5595 if (Value.isUnsigned() || Value.isNonNegative()) {
5596 if (T->isSignedIntegerOrEnumerationType())
5597 --BitWidth;
5598 return Value.getActiveBits() <= BitWidth;
5599 }
5600 return Value.getSignificantBits() <= BitWidth;
5601}
5602
5603UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5605 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5606 const Type *CanonicalType) const {
5607 void *Mem = Allocate(
5608 UnresolvedUsingType::totalSizeToAlloc<
5610 !!InsertPos, !!Qualifier),
5611 alignof(UnresolvedUsingType));
5612 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5613 if (InsertPos) {
5614 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5616 TypedefTypes.InsertNode(Placeholder, InsertPos);
5617 }
5618 Types.push_back(T);
5619 return T;
5620}
5621
5623 const UnresolvedUsingTypenameDecl *D) const {
5624 D = D->getCanonicalDecl();
5625 if (D->TypeForDecl)
5626 return D->TypeForDecl->getCanonicalTypeUnqualified();
5627
5628 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5630 /*Qualifier=*/std::nullopt, D,
5631 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5632 D->TypeForDecl = CanonicalType;
5633 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5634}
5635
5638 NestedNameSpecifier Qualifier,
5639 const UnresolvedUsingTypenameDecl *D) const {
5640 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5641 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5642 return QualType(T, 0);
5643
5644 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5645 const Type *T =
5646 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5647 /*Qualifier=*/std::nullopt, D,
5648 /*InsertPos=*/nullptr, CanonicalType);
5649 D->TypeForDecl = T;
5650 return QualType(T, 0);
5651 }
5652
5653 llvm::FoldingSetNodeID ID;
5654 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5655
5656 void *InsertPos = nullptr;
5658 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5659 return QualType(Placeholder->getType(), 0);
5660 assert(InsertPos);
5661
5662 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5663 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5664 InsertPos, CanonicalType);
5665 return QualType(T, 0);
5666}
5667
5669 QualType modifiedType,
5670 QualType equivalentType,
5671 const Attr *attr) const {
5672 llvm::FoldingSetNodeID id;
5673 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5674
5675 void *insertPos = nullptr;
5676 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5677 if (type) return QualType(type, 0);
5678
5679 assert(!attr || attr->getKind() == attrKind);
5680
5681 QualType canon = getCanonicalType(equivalentType);
5682 type = new (*this, alignof(AttributedType))
5683 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5684
5685 Types.push_back(type);
5686 AttributedTypes.InsertNode(type, insertPos);
5687
5688 return QualType(type, 0);
5689}
5690
5692 QualType equivalentType) const {
5693 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5694}
5695
5697 QualType modifiedType,
5698 QualType equivalentType) {
5699 switch (nullability) {
5701 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5702
5704 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5705
5707 return getAttributedType(attr::TypeNullableResult, modifiedType,
5708 equivalentType);
5709
5711 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5712 equivalentType);
5713 }
5714
5715 llvm_unreachable("Unknown nullability kind");
5716}
5717
5718QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5719 QualType Wrapped) const {
5720 llvm::FoldingSetNodeID ID;
5721 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5722
5723 void *InsertPos = nullptr;
5724 BTFTagAttributedType *Ty =
5725 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5726 if (Ty)
5727 return QualType(Ty, 0);
5728
5729 QualType Canon = getCanonicalType(Wrapped);
5730 Ty = new (*this, alignof(BTFTagAttributedType))
5731 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5732
5733 Types.push_back(Ty);
5734 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5735
5736 return QualType(Ty, 0);
5737}
5738
5740 QualType Underlying) const {
5741 const IdentifierInfo *II = Attr->getBehaviorKind();
5742 StringRef IdentName = II->getName();
5743 OverflowBehaviorType::OverflowBehaviorKind Kind;
5744 if (IdentName == "wrap") {
5745 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5746 } else if (IdentName == "trap") {
5747 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5748 } else {
5749 return Underlying;
5750 }
5751
5752 return getOverflowBehaviorType(Kind, Underlying);
5753}
5754
5756 OverflowBehaviorType::OverflowBehaviorKind Kind,
5757 QualType Underlying) const {
5758 assert(!Underlying->isOverflowBehaviorType() &&
5759 "Cannot have underlying types that are themselves OBTs");
5760 llvm::FoldingSetNodeID ID;
5761 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5762 void *InsertPos = nullptr;
5763
5764 if (OverflowBehaviorType *OBT =
5765 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5766 return QualType(OBT, 0);
5767 }
5768
5769 QualType Canonical;
5770 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5771 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5772 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5773 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5774 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5775 "Shouldn't be in the map");
5776 }
5777
5778 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5779 OverflowBehaviorType(Canonical, Underlying, Kind);
5780
5781 Types.push_back(Ty);
5782 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5783 return QualType(Ty, 0);
5784}
5785
5787 QualType Wrapped, QualType Contained,
5788 const HLSLAttributedResourceType::Attributes &Attrs) {
5789
5790 llvm::FoldingSetNodeID ID;
5791 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5792
5793 void *InsertPos = nullptr;
5794 HLSLAttributedResourceType *Ty =
5795 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5796 if (Ty)
5797 return QualType(Ty, 0);
5798
5799 Ty = new (*this, alignof(HLSLAttributedResourceType))
5800 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5801
5802 Types.push_back(Ty);
5803 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5804
5805 return QualType(Ty, 0);
5806}
5807
5808QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5809 uint32_t Alignment,
5810 ArrayRef<SpirvOperand> Operands) {
5811 llvm::FoldingSetNodeID ID;
5812 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5813
5814 void *InsertPos = nullptr;
5815 HLSLInlineSpirvType *Ty =
5816 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5817 if (Ty)
5818 return QualType(Ty, 0);
5819
5820 void *Mem = Allocate(
5821 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5822 alignof(HLSLInlineSpirvType));
5823
5824 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5825
5826 Types.push_back(Ty);
5827 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5828
5829 return QualType(Ty, 0);
5830}
5831
5832/// Retrieve a substitution-result type.
5834 Decl *AssociatedDecl,
5835 unsigned Index,
5836 UnsignedOrNone PackIndex,
5837 bool Final) const {
5838 llvm::FoldingSetNodeID ID;
5839 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5840 PackIndex, Final);
5841 void *InsertPos = nullptr;
5842 SubstTemplateTypeParmType *SubstParm =
5843 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5844
5845 if (!SubstParm) {
5846 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5847 !Replacement.isCanonical()),
5848 alignof(SubstTemplateTypeParmType));
5849 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5850 Index, PackIndex, Final);
5851 Types.push_back(SubstParm);
5852 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5853 }
5854
5855 return QualType(SubstParm, 0);
5856}
5857
5860 unsigned Index, bool Final,
5861 const TemplateArgument &ArgPack) {
5862#ifndef NDEBUG
5863 for (const auto &P : ArgPack.pack_elements())
5864 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5865#endif
5866
5867 llvm::FoldingSetNodeID ID;
5868 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5869 ArgPack);
5870 void *InsertPos = nullptr;
5871 if (SubstTemplateTypeParmPackType *SubstParm =
5872 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5873 return QualType(SubstParm, 0);
5874
5875 QualType Canon;
5876 {
5877 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5878 if (!AssociatedDecl->isCanonicalDecl() ||
5879 !CanonArgPack.structurallyEquals(ArgPack)) {
5881 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5882 [[maybe_unused]] const auto *Nothing =
5883 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5884 assert(!Nothing);
5885 }
5886 }
5887
5888 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5889 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5890 ArgPack);
5891 Types.push_back(SubstParm);
5892 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5893 return QualType(SubstParm, 0);
5894}
5895
5898 assert(llvm::all_of(ArgPack.pack_elements(),
5899 [](const auto &P) {
5900 return P.getKind() == TemplateArgument::Type;
5901 }) &&
5902 "Pack contains a non-type");
5903
5904 llvm::FoldingSetNodeID ID;
5905 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5906
5907 void *InsertPos = nullptr;
5908 if (auto *T =
5909 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5910 return QualType(T, 0);
5911
5912 QualType Canon;
5913 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5914 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5915 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5916 // Refresh InsertPos, in case the recursive call above caused rehashing,
5917 // which would invalidate the bucket pointer.
5918 [[maybe_unused]] const auto *Nothing =
5919 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5920 assert(!Nothing);
5921 }
5922
5923 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5924 SubstBuiltinTemplatePackType(Canon, ArgPack);
5925 Types.push_back(PackType);
5926 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5927 return QualType(PackType, 0);
5928}
5929
5930/// Retrieve the template type parameter type for a template
5931/// parameter or parameter pack with the given depth, index, and (optionally)
5932/// name.
5933QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5934 bool ParameterPack,
5935 TemplateTypeParmDecl *TTPDecl) const {
5936 llvm::FoldingSetNodeID ID;
5937 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5938 void *InsertPos = nullptr;
5939 TemplateTypeParmType *TypeParm
5940 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5941
5942 if (TypeParm)
5943 return QualType(TypeParm, 0);
5944
5945 if (TTPDecl) {
5946 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5947 TypeParm = new (*this, alignof(TemplateTypeParmType))
5948 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5949
5950 TemplateTypeParmType *TypeCheck
5951 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5952 assert(!TypeCheck && "Template type parameter canonical type broken");
5953 (void)TypeCheck;
5954 } else
5955 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5956 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5957
5958 Types.push_back(TypeParm);
5959 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5960
5961 return QualType(TypeParm, 0);
5962}
5963
5966 switch (Keyword) {
5967 // These are just themselves.
5973 return Keyword;
5974
5975 // These are equivalent.
5978
5979 // These are functionally equivalent, so relying on their equivalence is
5980 // IFNDR. By making them equivalent, we disallow overloading, which at least
5981 // can produce a diagnostic.
5984 }
5985 llvm_unreachable("unexpected keyword kind");
5986}
5987
5989 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5990 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5991 TemplateName Name, SourceLocation NameLoc,
5992 const TemplateArgumentListInfo &SpecifiedArgs,
5993 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5995 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5996
5999 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6000 SpecifiedArgs);
6001 return TSI;
6002}
6003
6006 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6007 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6008 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6009 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6010 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6011 SpecifiedArgVec.push_back(Arg.getArgument());
6012
6013 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6014 CanonicalArgs, Underlying);
6015}
6016
6017[[maybe_unused]] static bool
6019 for (const TemplateArgument &Arg : Args)
6020 if (Arg.isPackExpansion())
6021 return true;
6022 return false;
6023}
6024
6027 ArrayRef<TemplateArgument> Args) const {
6028 assert(Template ==
6029 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6031 Template.getAsDependentTemplateName()));
6032#ifndef NDEBUG
6033 for (const auto &Arg : Args)
6034 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6035#endif
6036
6037 llvm::FoldingSetNodeID ID;
6038 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6039 *this);
6040 void *InsertPos = nullptr;
6041 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6042 return QualType(T, 0);
6043
6044 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6045 sizeof(TemplateArgument) * Args.size(),
6046 alignof(TemplateSpecializationType));
6047 auto *Spec =
6048 new (Mem) TemplateSpecializationType(Keyword, Template,
6049 /*IsAlias=*/false, Args, QualType());
6050 assert(Spec->isDependentType() &&
6051 "canonical template specialization must be dependent");
6052 Types.push_back(Spec);
6053 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6054 return QualType(Spec, 0);
6055}
6056
6059 ArrayRef<TemplateArgument> SpecifiedArgs,
6060 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6061 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6062 bool IsTypeAlias = TD && TD->isTypeAlias();
6063 if (Underlying.isNull()) {
6064 TemplateName CanonTemplate =
6065 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6066 ElaboratedTypeKeyword CanonKeyword =
6067 CanonTemplate.getAsDependentTemplateName()
6070 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6072 if (CanonicalArgs.empty()) {
6073 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6074 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6075 CanonicalArgs = CanonArgsVec;
6076 } else {
6077 NonCanonical |= !llvm::equal(
6078 SpecifiedArgs, CanonicalArgs,
6079 [](const TemplateArgument &A, const TemplateArgument &B) {
6080 return A.structurallyEquals(B);
6081 });
6082 }
6083
6084 // We can get here with an alias template when the specialization
6085 // contains a pack expansion that does not match up with a parameter
6086 // pack, or a builtin template which cannot be resolved due to dependency.
6087 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6088 hasAnyPackExpansions(CanonicalArgs)) &&
6089 "Caller must compute aliased type");
6090 IsTypeAlias = false;
6091
6093 CanonKeyword, CanonTemplate, CanonicalArgs);
6094 if (!NonCanonical)
6095 return Underlying;
6096 }
6097 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6098 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6099 (IsTypeAlias ? sizeof(QualType) : 0),
6100 alignof(TemplateSpecializationType));
6101 auto *Spec = new (Mem) TemplateSpecializationType(
6102 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6103 Types.push_back(Spec);
6104 return QualType(Spec, 0);
6105}
6106
6109 llvm::FoldingSetNodeID ID;
6110 ParenType::Profile(ID, InnerType);
6111
6112 void *InsertPos = nullptr;
6113 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6114 if (T)
6115 return QualType(T, 0);
6116
6117 QualType Canon = InnerType;
6118 if (!Canon.isCanonical()) {
6119 Canon = getCanonicalType(InnerType);
6120 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6121 assert(!CheckT && "Paren canonical type broken");
6122 (void)CheckT;
6123 }
6124
6125 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6126 Types.push_back(T);
6127 ParenTypes.InsertNode(T, InsertPos);
6128 return QualType(T, 0);
6129}
6130
6133 const IdentifierInfo *MacroII) const {
6134 QualType Canon = UnderlyingTy;
6135 if (!Canon.isCanonical())
6136 Canon = getCanonicalType(UnderlyingTy);
6137
6138 auto *newType = new (*this, alignof(MacroQualifiedType))
6139 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6140 Types.push_back(newType);
6141 return QualType(newType, 0);
6142}
6143
6146 const IdentifierInfo *Name) const {
6147 llvm::FoldingSetNodeID ID;
6148 DependentNameType::Profile(ID, Keyword, NNS, Name);
6149
6150 void *InsertPos = nullptr;
6151 if (DependentNameType *T =
6152 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6153 return QualType(T, 0);
6154
6155 ElaboratedTypeKeyword CanonKeyword =
6157 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6158
6159 QualType Canon;
6160 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6161 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6162 [[maybe_unused]] DependentNameType *T =
6163 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6164 assert(!T && "broken canonicalization");
6165 assert(Canon.isCanonical());
6166 }
6167
6168 DependentNameType *T = new (*this, alignof(DependentNameType))
6169 DependentNameType(Keyword, NNS, Name, Canon);
6170 Types.push_back(T);
6171 DependentNameTypes.InsertNode(T, InsertPos);
6172 return QualType(T, 0);
6173}
6174
6176 TemplateArgument Arg;
6177 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6179 if (TTP->isParameterPack())
6180 ArgType = getPackExpansionType(ArgType, std::nullopt);
6181
6183 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6184 QualType T =
6185 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6186 // For class NTTPs, ensure we include the 'const' so the type matches that
6187 // of a real template argument.
6188 // FIXME: It would be more faithful to model this as something like an
6189 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6191 if (T->isRecordType()) {
6192 // C++ [temp.param]p8: An id-expression naming a non-type
6193 // template-parameter of class type T denotes a static storage duration
6194 // object of type const T.
6195 T.addConst();
6196 VK = VK_LValue;
6197 } else {
6198 VK = Expr::getValueKindForType(NTTP->getType());
6199 }
6200 Expr *E = new (*this)
6201 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6202 T, VK, NTTP->getLocation());
6203
6204 if (NTTP->isParameterPack())
6205 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6206 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6207 } else {
6208 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6210 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6211 TemplateName(TTP));
6212 if (TTP->isParameterPack())
6213 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6214 else
6215 Arg = TemplateArgument(Name);
6216 }
6217
6218 if (Param->isTemplateParameterPack())
6219 Arg =
6220 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6221
6222 return Arg;
6223}
6224
6226 UnsignedOrNone NumExpansions,
6227 bool ExpectPackInType) const {
6228 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6229 "Pack expansions must expand one or more parameter packs");
6230
6231 llvm::FoldingSetNodeID ID;
6232 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6233
6234 void *InsertPos = nullptr;
6235 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6236 if (T)
6237 return QualType(T, 0);
6238
6239 QualType Canon;
6240 if (!Pattern.isCanonical()) {
6241 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6242 /*ExpectPackInType=*/false);
6243
6244 // Find the insert position again, in case we inserted an element into
6245 // PackExpansionTypes and invalidated our insert position.
6246 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6247 }
6248
6249 T = new (*this, alignof(PackExpansionType))
6250 PackExpansionType(Pattern, Canon, NumExpansions);
6251 Types.push_back(T);
6252 PackExpansionTypes.InsertNode(T, InsertPos);
6253 return QualType(T, 0);
6254}
6255
6256/// CmpProtocolNames - Comparison predicate for sorting protocols
6257/// alphabetically.
6258static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6259 ObjCProtocolDecl *const *RHS) {
6260 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6261}
6262
6264 if (Protocols.empty()) return true;
6265
6266 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6267 return false;
6268
6269 for (unsigned i = 1; i != Protocols.size(); ++i)
6270 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6271 Protocols[i]->getCanonicalDecl() != Protocols[i])
6272 return false;
6273 return true;
6274}
6275
6276static void
6278 // Sort protocols, keyed by name.
6279 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6280
6281 // Canonicalize.
6282 for (ObjCProtocolDecl *&P : Protocols)
6283 P = P->getCanonicalDecl();
6284
6285 // Remove duplicates.
6286 auto ProtocolsEnd = llvm::unique(Protocols);
6287 Protocols.erase(ProtocolsEnd, Protocols.end());
6288}
6289
6291 ObjCProtocolDecl * const *Protocols,
6292 unsigned NumProtocols) const {
6293 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6294 /*isKindOf=*/false);
6295}
6296
6298 QualType baseType,
6299 ArrayRef<QualType> typeArgs,
6301 bool isKindOf) const {
6302 // If the base type is an interface and there aren't any protocols or
6303 // type arguments to add, then the interface type will do just fine.
6304 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6305 isa<ObjCInterfaceType>(baseType))
6306 return baseType;
6307
6308 // Look in the folding set for an existing type.
6309 llvm::FoldingSetNodeID ID;
6310 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6311 void *InsertPos = nullptr;
6312 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6313 return QualType(QT, 0);
6314
6315 // Determine the type arguments to be used for canonicalization,
6316 // which may be explicitly specified here or written on the base
6317 // type.
6318 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6319 if (effectiveTypeArgs.empty()) {
6320 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6321 effectiveTypeArgs = baseObject->getTypeArgs();
6322 }
6323
6324 // Build the canonical type, which has the canonical base type and a
6325 // sorted-and-uniqued list of protocols and the type arguments
6326 // canonicalized.
6327 QualType canonical;
6328 bool typeArgsAreCanonical = llvm::all_of(
6329 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6330 bool protocolsSorted = areSortedAndUniqued(protocols);
6331 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6332 // Determine the canonical type arguments.
6333 ArrayRef<QualType> canonTypeArgs;
6334 SmallVector<QualType, 4> canonTypeArgsVec;
6335 if (!typeArgsAreCanonical) {
6336 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6337 for (auto typeArg : effectiveTypeArgs)
6338 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6339 canonTypeArgs = canonTypeArgsVec;
6340 } else {
6341 canonTypeArgs = effectiveTypeArgs;
6342 }
6343
6344 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6345 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6346 if (!protocolsSorted) {
6347 canonProtocolsVec.append(protocols.begin(), protocols.end());
6348 SortAndUniqueProtocols(canonProtocolsVec);
6349 canonProtocols = canonProtocolsVec;
6350 } else {
6351 canonProtocols = protocols;
6352 }
6353
6354 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6355 canonProtocols, isKindOf);
6356
6357 // Regenerate InsertPos.
6358 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6359 }
6360
6361 unsigned size = sizeof(ObjCObjectTypeImpl);
6362 size += typeArgs.size() * sizeof(QualType);
6363 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6364 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6365 auto *T =
6366 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6367 isKindOf);
6368
6369 Types.push_back(T);
6370 ObjCObjectTypes.InsertNode(T, InsertPos);
6371 return QualType(T, 0);
6372}
6373
6374/// Apply Objective-C protocol qualifiers to the given type.
6375/// If this is for the canonical type of a type parameter, we can apply
6376/// protocol qualifiers on the ObjCObjectPointerType.
6379 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6380 bool allowOnPointerType) const {
6381 hasError = false;
6382
6383 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6384 return getObjCTypeParamType(objT->getDecl(), protocols);
6385 }
6386
6387 // Apply protocol qualifiers to ObjCObjectPointerType.
6388 if (allowOnPointerType) {
6389 if (const auto *objPtr =
6390 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6391 const ObjCObjectType *objT = objPtr->getObjectType();
6392 // Merge protocol lists and construct ObjCObjectType.
6394 protocolsVec.append(objT->qual_begin(),
6395 objT->qual_end());
6396 protocolsVec.append(protocols.begin(), protocols.end());
6397 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6399 objT->getBaseType(),
6400 objT->getTypeArgsAsWritten(),
6401 protocols,
6402 objT->isKindOfTypeAsWritten());
6404 }
6405 }
6406
6407 // Apply protocol qualifiers to ObjCObjectType.
6408 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6409 // FIXME: Check for protocols to which the class type is already
6410 // known to conform.
6411
6412 return getObjCObjectType(objT->getBaseType(),
6413 objT->getTypeArgsAsWritten(),
6414 protocols,
6415 objT->isKindOfTypeAsWritten());
6416 }
6417
6418 // If the canonical type is ObjCObjectType, ...
6419 if (type->isObjCObjectType()) {
6420 // Silently overwrite any existing protocol qualifiers.
6421 // TODO: determine whether that's the right thing to do.
6422
6423 // FIXME: Check for protocols to which the class type is already
6424 // known to conform.
6425 return getObjCObjectType(type, {}, protocols, false);
6426 }
6427
6428 // id<protocol-list>
6429 if (type->isObjCIdType()) {
6430 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6431 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6432 objPtr->isKindOfType());
6434 }
6435
6436 // Class<protocol-list>
6437 if (type->isObjCClassType()) {
6438 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6439 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6440 objPtr->isKindOfType());
6442 }
6443
6444 hasError = true;
6445 return type;
6446}
6447
6450 ArrayRef<ObjCProtocolDecl *> protocols) const {
6451 // Look in the folding set for an existing type.
6452 llvm::FoldingSetNodeID ID;
6453 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6454 void *InsertPos = nullptr;
6455 if (ObjCTypeParamType *TypeParam =
6456 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6457 return QualType(TypeParam, 0);
6458
6459 // We canonicalize to the underlying type.
6460 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6461 if (!protocols.empty()) {
6462 // Apply the protocol qualifers.
6463 bool hasError;
6465 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6466 assert(!hasError && "Error when apply protocol qualifier to bound type");
6467 }
6468
6469 unsigned size = sizeof(ObjCTypeParamType);
6470 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6471 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6472 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6473
6474 Types.push_back(newType);
6475 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6476 return QualType(newType, 0);
6477}
6478
6480 ObjCTypeParamDecl *New) const {
6481 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6482 // Update TypeForDecl after updating TypeSourceInfo.
6483 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6485 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6486 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6487 New->TypeForDecl = UpdatedTy.getTypePtr();
6488}
6489
6490/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6491/// protocol list adopt all protocols in QT's qualified-id protocol
6492/// list.
6494 ObjCInterfaceDecl *IC) {
6495 if (!QT->isObjCQualifiedIdType())
6496 return false;
6497
6498 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6499 // If both the right and left sides have qualifiers.
6500 for (auto *Proto : OPT->quals()) {
6501 if (!IC->ClassImplementsProtocol(Proto, false))
6502 return false;
6503 }
6504 return true;
6505 }
6506 return false;
6507}
6508
6509/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6510/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6511/// of protocols.
6513 ObjCInterfaceDecl *IDecl) {
6514 if (!QT->isObjCQualifiedIdType())
6515 return false;
6516 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6517 if (!OPT)
6518 return false;
6519 if (!IDecl->hasDefinition())
6520 return false;
6522 CollectInheritedProtocols(IDecl, InheritedProtocols);
6523 if (InheritedProtocols.empty())
6524 return false;
6525 // Check that if every protocol in list of id<plist> conforms to a protocol
6526 // of IDecl's, then bridge casting is ok.
6527 bool Conforms = false;
6528 for (auto *Proto : OPT->quals()) {
6529 Conforms = false;
6530 for (auto *PI : InheritedProtocols) {
6531 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6532 Conforms = true;
6533 break;
6534 }
6535 }
6536 if (!Conforms)
6537 break;
6538 }
6539 if (Conforms)
6540 return true;
6541
6542 for (auto *PI : InheritedProtocols) {
6543 // If both the right and left sides have qualifiers.
6544 bool Adopts = false;
6545 for (auto *Proto : OPT->quals()) {
6546 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6547 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6548 break;
6549 }
6550 if (!Adopts)
6551 return false;
6552 }
6553 return true;
6554}
6555
6556/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6557/// the given object type.
6559 llvm::FoldingSetNodeID ID;
6560 ObjCObjectPointerType::Profile(ID, ObjectT);
6561
6562 void *InsertPos = nullptr;
6563 if (ObjCObjectPointerType *QT =
6564 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6565 return QualType(QT, 0);
6566
6567 // Find the canonical object type.
6568 QualType Canonical;
6569 if (!ObjectT.isCanonical()) {
6570 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6571
6572 // Regenerate InsertPos.
6573 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6574 }
6575
6576 // No match.
6577 void *Mem =
6579 auto *QType =
6580 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6581
6582 Types.push_back(QType);
6583 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6584 return QualType(QType, 0);
6585}
6586
6587/// getObjCInterfaceType - Return the unique reference to the type for the
6588/// specified ObjC interface decl. The list of protocols is optional.
6590 ObjCInterfaceDecl *PrevDecl) const {
6591 if (Decl->TypeForDecl)
6592 return QualType(Decl->TypeForDecl, 0);
6593
6594 if (PrevDecl) {
6595 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6596 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6597 return QualType(PrevDecl->TypeForDecl, 0);
6598 }
6599
6600 // Prefer the definition, if there is one.
6601 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6602 Decl = Def;
6603
6604 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6605 auto *T = new (Mem) ObjCInterfaceType(Decl);
6606 Decl->TypeForDecl = T;
6607 Types.push_back(T);
6608 return QualType(T, 0);
6609}
6610
6611/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6612/// TypeOfExprType AST's (since expression's are never shared). For example,
6613/// multiple declarations that refer to "typeof(x)" all contain different
6614/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6615/// on canonical type's (which are always unique).
6617 TypeOfExprType *toe;
6618 if (tofExpr->isTypeDependent()) {
6619 llvm::FoldingSetNodeID ID;
6620 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6621 Kind == TypeOfKind::Unqualified);
6622
6623 void *InsertPos = nullptr;
6625 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6626 if (Canon) {
6627 // We already have a "canonical" version of an identical, dependent
6628 // typeof(expr) type. Use that as our canonical type.
6629 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6630 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6631 } else {
6632 // Build a new, canonical typeof(expr) type.
6633 Canon = new (*this, alignof(DependentTypeOfExprType))
6634 DependentTypeOfExprType(*this, tofExpr, Kind);
6635 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6636 toe = Canon;
6637 }
6638 } else {
6639 QualType Canonical = getCanonicalType(tofExpr->getType());
6640 toe = new (*this, alignof(TypeOfExprType))
6641 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6642 }
6643 Types.push_back(toe);
6644 return QualType(toe, 0);
6645}
6646
6647/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6648/// TypeOfType nodes. The only motivation to unique these nodes would be
6649/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6650/// an issue. This doesn't affect the type checker, since it operates
6651/// on canonical types (which are always unique).
6653 QualType Canonical = getCanonicalType(tofType);
6654 auto *tot = new (*this, alignof(TypeOfType))
6655 TypeOfType(*this, tofType, Canonical, Kind);
6656 Types.push_back(tot);
6657 return QualType(tot, 0);
6658}
6659
6660/// getReferenceQualifiedType - Given an expr, will return the type for
6661/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6662/// and class member access into account.
6664 // C++11 [dcl.type.simple]p4:
6665 // [...]
6666 QualType T = E->getType();
6667 switch (E->getValueKind()) {
6668 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6669 // type of e;
6670 case VK_XValue:
6671 return getRValueReferenceType(T);
6672 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6673 // type of e;
6674 case VK_LValue:
6675 return getLValueReferenceType(T);
6676 // - otherwise, decltype(e) is the type of e.
6677 case VK_PRValue:
6678 return T;
6679 }
6680 llvm_unreachable("Unknown value kind");
6681}
6682
6683/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6684/// nodes. This would never be helpful, since each such type has its own
6685/// expression, and would not give a significant memory saving, since there
6686/// is an Expr tree under each such type.
6688 // C++11 [temp.type]p2:
6689 // If an expression e involves a template parameter, decltype(e) denotes a
6690 // unique dependent type. Two such decltype-specifiers refer to the same
6691 // type only if their expressions are equivalent (14.5.6.1).
6692 QualType CanonType;
6693 if (!E->isInstantiationDependent()) {
6694 CanonType = getCanonicalType(UnderlyingType);
6695 } else if (!UnderlyingType.isNull()) {
6696 CanonType = getDecltypeType(E, QualType());
6697 } else {
6698 llvm::FoldingSetNodeID ID;
6699 DependentDecltypeType::Profile(ID, *this, E);
6700
6701 void *InsertPos = nullptr;
6702 if (DependentDecltypeType *Canon =
6703 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6704 return QualType(Canon, 0);
6705
6706 // Build a new, canonical decltype(expr) type.
6707 auto *DT =
6708 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6709 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6710 Types.push_back(DT);
6711 return QualType(DT, 0);
6712 }
6713 auto *DT = new (*this, alignof(DecltypeType))
6714 DecltypeType(E, UnderlyingType, CanonType);
6715 Types.push_back(DT);
6716 return QualType(DT, 0);
6717}
6718
6720 bool FullySubstituted,
6721 ArrayRef<QualType> Expansions,
6722 UnsignedOrNone Index) const {
6723 QualType Canonical;
6724 if (FullySubstituted && Index) {
6725 Canonical = getCanonicalType(Expansions[*Index]);
6726 } else {
6727 llvm::FoldingSetNodeID ID;
6728 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6729 FullySubstituted, Expansions);
6730 void *InsertPos = nullptr;
6731 PackIndexingType *Canon =
6732 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6733 if (!Canon) {
6734 void *Mem = Allocate(
6735 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6737 Canon =
6738 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6739 IndexExpr, FullySubstituted, Expansions);
6740 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6741 }
6742 Canonical = QualType(Canon, 0);
6743 }
6744
6745 void *Mem =
6746 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6748 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6749 FullySubstituted, Expansions);
6750 Types.push_back(T);
6751 return QualType(T, 0);
6752}
6753
6754/// getUnaryTransformationType - We don't unique these, since the memory
6755/// savings are minimal and these are rare.
6758 UnaryTransformType::UTTKind Kind) const {
6759
6760 llvm::FoldingSetNodeID ID;
6761 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6762
6763 void *InsertPos = nullptr;
6764 if (UnaryTransformType *UT =
6765 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6766 return QualType(UT, 0);
6767
6768 QualType CanonType;
6769 if (!BaseType->isDependentType()) {
6770 CanonType = UnderlyingType.getCanonicalType();
6771 } else {
6772 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6773 UnderlyingType = QualType();
6774 if (QualType CanonBase = BaseType.getCanonicalType();
6775 BaseType != CanonBase) {
6776 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6777 assert(CanonType.isCanonical());
6778
6779 // Find the insertion position again.
6780 [[maybe_unused]] UnaryTransformType *UT =
6781 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6782 assert(!UT && "broken canonicalization");
6783 }
6784 }
6785
6786 auto *UT = new (*this, alignof(UnaryTransformType))
6787 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6788 UnaryTransformTypes.InsertNode(UT, InsertPos);
6789 Types.push_back(UT);
6790 return QualType(UT, 0);
6791}
6792
6793QualType ASTContext::getAutoTypeInternal(
6794 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6795 bool IsPack, TemplateDecl *TypeConstraintConcept,
6796 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6797 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6798 !TypeConstraintConcept && !IsDependent)
6799 return getAutoDeductType();
6800
6801 // Look in the folding set for an existing type.
6802 llvm::FoldingSetNodeID ID;
6803 bool IsDeducedDependent =
6804 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6805 (!DeducedType.isNull() && DeducedType->isDependentType());
6806 AutoType::Profile(ID, *this, DeducedType, Keyword,
6807 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6808 TypeConstraintArgs);
6809 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6810 return QualType(AT_iter->getSecond(), 0);
6811
6812 QualType Canon;
6813 if (!IsCanon) {
6814 if (!DeducedType.isNull()) {
6815 Canon = DeducedType.getCanonicalType();
6816 } else if (TypeConstraintConcept) {
6817 bool AnyNonCanonArgs = false;
6818 auto *CanonicalConcept =
6819 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6820 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6821 *this, TypeConstraintArgs, AnyNonCanonArgs);
6822 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6823 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6824 CanonicalConcept, CanonicalConceptArgs,
6825 /*IsCanon=*/true);
6826 }
6827 }
6828 }
6829
6830 void *Mem = Allocate(sizeof(AutoType) +
6831 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6832 alignof(AutoType));
6833 auto *AT = new (Mem) AutoType(
6834 DeducedType, Keyword,
6835 (IsDependent ? TypeDependence::DependentInstantiation
6836 : TypeDependence::None) |
6837 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6838 Canon, TypeConstraintConcept, TypeConstraintArgs);
6839#ifndef NDEBUG
6840 llvm::FoldingSetNodeID InsertedID;
6841 AT->Profile(InsertedID, *this);
6842 assert(InsertedID == ID && "ID does not match");
6843#endif
6844 Types.push_back(AT);
6845 AutoTypes.try_emplace(ID, AT);
6846 return QualType(AT, 0);
6847}
6848
6849/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6850/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6851/// canonical deduced-but-dependent 'auto' type.
6852QualType
6854 bool IsDependent, bool IsPack,
6855 TemplateDecl *TypeConstraintConcept,
6856 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6857 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6858 assert((!IsDependent || DeducedType.isNull()) &&
6859 "A dependent auto should be undeduced");
6860 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6861 TypeConstraintConcept, TypeConstraintArgs);
6862}
6863
6866
6867 // Remove a type-constraint from a top-level auto or decltype(auto).
6868 if (auto *AT = CanonT->getAs<AutoType>()) {
6869 if (!AT->isConstrained())
6870 return T;
6871 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6872 AT->isDependentType(),
6873 AT->containsUnexpandedParameterPack()),
6874 T.getQualifiers());
6875 }
6876
6877 // FIXME: We only support constrained auto at the top level in the type of a
6878 // non-type template parameter at the moment. Once we lift that restriction,
6879 // we'll need to recursively build types containing auto here.
6880 assert(!CanonT->getContainedAutoType() ||
6881 !CanonT->getContainedAutoType()->isConstrained());
6882 return T;
6883}
6884
6885QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6887 bool IsDependent, QualType Canon) const {
6888 // Look in the folding set for an existing type.
6889 void *InsertPos = nullptr;
6890 llvm::FoldingSetNodeID ID;
6891 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6892 IsDependent);
6893 if (DeducedTemplateSpecializationType *DTST =
6894 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6895 return QualType(DTST, 0);
6896
6897 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6898 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6899 IsDependent, Canon);
6900
6901#ifndef NDEBUG
6902 llvm::FoldingSetNodeID TempID;
6903 DTST->Profile(TempID);
6904 assert(ID == TempID && "ID does not match");
6905#endif
6906 Types.push_back(DTST);
6907 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6908 return QualType(DTST, 0);
6909}
6910
6911/// Return the uniqued reference to the deduced template specialization type
6912/// which has been deduced to the given type, or to the canonical undeduced
6913/// such type, or the canonical deduced-but-dependent such type.
6916 bool IsDependent) const {
6917 // FIXME: This could save an extra hash table lookup if it handled all the
6918 // parameters already being canonical.
6919 // FIXME: Can this be formed from a DependentTemplateName, such that the
6920 // keyword should be part of the canonical type?
6921 QualType Canon =
6922 DeducedType.isNull()
6923 ? getDeducedTemplateSpecializationTypeInternal(
6925 QualType(), IsDependent, QualType())
6926 : DeducedType.getCanonicalType();
6927 return getDeducedTemplateSpecializationTypeInternal(
6928 Keyword, Template, DeducedType, IsDependent, Canon);
6929}
6930
6931/// getAtomicType - Return the uniqued reference to the atomic type for
6932/// the given value type.
6934 // Unique pointers, to guarantee there is only one pointer of a particular
6935 // structure.
6936 llvm::FoldingSetNodeID ID;
6937 AtomicType::Profile(ID, T);
6938
6939 void *InsertPos = nullptr;
6940 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6941 return QualType(AT, 0);
6942
6943 // If the atomic value type isn't canonical, this won't be a canonical type
6944 // either, so fill in the canonical type field.
6945 QualType Canonical;
6946 if (!T.isCanonical()) {
6947 Canonical = getAtomicType(getCanonicalType(T));
6948
6949 // Get the new insert position for the node we care about.
6950 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6951 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6952 }
6953 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6954 Types.push_back(New);
6955 AtomicTypes.InsertNode(New, InsertPos);
6956 return QualType(New, 0);
6957}
6958
6959/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6961 if (AutoDeductTy.isNull())
6962 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6963 AutoType(QualType(), AutoTypeKeyword::Auto,
6964 TypeDependence::None, QualType(),
6965 /*concept*/ nullptr, /*args*/ {}),
6966 0);
6967 return AutoDeductTy;
6968}
6969
6970/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6972 if (AutoRRefDeductTy.isNull())
6974 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6975 return AutoRRefDeductTy;
6976}
6977
6978/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6979/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6980/// needs to agree with the definition in <stddef.h>.
6984
6986 return getFromTargetType(Target->getSizeType());
6987}
6988
6989/// Return the unique signed counterpart of the integer type
6990/// corresponding to size_t.
6994
6995/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6996/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7000
7001/// Return the unique unsigned counterpart of "ptrdiff_t"
7002/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7003/// in the definition of %tu format specifier.
7005 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7006}
7007
7008/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7010 return getFromTargetType(Target->getIntMaxType());
7011}
7012
7013/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7015 return getFromTargetType(Target->getUIntMaxType());
7016}
7017
7018/// getSignedWCharType - Return the type of "signed wchar_t".
7019/// Used when in C++, as a GCC extension.
7021 // FIXME: derive from "Target" ?
7022 return WCharTy;
7023}
7024
7025/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7026/// Used when in C++, as a GCC extension.
7028 // FIXME: derive from "Target" ?
7029 return UnsignedIntTy;
7030}
7031
7033 return getFromTargetType(Target->getIntPtrType());
7034}
7035
7039
7040/// Return the unique type for "pid_t" defined in
7041/// <sys/types.h>. We need this to compute the correct type for vfork().
7043 return getFromTargetType(Target->getProcessIDType());
7044}
7045
7046//===----------------------------------------------------------------------===//
7047// Type Operators
7048//===----------------------------------------------------------------------===//
7049
7051 // Push qualifiers into arrays, and then discard any remaining
7052 // qualifiers.
7053 T = getCanonicalType(T);
7055 const Type *Ty = T.getTypePtr();
7059 } else if (isa<ArrayType>(Ty)) {
7061 } else if (isa<FunctionType>(Ty)) {
7062 Result = getPointerType(QualType(Ty, 0));
7063 } else {
7064 Result = QualType(Ty, 0);
7065 }
7066
7068}
7069
7071 Qualifiers &quals) const {
7072 SplitQualType splitType = type.getSplitUnqualifiedType();
7073
7074 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7075 // the unqualified desugared type and then drops it on the floor.
7076 // We then have to strip that sugar back off with
7077 // getUnqualifiedDesugaredType(), which is silly.
7078 const auto *AT =
7079 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7080
7081 // If we don't have an array, just use the results in splitType.
7082 if (!AT) {
7083 quals = splitType.Quals;
7084 return QualType(splitType.Ty, 0);
7085 }
7086
7087 // Otherwise, recurse on the array's element type.
7088 QualType elementType = AT->getElementType();
7089 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7090
7091 // If that didn't change the element type, AT has no qualifiers, so we
7092 // can just use the results in splitType.
7093 if (elementType == unqualElementType) {
7094 assert(quals.empty()); // from the recursive call
7095 quals = splitType.Quals;
7096 return QualType(splitType.Ty, 0);
7097 }
7098
7099 // Otherwise, add in the qualifiers from the outermost type, then
7100 // build the type back up.
7101 quals.addConsistentQualifiers(splitType.Quals);
7102
7103 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7104 return getConstantArrayType(unqualElementType, CAT->getSize(),
7105 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7106 }
7107
7108 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7109 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7110 }
7111
7112 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7113 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7114 VAT->getSizeModifier(),
7115 VAT->getIndexTypeCVRQualifiers());
7116 }
7117
7118 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7119 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7120 DSAT->getSizeModifier(), 0);
7121}
7122
7123/// Attempt to unwrap two types that may both be array types with the same bound
7124/// (or both be array types of unknown bound) for the purpose of comparing the
7125/// cv-decomposition of two types per C++ [conv.qual].
7126///
7127/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7128/// C++20 [conv.qual], if permitted by the current language mode.
7130 bool AllowPiMismatch) const {
7131 while (true) {
7132 auto *AT1 = getAsArrayType(T1);
7133 if (!AT1)
7134 return;
7135
7136 auto *AT2 = getAsArrayType(T2);
7137 if (!AT2)
7138 return;
7139
7140 // If we don't have two array types with the same constant bound nor two
7141 // incomplete array types, we've unwrapped everything we can.
7142 // C++20 also permits one type to be a constant array type and the other
7143 // to be an incomplete array type.
7144 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7145 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7146 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7147 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7148 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7150 return;
7151 } else if (isa<IncompleteArrayType>(AT1)) {
7152 if (!(isa<IncompleteArrayType>(AT2) ||
7153 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7155 return;
7156 } else {
7157 return;
7158 }
7159
7160 T1 = AT1->getElementType();
7161 T2 = AT2->getElementType();
7162 }
7163}
7164
7165/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7166///
7167/// If T1 and T2 are both pointer types of the same kind, or both array types
7168/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7169/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7170///
7171/// This function will typically be called in a loop that successively
7172/// "unwraps" pointer and pointer-to-member types to compare them at each
7173/// level.
7174///
7175/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7176/// C++20 [conv.qual], if permitted by the current language mode.
7177///
7178/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7179/// pair of types that can't be unwrapped further.
7181 bool AllowPiMismatch) const {
7182 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7183
7184 const auto *T1PtrType = T1->getAs<PointerType>();
7185 const auto *T2PtrType = T2->getAs<PointerType>();
7186 if (T1PtrType && T2PtrType) {
7187 T1 = T1PtrType->getPointeeType();
7188 T2 = T2PtrType->getPointeeType();
7189 return true;
7190 }
7191
7192 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7193 *T2MPType = T2->getAs<MemberPointerType>();
7194 T1MPType && T2MPType) {
7195 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7196 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7197 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7198 return false;
7199 if (T1MPType->getQualifier().getCanonical() !=
7200 T2MPType->getQualifier().getCanonical())
7201 return false;
7202 T1 = T1MPType->getPointeeType();
7203 T2 = T2MPType->getPointeeType();
7204 return true;
7205 }
7206
7207 if (getLangOpts().ObjC) {
7208 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7209 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7210 if (T1OPType && T2OPType) {
7211 T1 = T1OPType->getPointeeType();
7212 T2 = T2OPType->getPointeeType();
7213 return true;
7214 }
7215 }
7216
7217 // FIXME: Block pointers, too?
7218
7219 return false;
7220}
7221
7223 while (true) {
7224 Qualifiers Quals;
7225 T1 = getUnqualifiedArrayType(T1, Quals);
7226 T2 = getUnqualifiedArrayType(T2, Quals);
7227 if (hasSameType(T1, T2))
7228 return true;
7229 if (!UnwrapSimilarTypes(T1, T2))
7230 return false;
7231 }
7232}
7233
7235 while (true) {
7236 Qualifiers Quals1, Quals2;
7237 T1 = getUnqualifiedArrayType(T1, Quals1);
7238 T2 = getUnqualifiedArrayType(T2, Quals2);
7239
7240 Quals1.removeCVRQualifiers();
7241 Quals2.removeCVRQualifiers();
7242 if (Quals1 != Quals2)
7243 return false;
7244
7245 if (hasSameType(T1, T2))
7246 return true;
7247
7248 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7249 return false;
7250 }
7251}
7252
7255 SourceLocation NameLoc) const {
7256 switch (Name.getKind()) {
7259 // DNInfo work in progress: CHECKME: what about DNLoc?
7261 NameLoc);
7262
7265 // DNInfo work in progress: CHECKME: what about DNLoc?
7266 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7267 }
7268
7271 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7272 }
7273
7277 DeclarationName DName;
7278 if (const IdentifierInfo *II = TN.getIdentifier()) {
7279 DName = DeclarationNames.getIdentifier(II);
7280 return DeclarationNameInfo(DName, NameLoc);
7281 } else {
7282 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7283 // DNInfo work in progress: FIXME: source locations?
7284 DeclarationNameLoc DNLoc =
7286 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7287 }
7288 }
7289
7293 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7294 NameLoc);
7295 }
7296
7301 NameLoc);
7302 }
7305 NameLoc);
7308 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7309 }
7310 }
7311
7312 llvm_unreachable("bad template name kind!");
7313}
7314
7315static const TemplateArgument *
7317 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7318 if (!TP->hasDefaultArgument())
7319 return nullptr;
7320 return &TP->getDefaultArgument().getArgument();
7321 };
7322 switch (P->getKind()) {
7323 case NamedDecl::TemplateTypeParm:
7324 return handleParam(cast<TemplateTypeParmDecl>(P));
7325 case NamedDecl::NonTypeTemplateParm:
7326 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7327 case NamedDecl::TemplateTemplateParm:
7328 return handleParam(cast<TemplateTemplateParmDecl>(P));
7329 default:
7330 llvm_unreachable("Unexpected template parameter kind");
7331 }
7332}
7333
7335 bool IgnoreDeduced) const {
7336 while (std::optional<TemplateName> UnderlyingOrNone =
7337 Name.desugar(IgnoreDeduced))
7338 Name = *UnderlyingOrNone;
7339
7340 switch (Name.getKind()) {
7343 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7345
7346 // The canonical template name is the canonical template declaration.
7347 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7348 }
7349
7351 // An assumed template is just a name, so it is already canonical.
7352 return Name;
7353
7355 llvm_unreachable("cannot canonicalize overloaded template");
7356
7359 assert(DTN && "Non-dependent template names must refer to template decls.");
7360 NestedNameSpecifier Qualifier = DTN->getQualifier();
7361 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7362 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7363 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7364 /*HasTemplateKeyword=*/true});
7365 return Name;
7366 }
7367
7371 TemplateArgument canonArgPack =
7374 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7375 subst->getIndex(), subst->getFinal());
7376 }
7378 assert(IgnoreDeduced == false);
7380 DefaultArguments DefArgs = DTS->getDefaultArguments();
7381 TemplateName Underlying = DTS->getUnderlying();
7382
7383 TemplateName CanonUnderlying =
7384 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7385 bool NonCanonical = CanonUnderlying != Underlying;
7386 auto CanonArgs =
7387 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7388
7389 ArrayRef<NamedDecl *> Params =
7390 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7391 assert(CanonArgs.size() <= Params.size());
7392 // A deduced template name which deduces the same default arguments already
7393 // declared in the underlying template is the same template as the
7394 // underlying template. We need need to note any arguments which differ from
7395 // the corresponding declaration. If any argument differs, we must build a
7396 // deduced template name.
7397 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7399 if (!A)
7400 break;
7401 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7402 TemplateArgument &CanonDefArg = CanonArgs[I];
7403 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7404 continue;
7405 // Keep popping from the back any deault arguments which are the same.
7406 if (I == int(CanonArgs.size() - 1))
7407 CanonArgs.pop_back();
7408 NonCanonical = true;
7409 }
7410 return NonCanonical ? getDeducedTemplateName(
7411 CanonUnderlying,
7412 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7413 : Name;
7414 }
7418 llvm_unreachable("always sugar node");
7419 }
7420
7421 llvm_unreachable("bad template name!");
7422}
7423
7425 const TemplateName &Y,
7426 bool IgnoreDeduced) const {
7427 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7428 getCanonicalTemplateName(Y, IgnoreDeduced);
7429}
7430
7432 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7433 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7434 return false;
7436 return false;
7437 return true;
7438}
7439
7440bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7441 if (!XCE != !YCE)
7442 return false;
7443
7444 if (!XCE)
7445 return true;
7446
7447 llvm::FoldingSetNodeID XCEID, YCEID;
7448 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7449 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7450 return XCEID == YCEID;
7451}
7452
7454 const TypeConstraint *YTC) const {
7455 if (!XTC != !YTC)
7456 return false;
7457
7458 if (!XTC)
7459 return true;
7460
7461 auto *NCX = XTC->getNamedConcept();
7462 auto *NCY = YTC->getNamedConcept();
7463 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7464 return false;
7467 return false;
7469 if (XTC->getConceptReference()
7471 ->NumTemplateArgs !=
7473 return false;
7474
7475 // Compare slowly by profiling.
7476 //
7477 // We couldn't compare the profiling result for the template
7478 // args here. Consider the following example in different modules:
7479 //
7480 // template <__integer_like _Tp, C<_Tp> Sentinel>
7481 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7482 // return __t;
7483 // }
7484 //
7485 // When we compare the profiling result for `C<_Tp>` in different
7486 // modules, it will compare the type of `_Tp` in different modules.
7487 // However, the type of `_Tp` in different modules refer to different
7488 // types here naturally. So we couldn't compare the profiling result
7489 // for the template args directly.
7492}
7493
7495 const NamedDecl *Y) const {
7496 if (X->getKind() != Y->getKind())
7497 return false;
7498
7499 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7500 auto *TY = cast<TemplateTypeParmDecl>(Y);
7501 if (TX->isParameterPack() != TY->isParameterPack())
7502 return false;
7503 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7504 return false;
7505 return isSameTypeConstraint(TX->getTypeConstraint(),
7506 TY->getTypeConstraint());
7507 }
7508
7509 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7510 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7511 return TX->isParameterPack() == TY->isParameterPack() &&
7512 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7513 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7514 TY->getPlaceholderTypeConstraint());
7515 }
7516
7518 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7519 return TX->isParameterPack() == TY->isParameterPack() &&
7520 isSameTemplateParameterList(TX->getTemplateParameters(),
7521 TY->getTemplateParameters());
7522}
7523
7525 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7526 if (X->size() != Y->size())
7527 return false;
7528
7529 for (unsigned I = 0, N = X->size(); I != N; ++I)
7530 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7531 return false;
7532
7533 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7534}
7535
7537 const NamedDecl *Y) const {
7538 // If the type parameter isn't the same already, we don't need to check the
7539 // default argument further.
7540 if (!isSameTemplateParameter(X, Y))
7541 return false;
7542
7543 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7544 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7545 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7546 return false;
7547
7548 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7549 TTPY->getDefaultArgument().getArgument().getAsType());
7550 }
7551
7552 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7553 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7554 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7555 return false;
7556
7557 Expr *DefaultArgumentX =
7558 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7559 Expr *DefaultArgumentY =
7560 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7561 llvm::FoldingSetNodeID XID, YID;
7562 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7563 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7564 return XID == YID;
7565 }
7566
7567 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7568 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7569
7570 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7571 return false;
7572
7573 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7574 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7575 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7576}
7577
7579 const NestedNameSpecifier Y) {
7580 if (X == Y)
7581 return true;
7582 if (!X || !Y)
7583 return false;
7584
7585 auto Kind = X.getKind();
7586 if (Kind != Y.getKind())
7587 return false;
7588
7589 // FIXME: For namespaces and types, we're permitted to check that the entity
7590 // is named via the same tokens. We should probably do so.
7591 switch (Kind) {
7593 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7594 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7595 if (!declaresSameEntity(NamespaceX->getNamespace(),
7596 NamespaceY->getNamespace()))
7597 return false;
7598 return isSameQualifier(PrefixX, PrefixY);
7599 }
7601 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7602 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7603 return false;
7604 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7605 }
7609 return true;
7610 }
7611 llvm_unreachable("unhandled qualifier kind");
7612}
7613
7614static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7615 if (!A->getASTContext().getLangOpts().CUDA)
7616 return true; // Target attributes are overloadable in CUDA compilation only.
7617 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7618 return false;
7619 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7620 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7621 return true; // unattributed and __host__ functions are the same.
7622}
7623
7624/// Determine whether the attributes we can overload on are identical for A and
7625/// B. Will ignore any overloadable attrs represented in the type of A and B.
7627 const FunctionDecl *B) {
7628 // Note that pass_object_size attributes are represented in the function's
7629 // ExtParameterInfo, so we don't need to check them here.
7630
7631 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7632 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7633 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7634
7635 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7636 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7637 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7638
7639 // Return false if the number of enable_if attributes is different.
7640 if (!Cand1A || !Cand2A)
7641 return false;
7642
7643 Cand1ID.clear();
7644 Cand2ID.clear();
7645
7646 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7647 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7648
7649 // Return false if any of the enable_if expressions of A and B are
7650 // different.
7651 if (Cand1ID != Cand2ID)
7652 return false;
7653 }
7654 return hasSameCudaAttrs(A, B);
7655}
7656
7657bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7658 // Caution: this function is called by the AST reader during deserialization,
7659 // so it cannot rely on AST invariants being met. Non-trivial accessors
7660 // should be avoided, along with any traversal of redeclaration chains.
7661
7662 if (X == Y)
7663 return true;
7664
7665 if (X->getDeclName() != Y->getDeclName())
7666 return false;
7667
7668 // Must be in the same context.
7669 //
7670 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7671 // could be two different declarations of the same function. (We will fix the
7672 // semantic DC to refer to the primary definition after merging.)
7673 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7675 return false;
7676
7677 // If either X or Y are local to the owning module, they are only possible to
7678 // be the same entity if they are in the same module.
7679 if (X->isModuleLocal() || Y->isModuleLocal())
7680 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7681 return false;
7682
7683 // Two typedefs refer to the same entity if they have the same underlying
7684 // type.
7685 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7686 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7687 return hasSameType(TypedefX->getUnderlyingType(),
7688 TypedefY->getUnderlyingType());
7689
7690 // Must have the same kind.
7691 if (X->getKind() != Y->getKind())
7692 return false;
7693
7694 // Objective-C classes and protocols with the same name always match.
7696 return true;
7697
7699 // No need to handle these here: we merge them when adding them to the
7700 // template.
7701 return false;
7702 }
7703
7704 // Compatible tags match.
7705 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7706 const auto *TagY = cast<TagDecl>(Y);
7707 return (TagX->getTagKind() == TagY->getTagKind()) ||
7708 ((TagX->getTagKind() == TagTypeKind::Struct ||
7709 TagX->getTagKind() == TagTypeKind::Class ||
7710 TagX->getTagKind() == TagTypeKind::Interface) &&
7711 (TagY->getTagKind() == TagTypeKind::Struct ||
7712 TagY->getTagKind() == TagTypeKind::Class ||
7713 TagY->getTagKind() == TagTypeKind::Interface));
7714 }
7715
7716 // Functions with the same type and linkage match.
7717 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7718 // functions, etc.
7719 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7720 const auto *FuncY = cast<FunctionDecl>(Y);
7721 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7722 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7723 if (CtorX->getInheritedConstructor() &&
7724 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7725 CtorY->getInheritedConstructor().getConstructor()))
7726 return false;
7727 }
7728
7729 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7730 return false;
7731
7732 // Multiversioned functions with different feature strings are represented
7733 // as separate declarations.
7734 if (FuncX->isMultiVersion()) {
7735 const auto *TAX = FuncX->getAttr<TargetAttr>();
7736 const auto *TAY = FuncY->getAttr<TargetAttr>();
7737 assert(TAX && TAY && "Multiversion Function without target attribute");
7738
7739 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7740 return false;
7741 }
7742
7743 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7744 // not the same entity if they are constrained.
7745 if ((FuncX->isMemberLikeConstrainedFriend() ||
7746 FuncY->isMemberLikeConstrainedFriend()) &&
7747 !FuncX->getLexicalDeclContext()->Equals(
7748 FuncY->getLexicalDeclContext())) {
7749 return false;
7750 }
7751
7752 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7753 FuncY->getTrailingRequiresClause()))
7754 return false;
7755
7756 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7757 // Map to the first declaration that we've already merged into this one.
7758 // The TSI of redeclarations might not match (due to calling conventions
7759 // being inherited onto the type but not the TSI), but the TSI type of
7760 // the first declaration of the function should match across modules.
7761 FD = FD->getCanonicalDecl();
7762 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7763 : FD->getType();
7764 };
7765 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7766 if (!hasSameType(XT, YT)) {
7767 // We can get functions with different types on the redecl chain in C++17
7768 // if they have differing exception specifications and at least one of
7769 // the excpetion specs is unresolved.
7770 auto *XFPT = XT->getAs<FunctionProtoType>();
7771 auto *YFPT = YT->getAs<FunctionProtoType>();
7772 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7773 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7776 return true;
7777 return false;
7778 }
7779
7780 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7781 hasSameOverloadableAttrs(FuncX, FuncY);
7782 }
7783
7784 // Variables with the same type and linkage match.
7785 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7786 const auto *VarY = cast<VarDecl>(Y);
7787 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7788 // During deserialization, we might compare variables before we load
7789 // their types. Assume the types will end up being the same.
7790 if (VarX->getType().isNull() || VarY->getType().isNull())
7791 return true;
7792
7793 if (hasSameType(VarX->getType(), VarY->getType()))
7794 return true;
7795
7796 // We can get decls with different types on the redecl chain. Eg.
7797 // template <typename T> struct S { static T Var[]; }; // #1
7798 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7799 // Only? happens when completing an incomplete array type. In this case
7800 // when comparing #1 and #2 we should go through their element type.
7801 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7802 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7803 if (!VarXTy || !VarYTy)
7804 return false;
7805 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7806 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7807 }
7808 return false;
7809 }
7810
7811 // Namespaces with the same name and inlinedness match.
7812 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7813 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7814 return NamespaceX->isInline() == NamespaceY->isInline();
7815 }
7816
7817 // Identical template names and kinds match if their template parameter lists
7818 // and patterns match.
7819 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7820 const auto *TemplateY = cast<TemplateDecl>(Y);
7821
7822 // ConceptDecl wouldn't be the same if their constraint expression differs.
7823 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7824 const auto *ConceptY = cast<ConceptDecl>(Y);
7825 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7826 ConceptY->getConstraintExpr()))
7827 return false;
7828 }
7829
7830 return isSameEntity(TemplateX->getTemplatedDecl(),
7831 TemplateY->getTemplatedDecl()) &&
7832 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7833 TemplateY->getTemplateParameters());
7834 }
7835
7836 // Fields with the same name and the same type match.
7837 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7838 const auto *FDY = cast<FieldDecl>(Y);
7839 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7840 return hasSameType(FDX->getType(), FDY->getType());
7841 }
7842
7843 // Indirect fields with the same target field match.
7844 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7845 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7846 return IFDX->getAnonField()->getCanonicalDecl() ==
7847 IFDY->getAnonField()->getCanonicalDecl();
7848 }
7849
7850 // Enumerators with the same name match.
7852 // FIXME: Also check the value is odr-equivalent.
7853 return true;
7854
7855 // Using shadow declarations with the same target match.
7856 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7857 const auto *USY = cast<UsingShadowDecl>(Y);
7858 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7859 }
7860
7861 // Using declarations with the same qualifier match. (We already know that
7862 // the name matches.)
7863 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7864 const auto *UY = cast<UsingDecl>(Y);
7865 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7866 UX->hasTypename() == UY->hasTypename() &&
7867 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7868 }
7869 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7870 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7871 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7872 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7873 }
7874 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7875 return isSameQualifier(
7876 UX->getQualifier(),
7877 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7878 }
7879
7880 // Using-pack declarations are only created by instantiation, and match if
7881 // they're instantiated from matching UnresolvedUsing...Decls.
7882 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7883 return declaresSameEntity(
7884 UX->getInstantiatedFromUsingDecl(),
7885 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7886 }
7887
7888 // Namespace alias definitions with the same target match.
7889 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7890 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7891 return NAX->getNamespace()->Equals(NAY->getNamespace());
7892 }
7893
7894 return false;
7895}
7896
7899 switch (Arg.getKind()) {
7901 return Arg;
7902
7904 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7905 Arg.getIsDefaulted());
7906
7908 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7910 Arg.getIsDefaulted());
7911 }
7912
7915 /*isNullPtr*/ true, Arg.getIsDefaulted());
7916
7919 Arg.getIsDefaulted());
7920
7922 return TemplateArgument(
7925
7928
7930 return TemplateArgument(*this,
7933
7936 /*isNullPtr*/ false, Arg.getIsDefaulted());
7937
7939 bool AnyNonCanonArgs = false;
7940 auto CanonArgs = ::getCanonicalTemplateArguments(
7941 *this, Arg.pack_elements(), AnyNonCanonArgs);
7942 if (!AnyNonCanonArgs)
7943 return Arg;
7945 const_cast<ASTContext &>(*this), CanonArgs);
7946 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7947 return NewArg;
7948 }
7949 }
7950
7951 // Silence GCC warning
7952 llvm_unreachable("Unhandled template argument kind");
7953}
7954
7956 const TemplateArgument &Arg2) const {
7957 if (Arg1.getKind() != Arg2.getKind())
7958 return false;
7959
7960 switch (Arg1.getKind()) {
7962 llvm_unreachable("Comparing NULL template argument");
7963
7965 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7966
7968 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7970
7972 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7973
7978
7980 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7981 Arg2.getAsIntegral());
7982
7984 return Arg1.structurallyEquals(Arg2);
7985
7987 llvm::FoldingSetNodeID ID1, ID2;
7988 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7989 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7990 return ID1 == ID2;
7991 }
7992
7994 return llvm::equal(
7995 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7996 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7997 return isSameTemplateArgument(Arg1, Arg2);
7998 });
7999 }
8000
8001 llvm_unreachable("Unhandled template argument kind");
8002}
8003
8005 // Handle the non-qualified case efficiently.
8006 if (!T.hasLocalQualifiers()) {
8007 // Handle the common positive case fast.
8008 if (const auto *AT = dyn_cast<ArrayType>(T))
8009 return AT;
8010 }
8011
8012 // Handle the common negative case fast.
8013 if (!isa<ArrayType>(T.getCanonicalType()))
8014 return nullptr;
8015
8016 // Apply any qualifiers from the array type to the element type. This
8017 // implements C99 6.7.3p8: "If the specification of an array type includes
8018 // any type qualifiers, the element type is so qualified, not the array type."
8019
8020 // If we get here, we either have type qualifiers on the type, or we have
8021 // sugar such as a typedef in the way. If we have type qualifiers on the type
8022 // we must propagate them down into the element type.
8023
8024 SplitQualType split = T.getSplitDesugaredType();
8025 Qualifiers qs = split.Quals;
8026
8027 // If we have a simple case, just return now.
8028 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8029 if (!ATy || qs.empty())
8030 return ATy;
8031
8032 // Otherwise, we have an array and we have qualifiers on it. Push the
8033 // qualifiers into the array element type and return a new array type.
8034 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8035
8036 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8037 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8038 CAT->getSizeExpr(),
8039 CAT->getSizeModifier(),
8040 CAT->getIndexTypeCVRQualifiers()));
8041 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8043 IAT->getSizeModifier(),
8044 IAT->getIndexTypeCVRQualifiers()));
8045
8046 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8048 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8049 DSAT->getIndexTypeCVRQualifiers()));
8050
8051 const auto *VAT = cast<VariableArrayType>(ATy);
8052 return cast<ArrayType>(
8053 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8054 VAT->getIndexTypeCVRQualifiers()));
8055}
8056
8058 if (getLangOpts().HLSL && T->isConstantArrayType())
8059 return getArrayParameterType(T);
8060 if (T->isArrayType() || T->isFunctionType())
8061 return getDecayedType(T);
8062 return T;
8063}
8064
8068 return T.getUnqualifiedType();
8069}
8070
8072 // C++ [except.throw]p3:
8073 // A throw-expression initializes a temporary object, called the exception
8074 // object, the type of which is determined by removing any top-level
8075 // cv-qualifiers from the static type of the operand of throw and adjusting
8076 // the type from "array of T" or "function returning T" to "pointer to T"
8077 // or "pointer to function returning T", [...]
8079 if (T->isArrayType() || T->isFunctionType())
8080 T = getDecayedType(T);
8081 return T.getUnqualifiedType();
8082}
8083
8084/// getArrayDecayedType - Return the properly qualified result of decaying the
8085/// specified array type to a pointer. This operation is non-trivial when
8086/// handling typedefs etc. The canonical type of "T" must be an array type,
8087/// this returns a pointer to a properly qualified element of the array.
8088///
8089/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8091 // Get the element type with 'getAsArrayType' so that we don't lose any
8092 // typedefs in the element type of the array. This also handles propagation
8093 // of type qualifiers from the array type into the element type if present
8094 // (C99 6.7.3p8).
8095 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8096 assert(PrettyArrayType && "Not an array type!");
8097
8098 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8099
8100 // int x[restrict 4] -> int *restrict
8102 PrettyArrayType->getIndexTypeQualifiers());
8103
8104 // int x[_Nullable] -> int * _Nullable
8105 if (auto Nullability = Ty->getNullability()) {
8106 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8107 Result, Result);
8108 }
8109 return Result;
8110}
8111
8113 return getBaseElementType(array->getElementType());
8114}
8115
8117 Qualifiers qs;
8118 while (true) {
8119 SplitQualType split = type.getSplitDesugaredType();
8120 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8121 if (!array) break;
8122
8123 type = array->getElementType();
8125 }
8126
8127 return getQualifiedType(type, qs);
8128}
8129
8130/// getConstantArrayElementCount - Returns number of constant array elements.
8131uint64_t
8133 uint64_t ElementCount = 1;
8134 do {
8135 ElementCount *= CA->getZExtSize();
8136 CA = dyn_cast_or_null<ConstantArrayType>(
8138 } while (CA);
8139 return ElementCount;
8140}
8141
8143 const ArrayInitLoopExpr *AILE) const {
8144 if (!AILE)
8145 return 0;
8146
8147 uint64_t ElementCount = 1;
8148
8149 do {
8150 ElementCount *= AILE->getArraySize().getZExtValue();
8151 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8152 } while (AILE);
8153
8154 return ElementCount;
8155}
8156
8157/// getFloatingRank - Return a relative rank for floating point types.
8158/// This routine will assert if passed a built-in type that isn't a float.
8160 if (const auto *CT = T->getAs<ComplexType>())
8161 return getFloatingRank(CT->getElementType());
8162
8163 switch (T->castAs<BuiltinType>()->getKind()) {
8164 default: llvm_unreachable("getFloatingRank(): not a floating type");
8165 case BuiltinType::Float16: return Float16Rank;
8166 case BuiltinType::Half: return HalfRank;
8167 case BuiltinType::Float: return FloatRank;
8168 case BuiltinType::Double: return DoubleRank;
8169 case BuiltinType::LongDouble: return LongDoubleRank;
8170 case BuiltinType::Float128: return Float128Rank;
8171 case BuiltinType::BFloat16: return BFloat16Rank;
8172 case BuiltinType::Ibm128: return Ibm128Rank;
8173 }
8174}
8175
8176/// getFloatingTypeOrder - Compare the rank of the two specified floating
8177/// point types, ignoring the domain of the type (i.e. 'double' ==
8178/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8179/// LHS < RHS, return -1.
8181 FloatingRank LHSR = getFloatingRank(LHS);
8182 FloatingRank RHSR = getFloatingRank(RHS);
8183
8184 if (LHSR == RHSR)
8185 return 0;
8186 if (LHSR > RHSR)
8187 return 1;
8188 return -1;
8189}
8190
8193 return 0;
8194 return getFloatingTypeOrder(LHS, RHS);
8195}
8196
8197/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8198/// routine will assert if passed a built-in type that isn't an integer or enum,
8199/// or if it is not canonicalized.
8200unsigned ASTContext::getIntegerRank(const Type *T) const {
8201 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8202
8203 // Results in this 'losing' to any type of the same size, but winning if
8204 // larger.
8205 if (const auto *EIT = dyn_cast<BitIntType>(T))
8206 return 0 + (EIT->getNumBits() << 3);
8207
8208 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8209 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8210
8211 switch (cast<BuiltinType>(T)->getKind()) {
8212 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8213 case BuiltinType::Bool:
8214 return 1 + (getIntWidth(BoolTy) << 3);
8215 case BuiltinType::Char_S:
8216 case BuiltinType::Char_U:
8217 case BuiltinType::SChar:
8218 case BuiltinType::UChar:
8219 return 2 + (getIntWidth(CharTy) << 3);
8220 case BuiltinType::Short:
8221 case BuiltinType::UShort:
8222 return 3 + (getIntWidth(ShortTy) << 3);
8223 case BuiltinType::Int:
8224 case BuiltinType::UInt:
8225 return 4 + (getIntWidth(IntTy) << 3);
8226 case BuiltinType::Long:
8227 case BuiltinType::ULong:
8228 return 5 + (getIntWidth(LongTy) << 3);
8229 case BuiltinType::LongLong:
8230 case BuiltinType::ULongLong:
8231 return 6 + (getIntWidth(LongLongTy) << 3);
8232 case BuiltinType::Int128:
8233 case BuiltinType::UInt128:
8234 return 7 + (getIntWidth(Int128Ty) << 3);
8235
8236 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8237 // their underlying types" [c++20 conv.rank]
8238 case BuiltinType::Char8:
8239 return getIntegerRank(UnsignedCharTy.getTypePtr());
8240 case BuiltinType::Char16:
8241 return getIntegerRank(
8242 getFromTargetType(Target->getChar16Type()).getTypePtr());
8243 case BuiltinType::Char32:
8244 return getIntegerRank(
8245 getFromTargetType(Target->getChar32Type()).getTypePtr());
8246 case BuiltinType::WChar_S:
8247 case BuiltinType::WChar_U:
8248 return getIntegerRank(
8249 getFromTargetType(Target->getWCharType()).getTypePtr());
8250 }
8251}
8252
8253/// Whether this is a promotable bitfield reference according
8254/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8255///
8256/// \returns the type this bit-field will promote to, or NULL if no
8257/// promotion occurs.
8259 if (E->isTypeDependent() || E->isValueDependent())
8260 return {};
8261
8262 // C++ [conv.prom]p5:
8263 // If the bit-field has an enumerated type, it is treated as any other
8264 // value of that type for promotion purposes.
8266 return {};
8267
8268 // FIXME: We should not do this unless E->refersToBitField() is true. This
8269 // matters in C where getSourceBitField() will find bit-fields for various
8270 // cases where the source expression is not a bit-field designator.
8271
8272 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8273 if (!Field)
8274 return {};
8275
8276 QualType FT = Field->getType();
8277
8278 uint64_t BitWidth = Field->getBitWidthValue();
8279 uint64_t IntSize = getTypeSize(IntTy);
8280 // C++ [conv.prom]p5:
8281 // A prvalue for an integral bit-field can be converted to a prvalue of type
8282 // int if int can represent all the values of the bit-field; otherwise, it
8283 // can be converted to unsigned int if unsigned int can represent all the
8284 // values of the bit-field. If the bit-field is larger yet, no integral
8285 // promotion applies to it.
8286 // C11 6.3.1.1/2:
8287 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8288 // If an int can represent all values of the original type (as restricted by
8289 // the width, for a bit-field), the value is converted to an int; otherwise,
8290 // it is converted to an unsigned int.
8291 //
8292 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8293 // We perform that promotion here to match GCC and C++.
8294 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8295 // greater than that of 'int'. We perform that promotion to match GCC.
8296 //
8297 // C23 6.3.1.1p2:
8298 // The value from a bit-field of a bit-precise integer type is converted to
8299 // the corresponding bit-precise integer type. (The rest is the same as in
8300 // C11.)
8301 if (QualType QT = Field->getType(); QT->isBitIntType())
8302 return QT;
8303
8304 if (BitWidth < IntSize)
8305 return IntTy;
8306
8307 if (BitWidth == IntSize)
8308 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8309
8310 // Bit-fields wider than int are not subject to promotions, and therefore act
8311 // like the base type. GCC has some weird bugs in this area that we
8312 // deliberately do not follow (GCC follows a pre-standard resolution to
8313 // C's DR315 which treats bit-width as being part of the type, and this leaks
8314 // into their semantics in some cases).
8315 return {};
8316}
8317
8318/// getPromotedIntegerType - Returns the type that Promotable will
8319/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8320/// integer type.
8322 assert(!Promotable.isNull());
8323 assert(isPromotableIntegerType(Promotable));
8324 if (const auto *ED = Promotable->getAsEnumDecl())
8325 return ED->getPromotionType();
8326
8327 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8328 // qualifier.
8329 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8330 QualType PromotedUnderlying =
8331 getPromotedIntegerType(OBT->getUnderlyingType());
8332 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8333 }
8334
8335 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8336 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8337 // (3.9.1) can be converted to a prvalue of the first of the following
8338 // types that can represent all the values of its underlying type:
8339 // int, unsigned int, long int, unsigned long int, long long int, or
8340 // unsigned long long int [...]
8341 // FIXME: Is there some better way to compute this?
8342 if (BT->getKind() == BuiltinType::WChar_S ||
8343 BT->getKind() == BuiltinType::WChar_U ||
8344 BT->getKind() == BuiltinType::Char8 ||
8345 BT->getKind() == BuiltinType::Char16 ||
8346 BT->getKind() == BuiltinType::Char32) {
8347 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8348 uint64_t FromSize = getTypeSize(BT);
8349 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8351 for (const auto &PT : PromoteTypes) {
8352 uint64_t ToSize = getTypeSize(PT);
8353 if (FromSize < ToSize ||
8354 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8355 return PT;
8356 }
8357 llvm_unreachable("char type should fit into long long");
8358 }
8359 }
8360
8361 // At this point, we should have a signed or unsigned integer type.
8362 if (Promotable->isSignedIntegerType())
8363 return IntTy;
8364 uint64_t PromotableSize = getIntWidth(Promotable);
8365 uint64_t IntSize = getIntWidth(IntTy);
8366 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8367 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8368}
8369
8370/// Recurses in pointer/array types until it finds an objc retainable
8371/// type and returns its ownership.
8373 while (!T.isNull()) {
8374 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8375 return T.getObjCLifetime();
8376 if (T->isArrayType())
8377 T = getBaseElementType(T);
8378 else if (const auto *PT = T->getAs<PointerType>())
8379 T = PT->getPointeeType();
8380 else if (const auto *RT = T->getAs<ReferenceType>())
8381 T = RT->getPointeeType();
8382 else
8383 break;
8384 }
8385
8386 return Qualifiers::OCL_None;
8387}
8388
8389static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8390 // Incomplete enum types are not treated as integer types.
8391 // FIXME: In C++, enum types are never integer types.
8392 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8393 if (ED->isComplete() && !ED->isScoped())
8394 return ED->getIntegerType().getTypePtr();
8395 return nullptr;
8396}
8397
8398/// getIntegerTypeOrder - Returns the highest ranked integer type:
8399/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8400/// LHS < RHS, return -1.
8402 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8403 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8404
8405 // Unwrap enums to their underlying type.
8406 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8407 LHSC = getIntegerTypeForEnum(ET);
8408 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8409 RHSC = getIntegerTypeForEnum(ET);
8410
8411 if (LHSC == RHSC) return 0;
8412
8413 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8414 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8415
8416 unsigned LHSRank = getIntegerRank(LHSC);
8417 unsigned RHSRank = getIntegerRank(RHSC);
8418
8419 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8420 if (LHSRank == RHSRank) return 0;
8421 return LHSRank > RHSRank ? 1 : -1;
8422 }
8423
8424 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8425 if (LHSUnsigned) {
8426 // If the unsigned [LHS] type is larger, return it.
8427 if (LHSRank >= RHSRank)
8428 return 1;
8429
8430 // If the signed type can represent all values of the unsigned type, it
8431 // wins. Because we are dealing with 2's complement and types that are
8432 // powers of two larger than each other, this is always safe.
8433 return -1;
8434 }
8435
8436 // If the unsigned [RHS] type is larger, return it.
8437 if (RHSRank >= LHSRank)
8438 return -1;
8439
8440 // If the signed type can represent all values of the unsigned type, it
8441 // wins. Because we are dealing with 2's complement and types that are
8442 // powers of two larger than each other, this is always safe.
8443 return 1;
8444}
8445
8447 if (CFConstantStringTypeDecl)
8448 return CFConstantStringTypeDecl;
8449
8450 assert(!CFConstantStringTagDecl &&
8451 "tag and typedef should be initialized together");
8452 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8453 CFConstantStringTagDecl->startDefinition();
8454
8455 struct {
8456 QualType Type;
8457 const char *Name;
8458 } Fields[5];
8459 unsigned Count = 0;
8460
8461 /// Objective-C ABI
8462 ///
8463 /// typedef struct __NSConstantString_tag {
8464 /// const int *isa;
8465 /// int flags;
8466 /// const char *str;
8467 /// long length;
8468 /// } __NSConstantString;
8469 ///
8470 /// Swift ABI (4.1, 4.2)
8471 ///
8472 /// typedef struct __NSConstantString_tag {
8473 /// uintptr_t _cfisa;
8474 /// uintptr_t _swift_rc;
8475 /// _Atomic(uint64_t) _cfinfoa;
8476 /// const char *_ptr;
8477 /// uint32_t _length;
8478 /// } __NSConstantString;
8479 ///
8480 /// Swift ABI (5.0)
8481 ///
8482 /// typedef struct __NSConstantString_tag {
8483 /// uintptr_t _cfisa;
8484 /// uintptr_t _swift_rc;
8485 /// _Atomic(uint64_t) _cfinfoa;
8486 /// const char *_ptr;
8487 /// uintptr_t _length;
8488 /// } __NSConstantString;
8489
8490 const auto CFRuntime = getLangOpts().CFRuntime;
8491 if (static_cast<unsigned>(CFRuntime) <
8492 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8493 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8494 Fields[Count++] = { IntTy, "flags" };
8495 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8496 Fields[Count++] = { LongTy, "length" };
8497 } else {
8498 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8499 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8500 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8501 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8504 Fields[Count++] = { IntTy, "_ptr" };
8505 else
8506 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8507 }
8508
8509 // Create fields
8510 for (unsigned i = 0; i < Count; ++i) {
8511 FieldDecl *Field =
8512 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8513 SourceLocation(), &Idents.get(Fields[i].Name),
8514 Fields[i].Type, /*TInfo=*/nullptr,
8515 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8516 Field->setAccess(AS_public);
8517 CFConstantStringTagDecl->addDecl(Field);
8518 }
8519
8520 CFConstantStringTagDecl->completeDefinition();
8521 // This type is designed to be compatible with NSConstantString, but cannot
8522 // use the same name, since NSConstantString is an interface.
8523 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8524 CFConstantStringTypeDecl =
8525 buildImplicitTypedef(tagType, "__NSConstantString");
8526
8527 return CFConstantStringTypeDecl;
8528}
8529
8531 if (!CFConstantStringTagDecl)
8532 getCFConstantStringDecl(); // Build the tag and the typedef.
8533 return CFConstantStringTagDecl;
8534}
8535
8536// getCFConstantStringType - Return the type used for constant CFStrings.
8541
8543 if (ObjCSuperType.isNull()) {
8544 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8545 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8546 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8547 }
8548 return ObjCSuperType;
8549}
8550
8552 const auto *TT = T->castAs<TypedefType>();
8553 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8554 CFConstantStringTagDecl = TT->castAsRecordDecl();
8555}
8556
8558 if (BlockDescriptorType)
8559 return getCanonicalTagType(BlockDescriptorType);
8560
8561 RecordDecl *RD;
8562 // FIXME: Needs the FlagAppleBlock bit.
8563 RD = buildImplicitRecord("__block_descriptor");
8564 RD->startDefinition();
8565
8566 QualType FieldTypes[] = {
8569 };
8570
8571 static const char *const FieldNames[] = {
8572 "reserved",
8573 "Size"
8574 };
8575
8576 for (size_t i = 0; i < 2; ++i) {
8578 *this, RD, SourceLocation(), SourceLocation(),
8579 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8580 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8581 Field->setAccess(AS_public);
8582 RD->addDecl(Field);
8583 }
8584
8585 RD->completeDefinition();
8586
8587 BlockDescriptorType = RD;
8588
8589 return getCanonicalTagType(BlockDescriptorType);
8590}
8591
8593 if (BlockDescriptorExtendedType)
8594 return getCanonicalTagType(BlockDescriptorExtendedType);
8595
8596 RecordDecl *RD;
8597 // FIXME: Needs the FlagAppleBlock bit.
8598 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8599 RD->startDefinition();
8600
8601 QualType FieldTypes[] = {
8606 };
8607
8608 static const char *const FieldNames[] = {
8609 "reserved",
8610 "Size",
8611 "CopyFuncPtr",
8612 "DestroyFuncPtr"
8613 };
8614
8615 for (size_t i = 0; i < 4; ++i) {
8617 *this, RD, SourceLocation(), SourceLocation(),
8618 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8619 /*BitWidth=*/nullptr,
8620 /*Mutable=*/false, ICIS_NoInit);
8621 Field->setAccess(AS_public);
8622 RD->addDecl(Field);
8623 }
8624
8625 RD->completeDefinition();
8626
8627 BlockDescriptorExtendedType = RD;
8628 return getCanonicalTagType(BlockDescriptorExtendedType);
8629}
8630
8632 const auto *BT = dyn_cast<BuiltinType>(T);
8633
8634 if (!BT) {
8635 if (isa<PipeType>(T))
8636 return OCLTK_Pipe;
8637
8638 return OCLTK_Default;
8639 }
8640
8641 switch (BT->getKind()) {
8642#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8643 case BuiltinType::Id: \
8644 return OCLTK_Image;
8645#include "clang/Basic/OpenCLImageTypes.def"
8646
8647 case BuiltinType::OCLClkEvent:
8648 return OCLTK_ClkEvent;
8649
8650 case BuiltinType::OCLEvent:
8651 return OCLTK_Event;
8652
8653 case BuiltinType::OCLQueue:
8654 return OCLTK_Queue;
8655
8656 case BuiltinType::OCLReserveID:
8657 return OCLTK_ReserveID;
8658
8659 case BuiltinType::OCLSampler:
8660 return OCLTK_Sampler;
8661
8662 default:
8663 return OCLTK_Default;
8664 }
8665}
8666
8668 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8669}
8670
8671/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8672/// requires copy/dispose. Note that this must match the logic
8673/// in buildByrefHelpers.
8675 const VarDecl *D) {
8676 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8677 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8678 if (!copyExpr && record->hasTrivialDestructor()) return false;
8679
8680 return true;
8681 }
8682
8684 return true;
8685
8686 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8687 // move or destroy.
8689 return true;
8690
8691 if (!Ty->isObjCRetainableType()) return false;
8692
8693 Qualifiers qs = Ty.getQualifiers();
8694
8695 // If we have lifetime, that dominates.
8696 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8697 switch (lifetime) {
8698 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8699
8700 // These are just bits as far as the runtime is concerned.
8703 return false;
8704
8705 // These cases should have been taken care of when checking the type's
8706 // non-triviality.
8709 llvm_unreachable("impossible");
8710 }
8711 llvm_unreachable("fell out of lifetime switch!");
8712 }
8713 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8715}
8716
8718 Qualifiers::ObjCLifetime &LifeTime,
8719 bool &HasByrefExtendedLayout) const {
8720 if (!getLangOpts().ObjC ||
8721 getLangOpts().getGC() != LangOptions::NonGC)
8722 return false;
8723
8724 HasByrefExtendedLayout = false;
8725 if (Ty->isRecordType()) {
8726 HasByrefExtendedLayout = true;
8727 LifeTime = Qualifiers::OCL_None;
8728 } else if ((LifeTime = Ty.getObjCLifetime())) {
8729 // Honor the ARC qualifiers.
8730 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8731 // The MRR rule.
8733 } else {
8734 LifeTime = Qualifiers::OCL_None;
8735 }
8736 return true;
8737}
8738
8740 assert(Target && "Expected target to be initialized");
8741 const llvm::Triple &T = Target->getTriple();
8742 // Windows is LLP64 rather than LP64
8743 if (T.isOSWindows() && T.isArch64Bit())
8744 return UnsignedLongLongTy;
8745 return UnsignedLongTy;
8746}
8747
8749 assert(Target && "Expected target to be initialized");
8750 const llvm::Triple &T = Target->getTriple();
8751 // Windows is LLP64 rather than LP64
8752 if (T.isOSWindows() && T.isArch64Bit())
8753 return LongLongTy;
8754 return LongTy;
8755}
8756
8758 if (!ObjCInstanceTypeDecl)
8759 ObjCInstanceTypeDecl =
8760 buildImplicitTypedef(getObjCIdType(), "instancetype");
8761 return ObjCInstanceTypeDecl;
8762}
8763
8764// This returns true if a type has been typedefed to BOOL:
8765// typedef <type> BOOL;
8767 if (const auto *TT = dyn_cast<TypedefType>(T))
8768 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8769 return II->isStr("BOOL");
8770
8771 return false;
8772}
8773
8774/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8775/// purpose.
8777 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8778 return CharUnits::Zero();
8779
8781
8782 // Make all integer and enum types at least as large as an int
8783 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8784 sz = std::max(sz, getTypeSizeInChars(IntTy));
8785 // Treat arrays as pointers, since that's how they're passed in.
8786 else if (type->isArrayType())
8788 return sz;
8789}
8790
8797
8800 if (!VD->isInline())
8802
8803 // In almost all cases, it's a weak definition.
8804 auto *First = VD->getFirstDecl();
8805 if (First->isInlineSpecified() || !First->isStaticDataMember())
8807
8808 // If there's a file-context declaration in this translation unit, it's a
8809 // non-discardable definition.
8810 for (auto *D : VD->redecls())
8812 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8814
8815 // If we've not seen one yet, we don't know.
8817}
8818
8819static std::string charUnitsToString(const CharUnits &CU) {
8820 return llvm::itostr(CU.getQuantity());
8821}
8822
8823/// getObjCEncodingForBlock - Return the encoded type for this block
8824/// declaration.
8826 std::string S;
8827
8828 const BlockDecl *Decl = Expr->getBlockDecl();
8829 QualType BlockTy =
8831 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8832 // Encode result type.
8833 if (getLangOpts().EncodeExtendedBlockSig)
8835 true /*Extended*/);
8836 else
8837 getObjCEncodingForType(BlockReturnTy, S);
8838 // Compute size of all parameters.
8839 // Start with computing size of a pointer in number of bytes.
8840 // FIXME: There might(should) be a better way of doing this computation!
8842 CharUnits ParmOffset = PtrSize;
8843 for (auto *PI : Decl->parameters()) {
8844 QualType PType = PI->getType();
8846 if (sz.isZero())
8847 continue;
8848 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8849 ParmOffset += sz;
8850 }
8851 // Size of the argument frame
8852 S += charUnitsToString(ParmOffset);
8853 // Block pointer and offset.
8854 S += "@?0";
8855
8856 // Argument types.
8857 ParmOffset = PtrSize;
8858 for (auto *PVDecl : Decl->parameters()) {
8859 QualType PType = PVDecl->getOriginalType();
8860 if (const auto *AT =
8861 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8862 // Use array's original type only if it has known number of
8863 // elements.
8864 if (!isa<ConstantArrayType>(AT))
8865 PType = PVDecl->getType();
8866 } else if (PType->isFunctionType())
8867 PType = PVDecl->getType();
8868 if (getLangOpts().EncodeExtendedBlockSig)
8870 S, true /*Extended*/);
8871 else
8872 getObjCEncodingForType(PType, S);
8873 S += charUnitsToString(ParmOffset);
8874 ParmOffset += getObjCEncodingTypeSize(PType);
8875 }
8876
8877 return S;
8878}
8879
8880std::string
8882 std::string S;
8883 // Encode result type.
8884 getObjCEncodingForType(Decl->getReturnType(), S);
8885 CharUnits ParmOffset;
8886 // Compute size of all parameters.
8887 for (auto *PI : Decl->parameters()) {
8888 QualType PType = PI->getType();
8890 if (sz.isZero())
8891 continue;
8892
8893 assert(sz.isPositive() &&
8894 "getObjCEncodingForFunctionDecl - Incomplete param type");
8895 ParmOffset += sz;
8896 }
8897 S += charUnitsToString(ParmOffset);
8898 ParmOffset = CharUnits::Zero();
8899
8900 // Argument types.
8901 for (auto *PVDecl : Decl->parameters()) {
8902 QualType PType = PVDecl->getOriginalType();
8903 if (const auto *AT =
8904 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8905 // Use array's original type only if it has known number of
8906 // elements.
8907 if (!isa<ConstantArrayType>(AT))
8908 PType = PVDecl->getType();
8909 } else if (PType->isFunctionType())
8910 PType = PVDecl->getType();
8911 getObjCEncodingForType(PType, S);
8912 S += charUnitsToString(ParmOffset);
8913 ParmOffset += getObjCEncodingTypeSize(PType);
8914 }
8915
8916 return S;
8917}
8918
8919/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8920/// method parameter or return type. If Extended, include class names and
8921/// block object types.
8923 QualType T, std::string& S,
8924 bool Extended) const {
8925 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8927 // Encode parameter type.
8928 ObjCEncOptions Options = ObjCEncOptions()
8929 .setExpandPointedToStructures()
8930 .setExpandStructures()
8931 .setIsOutermostType();
8932 if (Extended)
8933 Options.setEncodeBlockParameters().setEncodeClassNames();
8934 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8935}
8936
8937/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8938/// declaration.
8940 bool Extended) const {
8941 // FIXME: This is not very efficient.
8942 // Encode return type.
8943 std::string S;
8944 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8945 Decl->getReturnType(), S, Extended);
8946 // Compute size of all parameters.
8947 // Start with computing size of a pointer in number of bytes.
8948 // FIXME: There might(should) be a better way of doing this computation!
8950 // The first two arguments (self and _cmd) are pointers; account for
8951 // their size.
8952 CharUnits ParmOffset = 2 * PtrSize;
8953 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8954 E = Decl->sel_param_end(); PI != E; ++PI) {
8955 QualType PType = (*PI)->getType();
8957 if (sz.isZero())
8958 continue;
8959
8960 assert(sz.isPositive() &&
8961 "getObjCEncodingForMethodDecl - Incomplete param type");
8962 ParmOffset += sz;
8963 }
8964 S += charUnitsToString(ParmOffset);
8965 S += "@0:";
8966 S += charUnitsToString(PtrSize);
8967
8968 // Argument types.
8969 ParmOffset = 2 * PtrSize;
8970 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8971 E = Decl->sel_param_end(); PI != E; ++PI) {
8972 const ParmVarDecl *PVDecl = *PI;
8973 QualType PType = PVDecl->getOriginalType();
8974 if (const auto *AT =
8975 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8976 // Use array's original type only if it has known number of
8977 // elements.
8978 if (!isa<ConstantArrayType>(AT))
8979 PType = PVDecl->getType();
8980 } else if (PType->isFunctionType())
8981 PType = PVDecl->getType();
8983 PType, S, Extended);
8984 S += charUnitsToString(ParmOffset);
8985 ParmOffset += getObjCEncodingTypeSize(PType);
8986 }
8987
8988 return S;
8989}
8990
8993 const ObjCPropertyDecl *PD,
8994 const Decl *Container) const {
8995 if (!Container)
8996 return nullptr;
8997 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8998 for (auto *PID : CID->property_impls())
8999 if (PID->getPropertyDecl() == PD)
9000 return PID;
9001 } else {
9002 const auto *OID = cast<ObjCImplementationDecl>(Container);
9003 for (auto *PID : OID->property_impls())
9004 if (PID->getPropertyDecl() == PD)
9005 return PID;
9006 }
9007 return nullptr;
9008}
9009
9010/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9011/// property declaration. If non-NULL, Container must be either an
9012/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9013/// NULL when getting encodings for protocol properties.
9014/// Property attributes are stored as a comma-delimited C string. The simple
9015/// attributes readonly and bycopy are encoded as single characters. The
9016/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9017/// encoded as single characters, followed by an identifier. Property types
9018/// are also encoded as a parametrized attribute. The characters used to encode
9019/// these attributes are defined by the following enumeration:
9020/// @code
9021/// enum PropertyAttributes {
9022/// kPropertyReadOnly = 'R', // property is read-only.
9023/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9024/// kPropertyByref = '&', // property is a reference to the value last assigned
9025/// kPropertyDynamic = 'D', // property is dynamic
9026/// kPropertyGetter = 'G', // followed by getter selector name
9027/// kPropertySetter = 'S', // followed by setter selector name
9028/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9029/// kPropertyType = 'T' // followed by old-style type encoding.
9030/// kPropertyWeak = 'W' // 'weak' property
9031/// kPropertyStrong = 'P' // property GC'able
9032/// kPropertyNonAtomic = 'N' // property non-atomic
9033/// kPropertyOptional = '?' // property optional
9034/// };
9035/// @endcode
9036std::string
9038 const Decl *Container) const {
9039 // Collect information from the property implementation decl(s).
9040 bool Dynamic = false;
9041 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9042
9043 if (ObjCPropertyImplDecl *PropertyImpDecl =
9045 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9046 Dynamic = true;
9047 else
9048 SynthesizePID = PropertyImpDecl;
9049 }
9050
9051 // FIXME: This is not very efficient.
9052 std::string S = "T";
9053
9054 // Encode result type.
9055 // GCC has some special rules regarding encoding of properties which
9056 // closely resembles encoding of ivars.
9058
9059 if (PD->isOptional())
9060 S += ",?";
9061
9062 if (PD->isReadOnly()) {
9063 S += ",R";
9065 S += ",C";
9067 S += ",&";
9069 S += ",W";
9070 } else {
9071 switch (PD->getSetterKind()) {
9072 case ObjCPropertyDecl::Assign: break;
9073 case ObjCPropertyDecl::Copy: S += ",C"; break;
9074 case ObjCPropertyDecl::Retain: S += ",&"; break;
9075 case ObjCPropertyDecl::Weak: S += ",W"; break;
9076 }
9077 }
9078
9079 // It really isn't clear at all what this means, since properties
9080 // are "dynamic by default".
9081 if (Dynamic)
9082 S += ",D";
9083
9085 S += ",N";
9086
9088 S += ",G";
9089 S += PD->getGetterName().getAsString();
9090 }
9091
9093 S += ",S";
9094 S += PD->getSetterName().getAsString();
9095 }
9096
9097 if (SynthesizePID) {
9098 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9099 S += ",V";
9100 S += OID->getNameAsString();
9101 }
9102
9103 // FIXME: OBJCGC: weak & strong
9104 return S;
9105}
9106
9107/// getLegacyIntegralTypeEncoding -
9108/// Another legacy compatibility encoding: 32-bit longs are encoded as
9109/// 'l' or 'L' , but not always. For typedefs, we need to use
9110/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9112 if (PointeeTy->getAs<TypedefType>()) {
9113 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9114 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9115 PointeeTy = UnsignedIntTy;
9116 else
9117 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9118 PointeeTy = IntTy;
9119 }
9120 }
9121}
9122
9124 const FieldDecl *Field,
9125 QualType *NotEncodedT) const {
9126 // We follow the behavior of gcc, expanding structures which are
9127 // directly pointed to, and expanding embedded structures. Note that
9128 // these rules are sufficient to prevent recursive encoding of the
9129 // same type.
9130 getObjCEncodingForTypeImpl(T, S,
9131 ObjCEncOptions()
9132 .setExpandPointedToStructures()
9133 .setExpandStructures()
9134 .setIsOutermostType(),
9135 Field, NotEncodedT);
9136}
9137
9139 std::string& S) const {
9140 // Encode result type.
9141 // GCC has some special rules regarding encoding of properties which
9142 // closely resembles encoding of ivars.
9143 getObjCEncodingForTypeImpl(T, S,
9144 ObjCEncOptions()
9145 .setExpandPointedToStructures()
9146 .setExpandStructures()
9147 .setIsOutermostType()
9148 .setEncodingProperty(),
9149 /*Field=*/nullptr);
9150}
9151
9153 const BuiltinType *BT) {
9155 switch (kind) {
9156 case BuiltinType::Void: return 'v';
9157 case BuiltinType::Bool: return 'B';
9158 case BuiltinType::Char8:
9159 case BuiltinType::Char_U:
9160 case BuiltinType::UChar: return 'C';
9161 case BuiltinType::Char16:
9162 case BuiltinType::UShort: return 'S';
9163 case BuiltinType::Char32:
9164 case BuiltinType::UInt: return 'I';
9165 case BuiltinType::ULong:
9166 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9167 case BuiltinType::UInt128: return 'T';
9168 case BuiltinType::ULongLong: return 'Q';
9169 case BuiltinType::Char_S:
9170 case BuiltinType::SChar: return 'c';
9171 case BuiltinType::Short: return 's';
9172 case BuiltinType::WChar_S:
9173 case BuiltinType::WChar_U:
9174 case BuiltinType::Int: return 'i';
9175 case BuiltinType::Long:
9176 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9177 case BuiltinType::LongLong: return 'q';
9178 case BuiltinType::Int128: return 't';
9179 case BuiltinType::Float: return 'f';
9180 case BuiltinType::Double: return 'd';
9181 case BuiltinType::LongDouble: return 'D';
9182 case BuiltinType::NullPtr: return '*'; // like char*
9183
9184 case BuiltinType::BFloat16:
9185 case BuiltinType::Float16:
9186 case BuiltinType::Float128:
9187 case BuiltinType::Ibm128:
9188 case BuiltinType::Half:
9189 case BuiltinType::ShortAccum:
9190 case BuiltinType::Accum:
9191 case BuiltinType::LongAccum:
9192 case BuiltinType::UShortAccum:
9193 case BuiltinType::UAccum:
9194 case BuiltinType::ULongAccum:
9195 case BuiltinType::ShortFract:
9196 case BuiltinType::Fract:
9197 case BuiltinType::LongFract:
9198 case BuiltinType::UShortFract:
9199 case BuiltinType::UFract:
9200 case BuiltinType::ULongFract:
9201 case BuiltinType::SatShortAccum:
9202 case BuiltinType::SatAccum:
9203 case BuiltinType::SatLongAccum:
9204 case BuiltinType::SatUShortAccum:
9205 case BuiltinType::SatUAccum:
9206 case BuiltinType::SatULongAccum:
9207 case BuiltinType::SatShortFract:
9208 case BuiltinType::SatFract:
9209 case BuiltinType::SatLongFract:
9210 case BuiltinType::SatUShortFract:
9211 case BuiltinType::SatUFract:
9212 case BuiltinType::SatULongFract:
9213 // FIXME: potentially need @encodes for these!
9214 return ' ';
9215
9216#define SVE_TYPE(Name, Id, SingletonId) \
9217 case BuiltinType::Id:
9218#include "clang/Basic/AArch64ACLETypes.def"
9219#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9220#include "clang/Basic/RISCVVTypes.def"
9221#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9222#include "clang/Basic/WebAssemblyReferenceTypes.def"
9223#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9224#include "clang/Basic/AMDGPUTypes.def"
9225 {
9226 DiagnosticsEngine &Diags = C->getDiagnostics();
9227 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9228 << QualType(BT, 0);
9229 return ' ';
9230 }
9231
9232 case BuiltinType::ObjCId:
9233 case BuiltinType::ObjCClass:
9234 case BuiltinType::ObjCSel:
9235 llvm_unreachable("@encoding ObjC primitive type");
9236
9237 // OpenCL and placeholder types don't need @encodings.
9238#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9239 case BuiltinType::Id:
9240#include "clang/Basic/OpenCLImageTypes.def"
9241#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9242 case BuiltinType::Id:
9243#include "clang/Basic/OpenCLExtensionTypes.def"
9244 case BuiltinType::OCLEvent:
9245 case BuiltinType::OCLClkEvent:
9246 case BuiltinType::OCLQueue:
9247 case BuiltinType::OCLReserveID:
9248 case BuiltinType::OCLSampler:
9249 case BuiltinType::Dependent:
9250#define PPC_VECTOR_TYPE(Name, Id, Size) \
9251 case BuiltinType::Id:
9252#include "clang/Basic/PPCTypes.def"
9253#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9254#include "clang/Basic/HLSLIntangibleTypes.def"
9255#define BUILTIN_TYPE(KIND, ID)
9256#define PLACEHOLDER_TYPE(KIND, ID) \
9257 case BuiltinType::KIND:
9258#include "clang/AST/BuiltinTypes.def"
9259 llvm_unreachable("invalid builtin type for @encode");
9260 }
9261 llvm_unreachable("invalid BuiltinType::Kind value");
9262}
9263
9264static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9266
9267 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9268 if (!Enum->isFixed())
9269 return 'i';
9270
9271 // The encoding of a fixed enum type matches its fixed underlying type.
9272 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9274}
9275
9276static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9277 QualType T, const FieldDecl *FD) {
9278 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9279 S += 'b';
9280 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9281 // The GNU runtime requires more information; bitfields are encoded as b,
9282 // then the offset (in bits) of the first element, then the type of the
9283 // bitfield, then the size in bits. For example, in this structure:
9284 //
9285 // struct
9286 // {
9287 // int integer;
9288 // int flags:2;
9289 // };
9290 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9291 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9292 // information is not especially sensible, but we're stuck with it for
9293 // compatibility with GCC, although providing it breaks anything that
9294 // actually uses runtime introspection and wants to work on both runtimes...
9295 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9296 uint64_t Offset;
9297
9298 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9299 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9300 } else {
9301 const RecordDecl *RD = FD->getParent();
9302 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9303 Offset = RL.getFieldOffset(FD->getFieldIndex());
9304 }
9305
9306 S += llvm::utostr(Offset);
9307
9308 if (const auto *ET = T->getAsCanonical<EnumType>())
9309 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9310 else {
9311 const auto *BT = T->castAs<BuiltinType>();
9312 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9313 }
9314 }
9315 S += llvm::utostr(FD->getBitWidthValue());
9316}
9317
9318// Helper function for determining whether the encoded type string would include
9319// a template specialization type.
9321 bool VisitBasesAndFields) {
9322 T = T->getBaseElementTypeUnsafe();
9323
9324 if (auto *PT = T->getAs<PointerType>())
9326 PT->getPointeeType().getTypePtr(), false);
9327
9328 auto *CXXRD = T->getAsCXXRecordDecl();
9329
9330 if (!CXXRD)
9331 return false;
9332
9334 return true;
9335
9336 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9337 return false;
9338
9339 for (const auto &B : CXXRD->bases())
9340 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9341 true))
9342 return true;
9343
9344 for (auto *FD : CXXRD->fields())
9345 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9346 true))
9347 return true;
9348
9349 return false;
9350}
9351
9352// FIXME: Use SmallString for accumulating string.
9353void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9354 const ObjCEncOptions Options,
9355 const FieldDecl *FD,
9356 QualType *NotEncodedT) const {
9358 switch (CT->getTypeClass()) {
9359 case Type::Builtin:
9360 case Type::Enum:
9361 if (FD && FD->isBitField())
9362 return EncodeBitField(this, S, T, FD);
9363 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9364 S += getObjCEncodingForPrimitiveType(this, BT);
9365 else
9366 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9367 return;
9368
9369 case Type::Complex:
9370 S += 'j';
9371 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9372 ObjCEncOptions(),
9373 /*Field=*/nullptr);
9374 return;
9375
9376 case Type::Atomic:
9377 S += 'A';
9378 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9379 ObjCEncOptions(),
9380 /*Field=*/nullptr);
9381 return;
9382
9383 // encoding for pointer or reference types.
9384 case Type::Pointer:
9385 case Type::LValueReference:
9386 case Type::RValueReference: {
9387 QualType PointeeTy;
9388 if (isa<PointerType>(CT)) {
9389 const auto *PT = T->castAs<PointerType>();
9390 if (PT->isObjCSelType()) {
9391 S += ':';
9392 return;
9393 }
9394 PointeeTy = PT->getPointeeType();
9395 } else {
9396 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9397 }
9398
9399 bool isReadOnly = false;
9400 // For historical/compatibility reasons, the read-only qualifier of the
9401 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9402 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9403 // Also, do not emit the 'r' for anything but the outermost type!
9404 if (T->getAs<TypedefType>()) {
9405 if (Options.IsOutermostType() && T.isConstQualified()) {
9406 isReadOnly = true;
9407 S += 'r';
9408 }
9409 } else if (Options.IsOutermostType()) {
9410 QualType P = PointeeTy;
9411 while (auto PT = P->getAs<PointerType>())
9412 P = PT->getPointeeType();
9413 if (P.isConstQualified()) {
9414 isReadOnly = true;
9415 S += 'r';
9416 }
9417 }
9418 if (isReadOnly) {
9419 // Another legacy compatibility encoding. Some ObjC qualifier and type
9420 // combinations need to be rearranged.
9421 // Rewrite "in const" from "nr" to "rn"
9422 if (StringRef(S).ends_with("nr"))
9423 S.replace(S.end()-2, S.end(), "rn");
9424 }
9425
9426 if (PointeeTy->isCharType()) {
9427 // char pointer types should be encoded as '*' unless it is a
9428 // type that has been typedef'd to 'BOOL'.
9429 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9430 S += '*';
9431 return;
9432 }
9433 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9434 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9435 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9436 if (II == &Idents.get("objc_class")) {
9437 S += '#';
9438 return;
9439 }
9440 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9441 if (II == &Idents.get("objc_object")) {
9442 S += '@';
9443 return;
9444 }
9445 // If the encoded string for the class includes template names, just emit
9446 // "^v" for pointers to the class.
9447 if (getLangOpts().CPlusPlus &&
9448 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9450 RTy, Options.ExpandPointedToStructures()))) {
9451 S += "^v";
9452 return;
9453 }
9454 // fall through...
9455 }
9456 S += '^';
9458
9459 ObjCEncOptions NewOptions;
9460 if (Options.ExpandPointedToStructures())
9461 NewOptions.setExpandStructures();
9462 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9463 /*Field=*/nullptr, NotEncodedT);
9464 return;
9465 }
9466
9467 case Type::ConstantArray:
9468 case Type::IncompleteArray:
9469 case Type::VariableArray: {
9470 const auto *AT = cast<ArrayType>(CT);
9471
9472 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9473 // Incomplete arrays are encoded as a pointer to the array element.
9474 S += '^';
9475
9476 getObjCEncodingForTypeImpl(
9477 AT->getElementType(), S,
9478 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9479 } else {
9480 S += '[';
9481
9482 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9483 S += llvm::utostr(CAT->getZExtSize());
9484 else {
9485 //Variable length arrays are encoded as a regular array with 0 elements.
9487 "Unknown array type!");
9488 S += '0';
9489 }
9490
9491 getObjCEncodingForTypeImpl(
9492 AT->getElementType(), S,
9493 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9494 NotEncodedT);
9495 S += ']';
9496 }
9497 return;
9498 }
9499
9500 case Type::FunctionNoProto:
9501 case Type::FunctionProto:
9502 S += '?';
9503 return;
9504
9505 case Type::Record: {
9506 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9507 S += RDecl->isUnion() ? '(' : '{';
9508 // Anonymous structures print as '?'
9509 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9510 S += II->getName();
9511 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9512 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9513 llvm::raw_string_ostream OS(S);
9514 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9516 }
9517 } else {
9518 S += '?';
9519 }
9520 if (Options.ExpandStructures()) {
9521 S += '=';
9522 if (!RDecl->isUnion()) {
9523 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9524 } else {
9525 for (const auto *Field : RDecl->fields()) {
9526 if (FD) {
9527 S += '"';
9528 S += Field->getNameAsString();
9529 S += '"';
9530 }
9531
9532 // Special case bit-fields.
9533 if (Field->isBitField()) {
9534 getObjCEncodingForTypeImpl(Field->getType(), S,
9535 ObjCEncOptions().setExpandStructures(),
9536 Field);
9537 } else {
9538 QualType qt = Field->getType();
9540 getObjCEncodingForTypeImpl(
9541 qt, S,
9542 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9543 NotEncodedT);
9544 }
9545 }
9546 }
9547 }
9548 S += RDecl->isUnion() ? ')' : '}';
9549 return;
9550 }
9551
9552 case Type::BlockPointer: {
9553 const auto *BT = T->castAs<BlockPointerType>();
9554 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9555 if (Options.EncodeBlockParameters()) {
9556 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9557
9558 S += '<';
9559 // Block return type
9560 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9561 Options.forComponentType(), FD, NotEncodedT);
9562 // Block self
9563 S += "@?";
9564 // Block parameters
9565 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9566 for (const auto &I : FPT->param_types())
9567 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9568 NotEncodedT);
9569 }
9570 S += '>';
9571 }
9572 return;
9573 }
9574
9575 case Type::ObjCObject: {
9576 // hack to match legacy encoding of *id and *Class
9577 QualType Ty = getObjCObjectPointerType(CT);
9578 if (Ty->isObjCIdType()) {
9579 S += "{objc_object=}";
9580 return;
9581 }
9582 else if (Ty->isObjCClassType()) {
9583 S += "{objc_class=}";
9584 return;
9585 }
9586 // TODO: Double check to make sure this intentionally falls through.
9587 [[fallthrough]];
9588 }
9589
9590 case Type::ObjCInterface: {
9591 // Ignore protocol qualifiers when mangling at this level.
9592 // @encode(class_name)
9593 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9594 S += '{';
9595 S += OI->getObjCRuntimeNameAsString();
9596 if (Options.ExpandStructures()) {
9597 S += '=';
9598 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9599 DeepCollectObjCIvars(OI, true, Ivars);
9600 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9601 const FieldDecl *Field = Ivars[i];
9602 if (Field->isBitField())
9603 getObjCEncodingForTypeImpl(Field->getType(), S,
9604 ObjCEncOptions().setExpandStructures(),
9605 Field);
9606 else
9607 getObjCEncodingForTypeImpl(Field->getType(), S,
9608 ObjCEncOptions().setExpandStructures(), FD,
9609 NotEncodedT);
9610 }
9611 }
9612 S += '}';
9613 return;
9614 }
9615
9616 case Type::ObjCObjectPointer: {
9617 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9618 if (OPT->isObjCIdType()) {
9619 S += '@';
9620 return;
9621 }
9622
9623 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9624 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9625 // Since this is a binary compatibility issue, need to consult with
9626 // runtime folks. Fortunately, this is a *very* obscure construct.
9627 S += '#';
9628 return;
9629 }
9630
9631 if (OPT->isObjCQualifiedIdType()) {
9632 getObjCEncodingForTypeImpl(
9633 getObjCIdType(), S,
9634 Options.keepingOnly(ObjCEncOptions()
9635 .setExpandPointedToStructures()
9636 .setExpandStructures()),
9637 FD);
9638 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9639 // Note that we do extended encoding of protocol qualifier list
9640 // Only when doing ivar or property encoding.
9641 S += '"';
9642 for (const auto *I : OPT->quals()) {
9643 S += '<';
9644 S += I->getObjCRuntimeNameAsString();
9645 S += '>';
9646 }
9647 S += '"';
9648 }
9649 return;
9650 }
9651
9652 S += '@';
9653 if (OPT->getInterfaceDecl() &&
9654 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9655 S += '"';
9656 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9657 for (const auto *I : OPT->quals()) {
9658 S += '<';
9659 S += I->getObjCRuntimeNameAsString();
9660 S += '>';
9661 }
9662 S += '"';
9663 }
9664 return;
9665 }
9666
9667 // gcc just blithely ignores member pointers.
9668 // FIXME: we should do better than that. 'M' is available.
9669 case Type::MemberPointer:
9670 // This matches gcc's encoding, even though technically it is insufficient.
9671 //FIXME. We should do a better job than gcc.
9672 case Type::Vector:
9673 case Type::ExtVector:
9674 // Until we have a coherent encoding of these three types, issue warning.
9675 if (NotEncodedT)
9676 *NotEncodedT = T;
9677 return;
9678
9679 case Type::ConstantMatrix:
9680 if (NotEncodedT)
9681 *NotEncodedT = T;
9682 return;
9683
9684 case Type::BitInt:
9685 if (NotEncodedT)
9686 *NotEncodedT = T;
9687 return;
9688
9689 // We could see an undeduced auto type here during error recovery.
9690 // Just ignore it.
9691 case Type::Auto:
9692 case Type::DeducedTemplateSpecialization:
9693 return;
9694
9695 case Type::HLSLAttributedResource:
9696 case Type::HLSLInlineSpirv:
9697 case Type::OverflowBehavior:
9698 llvm_unreachable("unexpected type");
9699
9700 case Type::ArrayParameter:
9701 case Type::Pipe:
9702#define ABSTRACT_TYPE(KIND, BASE)
9703#define TYPE(KIND, BASE)
9704#define DEPENDENT_TYPE(KIND, BASE) \
9705 case Type::KIND:
9706#define NON_CANONICAL_TYPE(KIND, BASE) \
9707 case Type::KIND:
9708#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9709 case Type::KIND:
9710#include "clang/AST/TypeNodes.inc"
9711 llvm_unreachable("@encode for dependent type!");
9712 }
9713 llvm_unreachable("bad type kind!");
9714}
9715
9716void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9717 std::string &S,
9718 const FieldDecl *FD,
9719 bool includeVBases,
9720 QualType *NotEncodedT) const {
9721 assert(RDecl && "Expected non-null RecordDecl");
9722 assert(!RDecl->isUnion() && "Should not be called for unions");
9723 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9724 return;
9725
9726 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9727 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9728 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9729
9730 if (CXXRec) {
9731 for (const auto &BI : CXXRec->bases()) {
9732 if (!BI.isVirtual()) {
9733 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9734 if (base->isEmpty())
9735 continue;
9736 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9737 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9738 std::make_pair(offs, base));
9739 }
9740 }
9741 }
9742
9743 for (FieldDecl *Field : RDecl->fields()) {
9744 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9745 continue;
9746 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9747 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9748 std::make_pair(offs, Field));
9749 }
9750
9751 if (CXXRec && includeVBases) {
9752 for (const auto &BI : CXXRec->vbases()) {
9753 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9754 if (base->isEmpty())
9755 continue;
9756 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9757 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9758 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9759 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9760 std::make_pair(offs, base));
9761 }
9762 }
9763
9764 CharUnits size;
9765 if (CXXRec) {
9766 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9767 } else {
9768 size = layout.getSize();
9769 }
9770
9771#ifndef NDEBUG
9772 uint64_t CurOffs = 0;
9773#endif
9774 std::multimap<uint64_t, NamedDecl *>::iterator
9775 CurLayObj = FieldOrBaseOffsets.begin();
9776
9777 if (CXXRec && CXXRec->isDynamicClass() &&
9778 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9779 if (FD) {
9780 S += "\"_vptr$";
9781 std::string recname = CXXRec->getNameAsString();
9782 if (recname.empty()) recname = "?";
9783 S += recname;
9784 S += '"';
9785 }
9786 S += "^^?";
9787#ifndef NDEBUG
9788 CurOffs += getTypeSize(VoidPtrTy);
9789#endif
9790 }
9791
9792 if (!RDecl->hasFlexibleArrayMember()) {
9793 // Mark the end of the structure.
9794 uint64_t offs = toBits(size);
9795 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9796 std::make_pair(offs, nullptr));
9797 }
9798
9799 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9800#ifndef NDEBUG
9801 assert(CurOffs <= CurLayObj->first);
9802 if (CurOffs < CurLayObj->first) {
9803 uint64_t padding = CurLayObj->first - CurOffs;
9804 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9805 // packing/alignment of members is different that normal, in which case
9806 // the encoding will be out-of-sync with the real layout.
9807 // If the runtime switches to just consider the size of types without
9808 // taking into account alignment, we could make padding explicit in the
9809 // encoding (e.g. using arrays of chars). The encoding strings would be
9810 // longer then though.
9811 CurOffs += padding;
9812 }
9813#endif
9814
9815 NamedDecl *dcl = CurLayObj->second;
9816 if (!dcl)
9817 break; // reached end of structure.
9818
9819 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9820 // We expand the bases without their virtual bases since those are going
9821 // in the initial structure. Note that this differs from gcc which
9822 // expands virtual bases each time one is encountered in the hierarchy,
9823 // making the encoding type bigger than it really is.
9824 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9825 NotEncodedT);
9826 assert(!base->isEmpty());
9827#ifndef NDEBUG
9828 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9829#endif
9830 } else {
9831 const auto *field = cast<FieldDecl>(dcl);
9832 if (FD) {
9833 S += '"';
9834 S += field->getNameAsString();
9835 S += '"';
9836 }
9837
9838 if (field->isBitField()) {
9839 EncodeBitField(this, S, field->getType(), field);
9840#ifndef NDEBUG
9841 CurOffs += field->getBitWidthValue();
9842#endif
9843 } else {
9844 QualType qt = field->getType();
9846 getObjCEncodingForTypeImpl(
9847 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9848 FD, NotEncodedT);
9849#ifndef NDEBUG
9850 CurOffs += getTypeSize(field->getType());
9851#endif
9852 }
9853 }
9854 }
9855}
9856
9858 std::string& S) const {
9859 if (QT & Decl::OBJC_TQ_In)
9860 S += 'n';
9861 if (QT & Decl::OBJC_TQ_Inout)
9862 S += 'N';
9863 if (QT & Decl::OBJC_TQ_Out)
9864 S += 'o';
9865 if (QT & Decl::OBJC_TQ_Bycopy)
9866 S += 'O';
9867 if (QT & Decl::OBJC_TQ_Byref)
9868 S += 'R';
9869 if (QT & Decl::OBJC_TQ_Oneway)
9870 S += 'V';
9871}
9872
9874 if (!ObjCIdDecl) {
9877 ObjCIdDecl = buildImplicitTypedef(T, "id");
9878 }
9879 return ObjCIdDecl;
9880}
9881
9883 if (!ObjCSelDecl) {
9885 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9886 }
9887 return ObjCSelDecl;
9888}
9889
9891 if (!ObjCClassDecl) {
9894 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9895 }
9896 return ObjCClassDecl;
9897}
9898
9900 if (!ObjCProtocolClassDecl) {
9901 ObjCProtocolClassDecl
9904 &Idents.get("Protocol"),
9905 /*typeParamList=*/nullptr,
9906 /*PrevDecl=*/nullptr,
9907 SourceLocation(), true);
9908 }
9909
9910 return ObjCProtocolClassDecl;
9911}
9912
9914 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9915 return PointerAuthQualifier();
9917 getLangOpts().PointerAuthObjcInterfaceSelKey,
9918 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9920 /*isIsaPointer=*/false,
9921 /*authenticatesNullValues=*/false);
9922}
9923
9924//===----------------------------------------------------------------------===//
9925// __builtin_va_list Construction Functions
9926//===----------------------------------------------------------------------===//
9927
9929 StringRef Name) {
9930 // typedef char* __builtin[_ms]_va_list;
9931 QualType T = Context->getPointerType(Context->CharTy);
9932 return Context->buildImplicitTypedef(T, Name);
9933}
9934
9936 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9937}
9938
9940 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9941}
9942
9944 // typedef void* __builtin_va_list;
9945 QualType T = Context->getPointerType(Context->VoidTy);
9946 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9947}
9948
9949static TypedefDecl *
9951 // struct __va_list
9952 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9953 if (Context->getLangOpts().CPlusPlus) {
9954 // namespace std { struct __va_list {
9955 auto *NS = NamespaceDecl::Create(
9956 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9957 /*Inline=*/false, SourceLocation(), SourceLocation(),
9958 &Context->Idents.get("std"),
9959 /*PrevDecl=*/nullptr, /*Nested=*/false);
9960 NS->setImplicit();
9962 }
9963
9964 VaListTagDecl->startDefinition();
9965
9966 const size_t NumFields = 5;
9967 QualType FieldTypes[NumFields];
9968 const char *FieldNames[NumFields];
9969
9970 // void *__stack;
9971 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9972 FieldNames[0] = "__stack";
9973
9974 // void *__gr_top;
9975 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9976 FieldNames[1] = "__gr_top";
9977
9978 // void *__vr_top;
9979 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9980 FieldNames[2] = "__vr_top";
9981
9982 // int __gr_offs;
9983 FieldTypes[3] = Context->IntTy;
9984 FieldNames[3] = "__gr_offs";
9985
9986 // int __vr_offs;
9987 FieldTypes[4] = Context->IntTy;
9988 FieldNames[4] = "__vr_offs";
9989
9990 // Create fields
9991 for (unsigned i = 0; i < NumFields; ++i) {
9992 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9996 &Context->Idents.get(FieldNames[i]),
9997 FieldTypes[i], /*TInfo=*/nullptr,
9998 /*BitWidth=*/nullptr,
9999 /*Mutable=*/false,
10000 ICIS_NoInit);
10001 Field->setAccess(AS_public);
10002 VaListTagDecl->addDecl(Field);
10003 }
10004 VaListTagDecl->completeDefinition();
10005 Context->VaListTagDecl = VaListTagDecl;
10006 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10007
10008 // } __builtin_va_list;
10009 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10010}
10011
10013 // typedef struct __va_list_tag {
10015
10016 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10017 VaListTagDecl->startDefinition();
10018
10019 const size_t NumFields = 5;
10020 QualType FieldTypes[NumFields];
10021 const char *FieldNames[NumFields];
10022
10023 // unsigned char gpr;
10024 FieldTypes[0] = Context->UnsignedCharTy;
10025 FieldNames[0] = "gpr";
10026
10027 // unsigned char fpr;
10028 FieldTypes[1] = Context->UnsignedCharTy;
10029 FieldNames[1] = "fpr";
10030
10031 // unsigned short reserved;
10032 FieldTypes[2] = Context->UnsignedShortTy;
10033 FieldNames[2] = "reserved";
10034
10035 // void* overflow_arg_area;
10036 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10037 FieldNames[3] = "overflow_arg_area";
10038
10039 // void* reg_save_area;
10040 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10041 FieldNames[4] = "reg_save_area";
10042
10043 // Create fields
10044 for (unsigned i = 0; i < NumFields; ++i) {
10045 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10048 &Context->Idents.get(FieldNames[i]),
10049 FieldTypes[i], /*TInfo=*/nullptr,
10050 /*BitWidth=*/nullptr,
10051 /*Mutable=*/false,
10052 ICIS_NoInit);
10053 Field->setAccess(AS_public);
10054 VaListTagDecl->addDecl(Field);
10055 }
10056 VaListTagDecl->completeDefinition();
10057 Context->VaListTagDecl = VaListTagDecl;
10058 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10059
10060 // } __va_list_tag;
10061 TypedefDecl *VaListTagTypedefDecl =
10062 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10063
10064 QualType VaListTagTypedefType =
10065 Context->getTypedefType(ElaboratedTypeKeyword::None,
10066 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10067
10068 // typedef __va_list_tag __builtin_va_list[1];
10069 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10070 QualType VaListTagArrayType = Context->getConstantArrayType(
10071 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10072 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10073}
10074
10075static TypedefDecl *
10077 // struct __va_list_tag {
10079 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10080 VaListTagDecl->startDefinition();
10081
10082 const size_t NumFields = 4;
10083 QualType FieldTypes[NumFields];
10084 const char *FieldNames[NumFields];
10085
10086 // unsigned gp_offset;
10087 FieldTypes[0] = Context->UnsignedIntTy;
10088 FieldNames[0] = "gp_offset";
10089
10090 // unsigned fp_offset;
10091 FieldTypes[1] = Context->UnsignedIntTy;
10092 FieldNames[1] = "fp_offset";
10093
10094 // void* overflow_arg_area;
10095 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10096 FieldNames[2] = "overflow_arg_area";
10097
10098 // void* reg_save_area;
10099 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10100 FieldNames[3] = "reg_save_area";
10101
10102 // Create fields
10103 for (unsigned i = 0; i < NumFields; ++i) {
10104 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10108 &Context->Idents.get(FieldNames[i]),
10109 FieldTypes[i], /*TInfo=*/nullptr,
10110 /*BitWidth=*/nullptr,
10111 /*Mutable=*/false,
10112 ICIS_NoInit);
10113 Field->setAccess(AS_public);
10114 VaListTagDecl->addDecl(Field);
10115 }
10116 VaListTagDecl->completeDefinition();
10117 Context->VaListTagDecl = VaListTagDecl;
10118 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10119
10120 // };
10121
10122 // typedef struct __va_list_tag __builtin_va_list[1];
10123 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10124 QualType VaListTagArrayType = Context->getConstantArrayType(
10125 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10126 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10127}
10128
10129static TypedefDecl *
10131 // struct __va_list
10132 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10133 if (Context->getLangOpts().CPlusPlus) {
10134 // namespace std { struct __va_list {
10135 NamespaceDecl *NS;
10136 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10137 Context->getTranslationUnitDecl(),
10138 /*Inline=*/false, SourceLocation(),
10139 SourceLocation(), &Context->Idents.get("std"),
10140 /*PrevDecl=*/nullptr, /*Nested=*/false);
10141 NS->setImplicit();
10142 VaListDecl->setDeclContext(NS);
10143 }
10144
10145 VaListDecl->startDefinition();
10146
10147 // void * __ap;
10148 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10149 VaListDecl,
10152 &Context->Idents.get("__ap"),
10153 Context->getPointerType(Context->VoidTy),
10154 /*TInfo=*/nullptr,
10155 /*BitWidth=*/nullptr,
10156 /*Mutable=*/false,
10157 ICIS_NoInit);
10158 Field->setAccess(AS_public);
10159 VaListDecl->addDecl(Field);
10160
10161 // };
10162 VaListDecl->completeDefinition();
10163 Context->VaListTagDecl = VaListDecl;
10164
10165 // typedef struct __va_list __builtin_va_list;
10166 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10167 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10168}
10169
10170static TypedefDecl *
10172 // struct __va_list_tag {
10174 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10175 VaListTagDecl->startDefinition();
10176
10177 const size_t NumFields = 4;
10178 QualType FieldTypes[NumFields];
10179 const char *FieldNames[NumFields];
10180
10181 // long __gpr;
10182 FieldTypes[0] = Context->LongTy;
10183 FieldNames[0] = "__gpr";
10184
10185 // long __fpr;
10186 FieldTypes[1] = Context->LongTy;
10187 FieldNames[1] = "__fpr";
10188
10189 // void *__overflow_arg_area;
10190 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10191 FieldNames[2] = "__overflow_arg_area";
10192
10193 // void *__reg_save_area;
10194 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10195 FieldNames[3] = "__reg_save_area";
10196
10197 // Create fields
10198 for (unsigned i = 0; i < NumFields; ++i) {
10199 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10203 &Context->Idents.get(FieldNames[i]),
10204 FieldTypes[i], /*TInfo=*/nullptr,
10205 /*BitWidth=*/nullptr,
10206 /*Mutable=*/false,
10207 ICIS_NoInit);
10208 Field->setAccess(AS_public);
10209 VaListTagDecl->addDecl(Field);
10210 }
10211 VaListTagDecl->completeDefinition();
10212 Context->VaListTagDecl = VaListTagDecl;
10213 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10214
10215 // };
10216
10217 // typedef __va_list_tag __builtin_va_list[1];
10218 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10219 QualType VaListTagArrayType = Context->getConstantArrayType(
10220 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10221
10222 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10223}
10224
10226 // typedef struct __va_list_tag {
10228 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10229 VaListTagDecl->startDefinition();
10230
10231 const size_t NumFields = 3;
10232 QualType FieldTypes[NumFields];
10233 const char *FieldNames[NumFields];
10234
10235 // void *CurrentSavedRegisterArea;
10236 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10237 FieldNames[0] = "__current_saved_reg_area_pointer";
10238
10239 // void *SavedRegAreaEnd;
10240 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10241 FieldNames[1] = "__saved_reg_area_end_pointer";
10242
10243 // void *OverflowArea;
10244 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10245 FieldNames[2] = "__overflow_area_pointer";
10246
10247 // Create fields
10248 for (unsigned i = 0; i < NumFields; ++i) {
10250 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10251 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10252 /*TInfo=*/nullptr,
10253 /*BitWidth=*/nullptr,
10254 /*Mutable=*/false, ICIS_NoInit);
10255 Field->setAccess(AS_public);
10256 VaListTagDecl->addDecl(Field);
10257 }
10258 VaListTagDecl->completeDefinition();
10259 Context->VaListTagDecl = VaListTagDecl;
10260 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10261
10262 // } __va_list_tag;
10263 TypedefDecl *VaListTagTypedefDecl =
10264 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10265
10266 QualType VaListTagTypedefType =
10267 Context->getTypedefType(ElaboratedTypeKeyword::None,
10268 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10269
10270 // typedef __va_list_tag __builtin_va_list[1];
10271 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10272 QualType VaListTagArrayType = Context->getConstantArrayType(
10273 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10274
10275 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10276}
10277
10278static TypedefDecl *
10280 // typedef struct __va_list_tag {
10281 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10282
10283 VaListTagDecl->startDefinition();
10284
10285 // int* __va_stk;
10286 // int* __va_reg;
10287 // int __va_ndx;
10288 constexpr size_t NumFields = 3;
10289 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10290 Context->getPointerType(Context->IntTy),
10291 Context->IntTy};
10292 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10293
10294 // Create fields
10295 for (unsigned i = 0; i < NumFields; ++i) {
10298 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10299 /*BitWidth=*/nullptr,
10300 /*Mutable=*/false, ICIS_NoInit);
10301 Field->setAccess(AS_public);
10302 VaListTagDecl->addDecl(Field);
10303 }
10304 VaListTagDecl->completeDefinition();
10305 Context->VaListTagDecl = VaListTagDecl;
10306 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10307
10308 // } __va_list_tag;
10309 TypedefDecl *VaListTagTypedefDecl =
10310 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10311
10312 return VaListTagTypedefDecl;
10313}
10314
10317 switch (Kind) {
10319 return CreateCharPtrBuiltinVaListDecl(Context);
10321 return CreateVoidPtrBuiltinVaListDecl(Context);
10323 return CreateAArch64ABIBuiltinVaListDecl(Context);
10325 return CreatePowerABIBuiltinVaListDecl(Context);
10327 return CreateX86_64ABIBuiltinVaListDecl(Context);
10329 return CreateAAPCSABIBuiltinVaListDecl(Context);
10331 return CreateSystemZBuiltinVaListDecl(Context);
10333 return CreateHexagonBuiltinVaListDecl(Context);
10335 return CreateXtensaABIBuiltinVaListDecl(Context);
10336 }
10337
10338 llvm_unreachable("Unhandled __builtin_va_list type kind");
10339}
10340
10342 if (!BuiltinVaListDecl) {
10343 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10344 assert(BuiltinVaListDecl->isImplicit());
10345 }
10346
10347 return BuiltinVaListDecl;
10348}
10349
10351 // Force the creation of VaListTagDecl by building the __builtin_va_list
10352 // declaration.
10353 if (!VaListTagDecl)
10354 (void)getBuiltinVaListDecl();
10355
10356 return VaListTagDecl;
10357}
10358
10360 if (!BuiltinMSVaListDecl)
10361 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10362
10363 return BuiltinMSVaListDecl;
10364}
10365
10367 // Allow redecl custom type checking builtin for HLSL.
10368 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10369 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10370 return true;
10371 // Allow redecl custom type checking builtin for SPIR-V.
10372 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10373 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10374 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10375 return true;
10376 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10377}
10378
10380 assert(ObjCConstantStringType.isNull() &&
10381 "'NSConstantString' type already set!");
10382
10383 ObjCConstantStringType = getObjCInterfaceType(Decl);
10384}
10385
10386/// Retrieve the template name that corresponds to a non-empty
10387/// lookup.
10390 UnresolvedSetIterator End) const {
10391 unsigned size = End - Begin;
10392 assert(size > 1 && "set is not overloaded!");
10393
10394 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10395 size * sizeof(FunctionTemplateDecl*));
10396 auto *OT = new (memory) OverloadedTemplateStorage(size);
10397
10398 NamedDecl **Storage = OT->getStorage();
10399 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10400 NamedDecl *D = *I;
10401 assert(isa<FunctionTemplateDecl>(D) ||
10405 *Storage++ = D;
10406 }
10407
10408 return TemplateName(OT);
10409}
10410
10411/// Retrieve a template name representing an unqualified-id that has been
10412/// assumed to name a template for ADL purposes.
10414 auto *OT = new (*this) AssumedTemplateStorage(Name);
10415 return TemplateName(OT);
10416}
10417
10418/// Retrieve the template name that represents a qualified
10419/// template name such as \c std::vector.
10421 bool TemplateKeyword,
10422 TemplateName Template) const {
10423 assert(Template.getKind() == TemplateName::Template ||
10425
10426 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10427 assert(!Qualifier && "unexpected qualified template template parameter");
10428 assert(TemplateKeyword == false);
10429 return Template;
10430 }
10431
10432 // FIXME: Canonicalization?
10433 llvm::FoldingSetNodeID ID;
10434 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10435
10436 void *InsertPos = nullptr;
10438 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10439 if (!QTN) {
10440 QTN = new (*this, alignof(QualifiedTemplateName))
10441 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10442 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10443 }
10444
10445 return TemplateName(QTN);
10446}
10447
10448/// Retrieve the template name that represents a dependent
10449/// template name such as \c MetaFun::template operator+.
10452 llvm::FoldingSetNodeID ID;
10453 S.Profile(ID);
10454
10455 void *InsertPos = nullptr;
10456 if (DependentTemplateName *QTN =
10457 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10458 return TemplateName(QTN);
10459
10461 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10462 DependentTemplateNames.InsertNode(QTN, InsertPos);
10463 return TemplateName(QTN);
10464}
10465
10467 Decl *AssociatedDecl,
10468 unsigned Index,
10469 UnsignedOrNone PackIndex,
10470 bool Final) const {
10471 llvm::FoldingSetNodeID ID;
10472 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10473 Index, PackIndex, Final);
10474
10475 void *insertPos = nullptr;
10477 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10478
10479 if (!subst) {
10480 subst = new (*this) SubstTemplateTemplateParmStorage(
10481 Replacement, AssociatedDecl, Index, PackIndex, Final);
10482 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10483 }
10484
10485 return TemplateName(subst);
10486}
10487
10490 Decl *AssociatedDecl,
10491 unsigned Index, bool Final) const {
10492 auto &Self = const_cast<ASTContext &>(*this);
10493 llvm::FoldingSetNodeID ID;
10495 AssociatedDecl, Index, Final);
10496
10497 void *InsertPos = nullptr;
10499 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10500
10501 if (!Subst) {
10502 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10503 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10504 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10505 }
10506
10507 return TemplateName(Subst);
10508}
10509
10510/// Retrieve the template name that represents a template name
10511/// deduced from a specialization.
10514 DefaultArguments DefaultArgs) const {
10515 if (!DefaultArgs)
10516 return Underlying;
10517
10518 llvm::FoldingSetNodeID ID;
10519 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10520
10521 void *InsertPos = nullptr;
10523 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10524 if (!DTS) {
10525 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10526 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10527 alignof(DeducedTemplateStorage));
10528 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10529 DeducedTemplates.InsertNode(DTS, InsertPos);
10530 }
10531 return TemplateName(DTS);
10532}
10533
10534/// getFromTargetType - Given one of the integer types provided by
10535/// TargetInfo, produce the corresponding type. The unsigned @p Type
10536/// is actually a value of type @c TargetInfo::IntType.
10537CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10538 switch (Type) {
10539 case TargetInfo::NoInt: return {};
10542 case TargetInfo::SignedShort: return ShortTy;
10544 case TargetInfo::SignedInt: return IntTy;
10546 case TargetInfo::SignedLong: return LongTy;
10550 }
10551
10552 llvm_unreachable("Unhandled TargetInfo::IntType value");
10553}
10554
10555//===----------------------------------------------------------------------===//
10556// Type Predicates.
10557//===----------------------------------------------------------------------===//
10558
10559/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10560/// garbage collection attribute.
10561///
10563 if (getLangOpts().getGC() == LangOptions::NonGC)
10564 return Qualifiers::GCNone;
10565
10566 assert(getLangOpts().ObjC);
10567 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10568
10569 // Default behaviour under objective-C's gc is for ObjC pointers
10570 // (or pointers to them) be treated as though they were declared
10571 // as __strong.
10572 if (GCAttrs == Qualifiers::GCNone) {
10574 return Qualifiers::Strong;
10575 else if (Ty->isPointerType())
10577 } else {
10578 // It's not valid to set GC attributes on anything that isn't a
10579 // pointer.
10580#ifndef NDEBUG
10582 while (const auto *AT = dyn_cast<ArrayType>(CT))
10583 CT = AT->getElementType();
10584 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10585#endif
10586 }
10587 return GCAttrs;
10588}
10589
10590//===----------------------------------------------------------------------===//
10591// Type Compatibility Testing
10592//===----------------------------------------------------------------------===//
10593
10594/// areCompatVectorTypes - Return true if the two specified vector types are
10595/// compatible.
10596static bool areCompatVectorTypes(const VectorType *LHS,
10597 const VectorType *RHS) {
10598 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10599 return LHS->getElementType() == RHS->getElementType() &&
10600 LHS->getNumElements() == RHS->getNumElements();
10601}
10602
10603/// areCompatMatrixTypes - Return true if the two specified matrix types are
10604/// compatible.
10606 const ConstantMatrixType *RHS) {
10607 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10608 return LHS->getElementType() == RHS->getElementType() &&
10609 LHS->getNumRows() == RHS->getNumRows() &&
10610 LHS->getNumColumns() == RHS->getNumColumns();
10611}
10612
10614 QualType SecondVec) {
10615 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10616 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10617
10618 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10619 return true;
10620
10621 // Treat Neon vector types and most AltiVec vector types as if they are the
10622 // equivalent GCC vector types.
10623 const auto *First = FirstVec->castAs<VectorType>();
10624 const auto *Second = SecondVec->castAs<VectorType>();
10625 if (First->getNumElements() == Second->getNumElements() &&
10626 hasSameType(First->getElementType(), Second->getElementType()) &&
10627 First->getVectorKind() != VectorKind::AltiVecPixel &&
10628 First->getVectorKind() != VectorKind::AltiVecBool &&
10631 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10632 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10635 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10637 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10639 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10641 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10643 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10645 return true;
10646
10647 // In OpenCL, treat half and _Float16 vector types as compatible.
10648 if (getLangOpts().OpenCL &&
10649 First->getNumElements() == Second->getNumElements()) {
10650 QualType FirstElt = First->getElementType();
10651 QualType SecondElt = Second->getElementType();
10652
10653 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10654 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10655 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10656 First->getVectorKind() != VectorKind::AltiVecBool &&
10659 return true;
10660 }
10661 }
10662 return false;
10663}
10664
10670
10673 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10674 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10675
10676 if (!LHSOBT && !RHSOBT)
10678
10679 if (LHSOBT && RHSOBT) {
10680 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10683 }
10684
10685 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10686 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10687
10688 if (RHSOBT && !LHSOBT) {
10689 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10691 }
10692
10694}
10695
10696/// getRVVTypeSize - Return RVV vector register size.
10697static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10698 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10699 auto VScale = Context.getTargetInfo().getVScaleRange(
10700 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10701 if (!VScale)
10702 return 0;
10703
10704 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10705
10706 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10707 if (Info.ElementType == Context.BoolTy)
10708 EltSize = 1;
10709
10710 uint64_t MinElts = Info.EC.getKnownMinValue();
10711 return VScale->first * MinElts * EltSize;
10712}
10713
10715 QualType SecondType) {
10716 assert(
10717 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10718 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10719 "Expected RVV builtin type and vector type!");
10720
10721 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10722 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10723 if (const auto *VT = SecondType->getAs<VectorType>()) {
10724 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10726 return FirstType->isRVVVLSBuiltinType() &&
10727 Info.ElementType == BoolTy &&
10728 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10729 }
10730 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10732 return FirstType->isRVVVLSBuiltinType() &&
10733 Info.ElementType == BoolTy &&
10734 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10735 }
10736 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10738 return FirstType->isRVVVLSBuiltinType() &&
10739 Info.ElementType == BoolTy &&
10740 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10741 }
10742 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10744 return FirstType->isRVVVLSBuiltinType() &&
10745 Info.ElementType == BoolTy &&
10746 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10747 }
10748 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10749 VT->getVectorKind() == VectorKind::Generic)
10750 return FirstType->isRVVVLSBuiltinType() &&
10751 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10752 hasSameType(VT->getElementType(),
10753 getBuiltinVectorTypeInfo(BT).ElementType);
10754 }
10755 }
10756 return false;
10757 };
10758
10759 return IsValidCast(FirstType, SecondType) ||
10760 IsValidCast(SecondType, FirstType);
10761}
10762
10764 QualType SecondType) {
10765 assert(
10766 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10767 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10768 "Expected RVV builtin type and vector type!");
10769
10770 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10771 const auto *BT = FirstType->getAs<BuiltinType>();
10772 if (!BT)
10773 return false;
10774
10775 if (!BT->isRVVVLSBuiltinType())
10776 return false;
10777
10778 const auto *VecTy = SecondType->getAs<VectorType>();
10779 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10781 getLangOpts().getLaxVectorConversions();
10782
10783 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10784 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10785 return false;
10786
10787 // If -flax-vector-conversions=all is specified, the types are
10788 // certainly compatible.
10790 return true;
10791
10792 // If -flax-vector-conversions=integer is specified, the types are
10793 // compatible if the elements are integer types.
10795 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10796 FirstType->getRVVEltType(*this)->isIntegerType();
10797 }
10798
10799 return false;
10800 };
10801
10802 return IsLaxCompatible(FirstType, SecondType) ||
10803 IsLaxCompatible(SecondType, FirstType);
10804}
10805
10807 while (true) {
10808 // __strong id
10809 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10810 if (Attr->getAttrKind() == attr::ObjCOwnership)
10811 return true;
10812
10813 Ty = Attr->getModifiedType();
10814
10815 // X *__strong (...)
10816 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10817 Ty = Paren->getInnerType();
10818
10819 // We do not want to look through typedefs, typeof(expr),
10820 // typeof(type), or any other way that the type is somehow
10821 // abstracted.
10822 } else {
10823 return false;
10824 }
10825 }
10826}
10827
10828//===----------------------------------------------------------------------===//
10829// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10830//===----------------------------------------------------------------------===//
10831
10832/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10833/// inheritance hierarchy of 'rProto'.
10834bool
10836 ObjCProtocolDecl *rProto) const {
10837 if (declaresSameEntity(lProto, rProto))
10838 return true;
10839 for (auto *PI : rProto->protocols())
10840 if (ProtocolCompatibleWithProtocol(lProto, PI))
10841 return true;
10842 return false;
10843}
10844
10845/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10846/// Class<pr1, ...>.
10848 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10849 for (auto *lhsProto : lhs->quals()) {
10850 bool match = false;
10851 for (auto *rhsProto : rhs->quals()) {
10852 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10853 match = true;
10854 break;
10855 }
10856 }
10857 if (!match)
10858 return false;
10859 }
10860 return true;
10861}
10862
10863/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10864/// ObjCQualifiedIDType.
10866 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10867 bool compare) {
10868 // Allow id<P..> and an 'id' in all cases.
10869 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10870 return true;
10871
10872 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10873 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10875 return false;
10876
10877 if (lhs->isObjCQualifiedIdType()) {
10878 if (rhs->qual_empty()) {
10879 // If the RHS is a unqualified interface pointer "NSString*",
10880 // make sure we check the class hierarchy.
10881 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10882 for (auto *I : lhs->quals()) {
10883 // when comparing an id<P> on lhs with a static type on rhs,
10884 // see if static class implements all of id's protocols, directly or
10885 // through its super class and categories.
10886 if (!rhsID->ClassImplementsProtocol(I, true))
10887 return false;
10888 }
10889 }
10890 // If there are no qualifiers and no interface, we have an 'id'.
10891 return true;
10892 }
10893 // Both the right and left sides have qualifiers.
10894 for (auto *lhsProto : lhs->quals()) {
10895 bool match = false;
10896
10897 // when comparing an id<P> on lhs with a static type on rhs,
10898 // see if static class implements all of id's protocols, directly or
10899 // through its super class and categories.
10900 for (auto *rhsProto : rhs->quals()) {
10901 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10902 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10903 match = true;
10904 break;
10905 }
10906 }
10907 // If the RHS is a qualified interface pointer "NSString<P>*",
10908 // make sure we check the class hierarchy.
10909 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10910 for (auto *I : lhs->quals()) {
10911 // when comparing an id<P> on lhs with a static type on rhs,
10912 // see if static class implements all of id's protocols, directly or
10913 // through its super class and categories.
10914 if (rhsID->ClassImplementsProtocol(I, true)) {
10915 match = true;
10916 break;
10917 }
10918 }
10919 }
10920 if (!match)
10921 return false;
10922 }
10923
10924 return true;
10925 }
10926
10927 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10928
10929 if (lhs->getInterfaceType()) {
10930 // If both the right and left sides have qualifiers.
10931 for (auto *lhsProto : lhs->quals()) {
10932 bool match = false;
10933
10934 // when comparing an id<P> on rhs with a static type on lhs,
10935 // see if static class implements all of id's protocols, directly or
10936 // through its super class and categories.
10937 // First, lhs protocols in the qualifier list must be found, direct
10938 // or indirect in rhs's qualifier list or it is a mismatch.
10939 for (auto *rhsProto : rhs->quals()) {
10940 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10941 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10942 match = true;
10943 break;
10944 }
10945 }
10946 if (!match)
10947 return false;
10948 }
10949
10950 // Static class's protocols, or its super class or category protocols
10951 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10952 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10953 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10954 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10955 // This is rather dubious but matches gcc's behavior. If lhs has
10956 // no type qualifier and its class has no static protocol(s)
10957 // assume that it is mismatch.
10958 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10959 return false;
10960 for (auto *lhsProto : LHSInheritedProtocols) {
10961 bool match = false;
10962 for (auto *rhsProto : rhs->quals()) {
10963 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10964 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10965 match = true;
10966 break;
10967 }
10968 }
10969 if (!match)
10970 return false;
10971 }
10972 }
10973 return true;
10974 }
10975 return false;
10976}
10977
10978/// canAssignObjCInterfaces - Return true if the two interface types are
10979/// compatible for assignment from RHS to LHS. This handles validation of any
10980/// protocol qualifiers on the LHS or RHS.
10982 const ObjCObjectPointerType *RHSOPT) {
10983 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10984 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10985
10986 // If either type represents the built-in 'id' type, return true.
10987 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10988 return true;
10989
10990 // Function object that propagates a successful result or handles
10991 // __kindof types.
10992 auto finish = [&](bool succeeded) -> bool {
10993 if (succeeded)
10994 return true;
10995
10996 if (!RHS->isKindOfType())
10997 return false;
10998
10999 // Strip off __kindof and protocol qualifiers, then check whether
11000 // we can assign the other way.
11002 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11003 };
11004
11005 // Casts from or to id<P> are allowed when the other side has compatible
11006 // protocols.
11007 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11008 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11009 }
11010
11011 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11012 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11013 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11014 }
11015
11016 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11017 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11018 return true;
11019 }
11020
11021 // If we have 2 user-defined types, fall into that path.
11022 if (LHS->getInterface() && RHS->getInterface()) {
11023 return finish(canAssignObjCInterfaces(LHS, RHS));
11024 }
11025
11026 return false;
11027}
11028
11029/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11030/// for providing type-safety for objective-c pointers used to pass/return
11031/// arguments in block literals. When passed as arguments, passing 'A*' where
11032/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11033/// not OK. For the return type, the opposite is not OK.
11035 const ObjCObjectPointerType *LHSOPT,
11036 const ObjCObjectPointerType *RHSOPT,
11037 bool BlockReturnType) {
11038
11039 // Function object that propagates a successful result or handles
11040 // __kindof types.
11041 auto finish = [&](bool succeeded) -> bool {
11042 if (succeeded)
11043 return true;
11044
11045 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11046 if (!Expected->isKindOfType())
11047 return false;
11048
11049 // Strip off __kindof and protocol qualifiers, then check whether
11050 // we can assign the other way.
11052 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11053 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11054 BlockReturnType);
11055 };
11056
11057 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11058 return true;
11059
11060 if (LHSOPT->isObjCBuiltinType()) {
11061 return finish(RHSOPT->isObjCBuiltinType() ||
11062 RHSOPT->isObjCQualifiedIdType());
11063 }
11064
11065 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11066 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11067 // Use for block parameters previous type checking for compatibility.
11068 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11069 // Or corrected type checking as in non-compat mode.
11070 (!BlockReturnType &&
11071 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11072 else
11074 (BlockReturnType ? LHSOPT : RHSOPT),
11075 (BlockReturnType ? RHSOPT : LHSOPT), false));
11076 }
11077
11078 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11079 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11080 if (LHS && RHS) { // We have 2 user-defined types.
11081 if (LHS != RHS) {
11082 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11083 return finish(BlockReturnType);
11084 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11085 return finish(!BlockReturnType);
11086 }
11087 else
11088 return true;
11089 }
11090 return false;
11091}
11092
11093/// Comparison routine for Objective-C protocols to be used with
11094/// llvm::array_pod_sort.
11096 ObjCProtocolDecl * const *rhs) {
11097 return (*lhs)->getName().compare((*rhs)->getName());
11098}
11099
11100/// getIntersectionOfProtocols - This routine finds the intersection of set
11101/// of protocols inherited from two distinct objective-c pointer objects with
11102/// the given common base.
11103/// It is used to build composite qualifier list of the composite type of
11104/// the conditional expression involving two objective-c pointer objects.
11105static
11107 const ObjCInterfaceDecl *CommonBase,
11108 const ObjCObjectPointerType *LHSOPT,
11109 const ObjCObjectPointerType *RHSOPT,
11110 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11111
11112 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11113 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11114 assert(LHS->getInterface() && "LHS must have an interface base");
11115 assert(RHS->getInterface() && "RHS must have an interface base");
11116
11117 // Add all of the protocols for the LHS.
11119
11120 // Start with the protocol qualifiers.
11121 for (auto *proto : LHS->quals()) {
11122 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11123 }
11124
11125 // Also add the protocols associated with the LHS interface.
11126 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11127
11128 // Add all of the protocols for the RHS.
11130
11131 // Start with the protocol qualifiers.
11132 for (auto *proto : RHS->quals()) {
11133 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11134 }
11135
11136 // Also add the protocols associated with the RHS interface.
11137 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11138
11139 // Compute the intersection of the collected protocol sets.
11140 for (auto *proto : LHSProtocolSet) {
11141 if (RHSProtocolSet.count(proto))
11142 IntersectionSet.push_back(proto);
11143 }
11144
11145 // Compute the set of protocols that is implied by either the common type or
11146 // the protocols within the intersection.
11148 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11149
11150 // Remove any implied protocols from the list of inherited protocols.
11151 if (!ImpliedProtocols.empty()) {
11152 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11153 return ImpliedProtocols.contains(proto);
11154 });
11155 }
11156
11157 // Sort the remaining protocols by name.
11158 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11160}
11161
11162/// Determine whether the first type is a subtype of the second.
11164 QualType rhs) {
11165 // Common case: two object pointers.
11166 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11167 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11168 if (lhsOPT && rhsOPT)
11169 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11170
11171 // Two block pointers.
11172 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11173 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11174 if (lhsBlock && rhsBlock)
11175 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11176
11177 // If either is an unqualified 'id' and the other is a block, it's
11178 // acceptable.
11179 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11180 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11181 return true;
11182
11183 return false;
11184}
11185
11186// Check that the given Objective-C type argument lists are equivalent.
11188 const ObjCInterfaceDecl *iface,
11189 ArrayRef<QualType> lhsArgs,
11190 ArrayRef<QualType> rhsArgs,
11191 bool stripKindOf) {
11192 if (lhsArgs.size() != rhsArgs.size())
11193 return false;
11194
11195 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11196 if (!typeParams)
11197 return false;
11198
11199 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11200 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11201 continue;
11202
11203 switch (typeParams->begin()[i]->getVariance()) {
11205 if (!stripKindOf ||
11206 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11207 rhsArgs[i].stripObjCKindOfType(ctx))) {
11208 return false;
11209 }
11210 break;
11211
11213 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11214 return false;
11215 break;
11216
11218 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11219 return false;
11220 break;
11221 }
11222 }
11223
11224 return true;
11225}
11226
11228 const ObjCObjectPointerType *Lptr,
11229 const ObjCObjectPointerType *Rptr) {
11230 const ObjCObjectType *LHS = Lptr->getObjectType();
11231 const ObjCObjectType *RHS = Rptr->getObjectType();
11232 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11233 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11234
11235 if (!LDecl || !RDecl)
11236 return {};
11237
11238 // When either LHS or RHS is a kindof type, we should return a kindof type.
11239 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11240 // kindof(A).
11241 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11242
11243 // Follow the left-hand side up the class hierarchy until we either hit a
11244 // root or find the RHS. Record the ancestors in case we don't find it.
11245 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11246 LHSAncestors;
11247 while (true) {
11248 // Record this ancestor. We'll need this if the common type isn't in the
11249 // path from the LHS to the root.
11250 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11251
11252 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11253 // Get the type arguments.
11254 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11255 bool anyChanges = false;
11256 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11257 // Both have type arguments, compare them.
11258 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11259 LHS->getTypeArgs(), RHS->getTypeArgs(),
11260 /*stripKindOf=*/true))
11261 return {};
11262 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11263 // If only one has type arguments, the result will not have type
11264 // arguments.
11265 LHSTypeArgs = {};
11266 anyChanges = true;
11267 }
11268
11269 // Compute the intersection of protocols.
11271 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11272 Protocols);
11273 if (!Protocols.empty())
11274 anyChanges = true;
11275
11276 // If anything in the LHS will have changed, build a new result type.
11277 // If we need to return a kindof type but LHS is not a kindof type, we
11278 // build a new result type.
11279 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11280 QualType Result = getObjCInterfaceType(LHS->getInterface());
11281 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11282 anyKindOf || LHS->isKindOfType());
11284 }
11285
11286 return getObjCObjectPointerType(QualType(LHS, 0));
11287 }
11288
11289 // Find the superclass.
11290 QualType LHSSuperType = LHS->getSuperClassType();
11291 if (LHSSuperType.isNull())
11292 break;
11293
11294 LHS = LHSSuperType->castAs<ObjCObjectType>();
11295 }
11296
11297 // We didn't find anything by following the LHS to its root; now check
11298 // the RHS against the cached set of ancestors.
11299 while (true) {
11300 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11301 if (KnownLHS != LHSAncestors.end()) {
11302 LHS = KnownLHS->second;
11303
11304 // Get the type arguments.
11305 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11306 bool anyChanges = false;
11307 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11308 // Both have type arguments, compare them.
11309 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11310 LHS->getTypeArgs(), RHS->getTypeArgs(),
11311 /*stripKindOf=*/true))
11312 return {};
11313 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11314 // If only one has type arguments, the result will not have type
11315 // arguments.
11316 RHSTypeArgs = {};
11317 anyChanges = true;
11318 }
11319
11320 // Compute the intersection of protocols.
11322 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11323 Protocols);
11324 if (!Protocols.empty())
11325 anyChanges = true;
11326
11327 // If we need to return a kindof type but RHS is not a kindof type, we
11328 // build a new result type.
11329 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11330 QualType Result = getObjCInterfaceType(RHS->getInterface());
11331 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11332 anyKindOf || RHS->isKindOfType());
11334 }
11335
11336 return getObjCObjectPointerType(QualType(RHS, 0));
11337 }
11338
11339 // Find the superclass of the RHS.
11340 QualType RHSSuperType = RHS->getSuperClassType();
11341 if (RHSSuperType.isNull())
11342 break;
11343
11344 RHS = RHSSuperType->castAs<ObjCObjectType>();
11345 }
11346
11347 return {};
11348}
11349
11351 const ObjCObjectType *RHS) {
11352 assert(LHS->getInterface() && "LHS is not an interface type");
11353 assert(RHS->getInterface() && "RHS is not an interface type");
11354
11355 // Verify that the base decls are compatible: the RHS must be a subclass of
11356 // the LHS.
11357 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11358 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11359 if (!IsSuperClass)
11360 return false;
11361
11362 // If the LHS has protocol qualifiers, determine whether all of them are
11363 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11364 // LHS).
11365 if (LHS->getNumProtocols() > 0) {
11366 // OK if conversion of LHS to SuperClass results in narrowing of types
11367 // ; i.e., SuperClass may implement at least one of the protocols
11368 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11369 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11370 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11371 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11372 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11373 // qualifiers.
11374 for (auto *RHSPI : RHS->quals())
11375 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11376 // If there is no protocols associated with RHS, it is not a match.
11377 if (SuperClassInheritedProtocols.empty())
11378 return false;
11379
11380 for (const auto *LHSProto : LHS->quals()) {
11381 bool SuperImplementsProtocol = false;
11382 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11383 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11384 SuperImplementsProtocol = true;
11385 break;
11386 }
11387 if (!SuperImplementsProtocol)
11388 return false;
11389 }
11390 }
11391
11392 // If the LHS is specialized, we may need to check type arguments.
11393 if (LHS->isSpecialized()) {
11394 // Follow the superclass chain until we've matched the LHS class in the
11395 // hierarchy. This substitutes type arguments through.
11396 const ObjCObjectType *RHSSuper = RHS;
11397 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11398 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11399
11400 // If the RHS is specializd, compare type arguments.
11401 if (RHSSuper->isSpecialized() &&
11402 !sameObjCTypeArgs(*this, LHS->getInterface(),
11403 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11404 /*stripKindOf=*/true)) {
11405 return false;
11406 }
11407 }
11408
11409 return true;
11410}
11411
11413 // get the "pointed to" types
11414 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11415 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11416
11417 if (!LHSOPT || !RHSOPT)
11418 return false;
11419
11420 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11421 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11422}
11423
11426 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11427 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11428}
11429
11430/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11431/// both shall have the identically qualified version of a compatible type.
11432/// C99 6.2.7p1: Two types have compatible types if their types are the
11433/// same. See 6.7.[2,3,5] for additional rules.
11435 bool CompareUnqualified) {
11436 if (getLangOpts().CPlusPlus)
11437 return hasSameType(LHS, RHS);
11438
11439 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11440}
11441
11443 return typesAreCompatible(LHS, RHS);
11444}
11445
11447 return !mergeTypes(LHS, RHS, true).isNull();
11448}
11449
11450/// mergeTransparentUnionType - if T is a transparent union type and a member
11451/// of T is compatible with SubType, return the merged type, else return
11452/// QualType()
11454 bool OfBlockPointer,
11455 bool Unqualified) {
11456 if (const RecordType *UT = T->getAsUnionType()) {
11457 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11458 if (UD->hasAttr<TransparentUnionAttr>()) {
11459 for (const auto *I : UD->fields()) {
11460 QualType ET = I->getType().getUnqualifiedType();
11461 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11462 if (!MT.isNull())
11463 return MT;
11464 }
11465 }
11466 }
11467
11468 return {};
11469}
11470
11471/// mergeFunctionParameterTypes - merge two types which appear as function
11472/// parameter types
11474 bool OfBlockPointer,
11475 bool Unqualified) {
11476 // GNU extension: two types are compatible if they appear as a function
11477 // argument, one of the types is a transparent union type and the other
11478 // type is compatible with a union member
11479 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11480 Unqualified);
11481 if (!lmerge.isNull())
11482 return lmerge;
11483
11484 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11485 Unqualified);
11486 if (!rmerge.isNull())
11487 return rmerge;
11488
11489 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11490}
11491
11493 bool OfBlockPointer, bool Unqualified,
11494 bool AllowCXX,
11495 bool IsConditionalOperator) {
11496 const auto *lbase = lhs->castAs<FunctionType>();
11497 const auto *rbase = rhs->castAs<FunctionType>();
11498 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11499 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11500 bool allLTypes = true;
11501 bool allRTypes = true;
11502
11503 // Check return type
11504 QualType retType;
11505 if (OfBlockPointer) {
11506 QualType RHS = rbase->getReturnType();
11507 QualType LHS = lbase->getReturnType();
11508 bool UnqualifiedResult = Unqualified;
11509 if (!UnqualifiedResult)
11510 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11511 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11512 }
11513 else
11514 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11515 Unqualified);
11516 if (retType.isNull())
11517 return {};
11518
11519 if (Unqualified)
11520 retType = retType.getUnqualifiedType();
11521
11522 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11523 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11524 if (Unqualified) {
11525 LRetType = LRetType.getUnqualifiedType();
11526 RRetType = RRetType.getUnqualifiedType();
11527 }
11528
11529 if (getCanonicalType(retType) != LRetType)
11530 allLTypes = false;
11531 if (getCanonicalType(retType) != RRetType)
11532 allRTypes = false;
11533
11534 // FIXME: double check this
11535 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11536 // rbase->getRegParmAttr() != 0 &&
11537 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11538 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11539 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11540
11541 // Compatible functions must have compatible calling conventions
11542 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11543 return {};
11544
11545 // Regparm is part of the calling convention.
11546 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11547 return {};
11548 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11549 return {};
11550
11551 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11552 return {};
11553 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11554 return {};
11555 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11556 return {};
11557
11558 // When merging declarations, it's common for supplemental information like
11559 // attributes to only be present in one of the declarations, and we generally
11560 // want type merging to preserve the union of information. So a merged
11561 // function type should be noreturn if it was noreturn in *either* operand
11562 // type.
11563 //
11564 // But for the conditional operator, this is backwards. The result of the
11565 // operator could be either operand, and its type should conservatively
11566 // reflect that. So a function type in a composite type is noreturn only
11567 // if it's noreturn in *both* operand types.
11568 //
11569 // Arguably, noreturn is a kind of subtype, and the conditional operator
11570 // ought to produce the most specific common supertype of its operand types.
11571 // That would differ from this rule in contravariant positions. However,
11572 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11573 // as a practical matter, it would only affect C code that does abstraction of
11574 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11575 // say the least. So we use the simpler rule.
11576 bool NoReturn = IsConditionalOperator
11577 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11578 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11579 if (lbaseInfo.getNoReturn() != NoReturn)
11580 allLTypes = false;
11581 if (rbaseInfo.getNoReturn() != NoReturn)
11582 allRTypes = false;
11583
11584 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11585
11586 std::optional<FunctionEffectSet> MergedFX;
11587
11588 if (lproto && rproto) { // two C99 style function prototypes
11589 assert((AllowCXX ||
11590 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11591 "C++ shouldn't be here");
11592 // Compatible functions must have the same number of parameters
11593 if (lproto->getNumParams() != rproto->getNumParams())
11594 return {};
11595
11596 // Variadic and non-variadic functions aren't compatible
11597 if (lproto->isVariadic() != rproto->isVariadic())
11598 return {};
11599
11600 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11601 return {};
11602
11603 // Function protos with different 'cfi_salt' values aren't compatible.
11604 if (lproto->getExtraAttributeInfo().CFISalt !=
11605 rproto->getExtraAttributeInfo().CFISalt)
11606 return {};
11607
11608 // Function effects are handled similarly to noreturn, see above.
11609 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11610 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11611 if (LHSFX != RHSFX) {
11612 if (IsConditionalOperator)
11613 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11614 else {
11616 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11617 // Here we're discarding a possible error due to conflicts in the effect
11618 // sets. But we're not in a context where we can report it. The
11619 // operation does however guarantee maintenance of invariants.
11620 }
11621 if (*MergedFX != LHSFX)
11622 allLTypes = false;
11623 if (*MergedFX != RHSFX)
11624 allRTypes = false;
11625 }
11626
11628 bool canUseLeft, canUseRight;
11629 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11630 newParamInfos))
11631 return {};
11632
11633 if (!canUseLeft)
11634 allLTypes = false;
11635 if (!canUseRight)
11636 allRTypes = false;
11637
11638 // Check parameter type compatibility
11640 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11641 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11642 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11644 lParamType, rParamType, OfBlockPointer, Unqualified);
11645 if (paramType.isNull())
11646 return {};
11647
11648 if (Unqualified)
11649 paramType = paramType.getUnqualifiedType();
11650
11651 types.push_back(paramType);
11652 if (Unqualified) {
11653 lParamType = lParamType.getUnqualifiedType();
11654 rParamType = rParamType.getUnqualifiedType();
11655 }
11656
11657 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11658 allLTypes = false;
11659 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11660 allRTypes = false;
11661 }
11662
11663 if (allLTypes) return lhs;
11664 if (allRTypes) return rhs;
11665
11666 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11667 EPI.ExtInfo = einfo;
11668 EPI.ExtParameterInfos =
11669 newParamInfos.empty() ? nullptr : newParamInfos.data();
11670 if (MergedFX)
11671 EPI.FunctionEffects = *MergedFX;
11672 return getFunctionType(retType, types, EPI);
11673 }
11674
11675 if (lproto) allRTypes = false;
11676 if (rproto) allLTypes = false;
11677
11678 const FunctionProtoType *proto = lproto ? lproto : rproto;
11679 if (proto) {
11680 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11681 if (proto->isVariadic())
11682 return {};
11683 // Check that the types are compatible with the types that
11684 // would result from default argument promotions (C99 6.7.5.3p15).
11685 // The only types actually affected are promotable integer
11686 // types and floats, which would be passed as a different
11687 // type depending on whether the prototype is visible.
11688 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11689 QualType paramTy = proto->getParamType(i);
11690
11691 // Look at the converted type of enum types, since that is the type used
11692 // to pass enum values.
11693 if (const auto *ED = paramTy->getAsEnumDecl()) {
11694 paramTy = ED->getIntegerType();
11695 if (paramTy.isNull())
11696 return {};
11697 }
11698
11699 if (isPromotableIntegerType(paramTy) ||
11700 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11701 return {};
11702 }
11703
11704 if (allLTypes) return lhs;
11705 if (allRTypes) return rhs;
11706
11708 EPI.ExtInfo = einfo;
11709 if (MergedFX)
11710 EPI.FunctionEffects = *MergedFX;
11711 return getFunctionType(retType, proto->getParamTypes(), EPI);
11712 }
11713
11714 if (allLTypes) return lhs;
11715 if (allRTypes) return rhs;
11716 return getFunctionNoProtoType(retType, einfo);
11717}
11718
11719/// Given that we have an enum type and a non-enum type, try to merge them.
11720static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11721 QualType other, bool isBlockReturnType) {
11722 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11723 // a signed integer type, or an unsigned integer type.
11724 // Compatibility is based on the underlying type, not the promotion
11725 // type.
11726 QualType underlyingType =
11727 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11728 if (underlyingType.isNull())
11729 return {};
11730 if (Context.hasSameType(underlyingType, other))
11731 return other;
11732
11733 // In block return types, we're more permissive and accept any
11734 // integral type of the same size.
11735 if (isBlockReturnType && other->isIntegerType() &&
11736 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11737 return other;
11738
11739 return {};
11740}
11741
11743 // C17 and earlier and C++ disallow two tag definitions within the same TU
11744 // from being compatible.
11745 if (LangOpts.CPlusPlus || !LangOpts.C23)
11746 return {};
11747
11748 // Nameless tags are comparable only within outer definitions. At the top
11749 // level they are not comparable.
11750 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11751 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11752 return {};
11753
11754 // C23, on the other hand, requires the members to be "the same enough", so
11755 // we use a structural equivalence check.
11758 getLangOpts(), *this, *this, NonEquivalentDecls,
11759 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11760 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11761 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11762}
11763
11765 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11766 bool BlockReturnType, bool IsConditionalOperator) {
11767 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11768 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11769
11770 if (!LHSOBT && !RHSOBT)
11771 return std::nullopt;
11772
11773 if (LHSOBT) {
11774 if (RHSOBT) {
11775 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11776 return QualType();
11777
11778 QualType MergedUnderlying = mergeTypes(
11779 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11780 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11781
11782 if (MergedUnderlying.isNull())
11783 return QualType();
11784
11785 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11786 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11787 return getCommonSugaredType(LHS, RHS);
11789 LHSOBT->getBehaviorKind(),
11790 getCanonicalType(LHSOBT->getUnderlyingType()));
11791 }
11792
11793 // For different underlying types that successfully merge, wrap the
11794 // merged underlying type with the common overflow behavior
11795 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11796 MergedUnderlying);
11797 }
11798 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11799 Unqualified, BlockReturnType, IsConditionalOperator);
11800 }
11801
11802 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11803 Unqualified, BlockReturnType, IsConditionalOperator);
11804}
11805
11806QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11807 bool Unqualified, bool BlockReturnType,
11808 bool IsConditionalOperator) {
11809 // For C++ we will not reach this code with reference types (see below),
11810 // for OpenMP variant call overloading we might.
11811 //
11812 // C++ [expr]: If an expression initially has the type "reference to T", the
11813 // type is adjusted to "T" prior to any further analysis, the expression
11814 // designates the object or function denoted by the reference, and the
11815 // expression is an lvalue unless the reference is an rvalue reference and
11816 // the expression is a function call (possibly inside parentheses).
11817 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11818 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11819 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11820 LHS->getTypeClass() == RHS->getTypeClass())
11821 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11822 OfBlockPointer, Unqualified, BlockReturnType);
11823 if (LHSRefTy || RHSRefTy)
11824 return {};
11825
11826 if (std::optional<QualType> MergedOBT =
11827 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11828 BlockReturnType, IsConditionalOperator))
11829 return *MergedOBT;
11830
11831 if (Unqualified) {
11832 LHS = LHS.getUnqualifiedType();
11833 RHS = RHS.getUnqualifiedType();
11834 }
11835
11836 QualType LHSCan = getCanonicalType(LHS),
11837 RHSCan = getCanonicalType(RHS);
11838
11839 // If two types are identical, they are compatible.
11840 if (LHSCan == RHSCan)
11841 return LHS;
11842
11843 // If the qualifiers are different, the types aren't compatible... mostly.
11844 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11845 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11846 if (LQuals != RQuals) {
11847 // If any of these qualifiers are different, we have a type
11848 // mismatch.
11849 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11850 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11851 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11852 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11853 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11854 return {};
11855
11856 // Exactly one GC qualifier difference is allowed: __strong is
11857 // okay if the other type has no GC qualifier but is an Objective
11858 // C object pointer (i.e. implicitly strong by default). We fix
11859 // this by pretending that the unqualified type was actually
11860 // qualified __strong.
11861 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11862 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11863 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11864
11865 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11866 return {};
11867
11868 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11870 }
11871 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11873 }
11874 return {};
11875 }
11876
11877 // Okay, qualifiers are equal.
11878
11879 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11880 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11881
11882 // We want to consider the two function types to be the same for these
11883 // comparisons, just force one to the other.
11884 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11885 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11886
11887 // Same as above for arrays
11888 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11889 LHSClass = Type::ConstantArray;
11890 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11891 RHSClass = Type::ConstantArray;
11892
11893 // ObjCInterfaces are just specialized ObjCObjects.
11894 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11895 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11896
11897 // Canonicalize ExtVector -> Vector.
11898 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11899 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11900
11901 // If the canonical type classes don't match.
11902 if (LHSClass != RHSClass) {
11903 // Note that we only have special rules for turning block enum
11904 // returns into block int returns, not vice-versa.
11905 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11906 return mergeEnumWithInteger(*this, ETy, RHS, false);
11907 }
11908 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11909 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11910 }
11911 // allow block pointer type to match an 'id' type.
11912 if (OfBlockPointer && !BlockReturnType) {
11913 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11914 return LHS;
11915 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11916 return RHS;
11917 }
11918 // Allow __auto_type to match anything; it merges to the type with more
11919 // information.
11920 if (const auto *AT = LHS->getAs<AutoType>()) {
11921 if (!AT->isDeduced() && AT->isGNUAutoType())
11922 return RHS;
11923 }
11924 if (const auto *AT = RHS->getAs<AutoType>()) {
11925 if (!AT->isDeduced() && AT->isGNUAutoType())
11926 return LHS;
11927 }
11928 return {};
11929 }
11930
11931 // The canonical type classes match.
11932 switch (LHSClass) {
11933#define TYPE(Class, Base)
11934#define ABSTRACT_TYPE(Class, Base)
11935#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11936#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11937#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11938#include "clang/AST/TypeNodes.inc"
11939 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11940
11941 case Type::Auto:
11942 case Type::DeducedTemplateSpecialization:
11943 case Type::LValueReference:
11944 case Type::RValueReference:
11945 case Type::MemberPointer:
11946 llvm_unreachable("C++ should never be in mergeTypes");
11947
11948 case Type::ObjCInterface:
11949 case Type::IncompleteArray:
11950 case Type::VariableArray:
11951 case Type::FunctionProto:
11952 case Type::ExtVector:
11953 case Type::OverflowBehavior:
11954 llvm_unreachable("Types are eliminated above");
11955
11956 case Type::Pointer:
11957 {
11958 // Merge two pointer types, while trying to preserve typedef info
11959 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11960 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11961 if (Unqualified) {
11962 LHSPointee = LHSPointee.getUnqualifiedType();
11963 RHSPointee = RHSPointee.getUnqualifiedType();
11964 }
11965 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11966 Unqualified);
11967 if (ResultType.isNull())
11968 return {};
11969 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11970 return LHS;
11971 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11972 return RHS;
11973 return getPointerType(ResultType);
11974 }
11975 case Type::BlockPointer:
11976 {
11977 // Merge two block pointer types, while trying to preserve typedef info
11978 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11979 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11980 if (Unqualified) {
11981 LHSPointee = LHSPointee.getUnqualifiedType();
11982 RHSPointee = RHSPointee.getUnqualifiedType();
11983 }
11984 if (getLangOpts().OpenCL) {
11985 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11986 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11987 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11988 // 6.12.5) thus the following check is asymmetric.
11989 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11990 return {};
11991 LHSPteeQual.removeAddressSpace();
11992 RHSPteeQual.removeAddressSpace();
11993 LHSPointee =
11994 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11995 RHSPointee =
11996 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11997 }
11998 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11999 Unqualified);
12000 if (ResultType.isNull())
12001 return {};
12002 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12003 return LHS;
12004 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12005 return RHS;
12006 return getBlockPointerType(ResultType);
12007 }
12008 case Type::Atomic:
12009 {
12010 // Merge two pointer types, while trying to preserve typedef info
12011 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12012 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12013 if (Unqualified) {
12014 LHSValue = LHSValue.getUnqualifiedType();
12015 RHSValue = RHSValue.getUnqualifiedType();
12016 }
12017 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12018 Unqualified);
12019 if (ResultType.isNull())
12020 return {};
12021 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12022 return LHS;
12023 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12024 return RHS;
12025 return getAtomicType(ResultType);
12026 }
12027 case Type::ConstantArray:
12028 {
12029 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12030 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12031 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12032 return {};
12033
12034 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12035 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12036 if (Unqualified) {
12037 LHSElem = LHSElem.getUnqualifiedType();
12038 RHSElem = RHSElem.getUnqualifiedType();
12039 }
12040
12041 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12042 if (ResultType.isNull())
12043 return {};
12044
12045 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12046 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12047
12048 // If either side is a variable array, and both are complete, check whether
12049 // the current dimension is definite.
12050 if (LVAT || RVAT) {
12051 auto SizeFetch = [this](const VariableArrayType* VAT,
12052 const ConstantArrayType* CAT)
12053 -> std::pair<bool,llvm::APInt> {
12054 if (VAT) {
12055 std::optional<llvm::APSInt> TheInt;
12056 Expr *E = VAT->getSizeExpr();
12057 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12058 return std::make_pair(true, *TheInt);
12059 return std::make_pair(false, llvm::APSInt());
12060 }
12061 if (CAT)
12062 return std::make_pair(true, CAT->getSize());
12063 return std::make_pair(false, llvm::APInt());
12064 };
12065
12066 bool HaveLSize, HaveRSize;
12067 llvm::APInt LSize, RSize;
12068 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12069 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12070 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12071 return {}; // Definite, but unequal, array dimension
12072 }
12073
12074 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12075 return LHS;
12076 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12077 return RHS;
12078 if (LCAT)
12079 return getConstantArrayType(ResultType, LCAT->getSize(),
12080 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12081 if (RCAT)
12082 return getConstantArrayType(ResultType, RCAT->getSize(),
12083 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12084 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12085 return LHS;
12086 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12087 return RHS;
12088 if (LVAT) {
12089 // FIXME: This isn't correct! But tricky to implement because
12090 // the array's size has to be the size of LHS, but the type
12091 // has to be different.
12092 return LHS;
12093 }
12094 if (RVAT) {
12095 // FIXME: This isn't correct! But tricky to implement because
12096 // the array's size has to be the size of RHS, but the type
12097 // has to be different.
12098 return RHS;
12099 }
12100 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12101 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12102 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12103 }
12104 case Type::FunctionNoProto:
12105 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12106 /*AllowCXX=*/false, IsConditionalOperator);
12107 case Type::Record:
12108 case Type::Enum:
12109 return mergeTagDefinitions(LHS, RHS);
12110 case Type::Builtin:
12111 // Only exactly equal builtin types are compatible, which is tested above.
12112 return {};
12113 case Type::Complex:
12114 // Distinct complex types are incompatible.
12115 return {};
12116 case Type::Vector:
12117 // FIXME: The merged type should be an ExtVector!
12118 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12119 RHSCan->castAs<VectorType>()))
12120 return LHS;
12121 return {};
12122 case Type::ConstantMatrix:
12124 RHSCan->castAs<ConstantMatrixType>()))
12125 return LHS;
12126 return {};
12127 case Type::ObjCObject: {
12128 // Check if the types are assignment compatible.
12129 // FIXME: This should be type compatibility, e.g. whether
12130 // "LHS x; RHS x;" at global scope is legal.
12132 RHS->castAs<ObjCObjectType>()))
12133 return LHS;
12134 return {};
12135 }
12136 case Type::ObjCObjectPointer:
12137 if (OfBlockPointer) {
12140 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12141 return LHS;
12142 return {};
12143 }
12146 return LHS;
12147 return {};
12148 case Type::Pipe:
12149 assert(LHS != RHS &&
12150 "Equivalent pipe types should have already been handled!");
12151 return {};
12152 case Type::ArrayParameter:
12153 assert(LHS != RHS &&
12154 "Equivalent ArrayParameter types should have already been handled!");
12155 return {};
12156 case Type::BitInt: {
12157 // Merge two bit-precise int types, while trying to preserve typedef info.
12158 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12159 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12160 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12161 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12162
12163 // Like unsigned/int, shouldn't have a type if they don't match.
12164 if (LHSUnsigned != RHSUnsigned)
12165 return {};
12166
12167 if (LHSBits != RHSBits)
12168 return {};
12169 return LHS;
12170 }
12171 case Type::HLSLAttributedResource: {
12172 const HLSLAttributedResourceType *LHSTy =
12173 LHS->castAs<HLSLAttributedResourceType>();
12174 const HLSLAttributedResourceType *RHSTy =
12175 RHS->castAs<HLSLAttributedResourceType>();
12176 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12177 LHSTy->getWrappedType()->isHLSLResourceType() &&
12178 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12179
12180 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12181 LHSTy->getContainedType() == RHSTy->getContainedType())
12182 return LHS;
12183 return {};
12184 }
12185 case Type::HLSLInlineSpirv:
12186 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12187 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12188
12189 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12190 LHSTy->getSize() == RHSTy->getSize() &&
12191 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12192 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12193 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12194 return {};
12195
12196 return LHS;
12197 }
12198 return {};
12199 }
12200
12201 llvm_unreachable("Invalid Type::Class!");
12202}
12203
12205 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12206 bool &CanUseFirst, bool &CanUseSecond,
12208 assert(NewParamInfos.empty() && "param info list not empty");
12209 CanUseFirst = CanUseSecond = true;
12210 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12211 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12212
12213 // Fast path: if the first type doesn't have ext parameter infos,
12214 // we match if and only if the second type also doesn't have them.
12215 if (!FirstHasInfo && !SecondHasInfo)
12216 return true;
12217
12218 bool NeedParamInfo = false;
12219 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12220 : SecondFnType->getExtParameterInfos().size();
12221
12222 for (size_t I = 0; I < E; ++I) {
12223 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12224 if (FirstHasInfo)
12225 FirstParam = FirstFnType->getExtParameterInfo(I);
12226 if (SecondHasInfo)
12227 SecondParam = SecondFnType->getExtParameterInfo(I);
12228
12229 // Cannot merge unless everything except the noescape flag matches.
12230 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12231 return false;
12232
12233 bool FirstNoEscape = FirstParam.isNoEscape();
12234 bool SecondNoEscape = SecondParam.isNoEscape();
12235 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12236 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12237 if (NewParamInfos.back().getOpaqueValue())
12238 NeedParamInfo = true;
12239 if (FirstNoEscape != IsNoEscape)
12240 CanUseFirst = false;
12241 if (SecondNoEscape != IsNoEscape)
12242 CanUseSecond = false;
12243 }
12244
12245 if (!NeedParamInfo)
12246 NewParamInfos.clear();
12247
12248 return true;
12249}
12250
12252 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12253 It->second = nullptr;
12254 for (auto *SubClass : ObjCSubClasses.lookup(D))
12255 ResetObjCLayout(SubClass);
12256 }
12257}
12258
12259/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12260/// 'RHS' attributes and returns the merged version; including for function
12261/// return types.
12263 QualType LHSCan = getCanonicalType(LHS),
12264 RHSCan = getCanonicalType(RHS);
12265 // If two types are identical, they are compatible.
12266 if (LHSCan == RHSCan)
12267 return LHS;
12268 if (RHSCan->isFunctionType()) {
12269 if (!LHSCan->isFunctionType())
12270 return {};
12271 QualType OldReturnType =
12272 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12273 QualType NewReturnType =
12274 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12275 QualType ResReturnType =
12276 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12277 if (ResReturnType.isNull())
12278 return {};
12279 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12280 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12281 // In either case, use OldReturnType to build the new function type.
12282 const auto *F = LHS->castAs<FunctionType>();
12283 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12284 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12285 EPI.ExtInfo = getFunctionExtInfo(LHS);
12286 QualType ResultType =
12287 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12288 return ResultType;
12289 }
12290 }
12291 return {};
12292 }
12293
12294 // If the qualifiers are different, the types can still be merged.
12295 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12296 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12297 if (LQuals != RQuals) {
12298 // If any of these qualifiers are different, we have a type mismatch.
12299 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12300 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12301 return {};
12302
12303 // Exactly one GC qualifier difference is allowed: __strong is
12304 // okay if the other type has no GC qualifier but is an Objective
12305 // C object pointer (i.e. implicitly strong by default). We fix
12306 // this by pretending that the unqualified type was actually
12307 // qualified __strong.
12308 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12309 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12310 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12311
12312 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12313 return {};
12314
12315 if (GC_L == Qualifiers::Strong)
12316 return LHS;
12317 if (GC_R == Qualifiers::Strong)
12318 return RHS;
12319 return {};
12320 }
12321
12322 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12323 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12324 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12325 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12326 if (ResQT == LHSBaseQT)
12327 return LHS;
12328 if (ResQT == RHSBaseQT)
12329 return RHS;
12330 }
12331 return {};
12332}
12333
12334//===----------------------------------------------------------------------===//
12335// Integer Predicates
12336//===----------------------------------------------------------------------===//
12337
12339 if (const auto *ED = T->getAsEnumDecl())
12340 T = ED->getIntegerType();
12341 if (T->isBooleanType())
12342 return 1;
12343 if (const auto *EIT = T->getAs<BitIntType>())
12344 return EIT->getNumBits();
12345 // For builtin types, just use the standard type sizing method
12346 return (unsigned)getTypeSize(T);
12347}
12348
12350 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12351 T->isFixedPointType()) &&
12352 "Unexpected type");
12353
12354 // Turn <4 x signed int> -> <4 x unsigned int>
12355 if (const auto *VTy = T->getAs<VectorType>())
12356 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12357 VTy->getNumElements(), VTy->getVectorKind());
12358
12359 // For _BitInt, return an unsigned _BitInt with same width.
12360 if (const auto *EITy = T->getAs<BitIntType>())
12361 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12362
12363 // For the overflow behavior types, construct a new unsigned variant
12364 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12366 OBT->getBehaviorKind(),
12367 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12368
12369 // For enums, get the underlying integer type of the enum, and let the general
12370 // integer type signchanging code handle it.
12371 if (const auto *ED = T->getAsEnumDecl())
12372 T = ED->getIntegerType();
12373
12374 switch (T->castAs<BuiltinType>()->getKind()) {
12375 case BuiltinType::Char_U:
12376 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12377 case BuiltinType::Char_S:
12378 case BuiltinType::SChar:
12379 case BuiltinType::Char8:
12380 return UnsignedCharTy;
12381 case BuiltinType::Short:
12382 return UnsignedShortTy;
12383 case BuiltinType::Int:
12384 return UnsignedIntTy;
12385 case BuiltinType::Long:
12386 return UnsignedLongTy;
12387 case BuiltinType::LongLong:
12388 return UnsignedLongLongTy;
12389 case BuiltinType::Int128:
12390 return UnsignedInt128Ty;
12391 // wchar_t is special. It is either signed or not, but when it's signed,
12392 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12393 // version of its underlying type instead.
12394 case BuiltinType::WChar_S:
12395 return getUnsignedWCharType();
12396
12397 case BuiltinType::ShortAccum:
12398 return UnsignedShortAccumTy;
12399 case BuiltinType::Accum:
12400 return UnsignedAccumTy;
12401 case BuiltinType::LongAccum:
12402 return UnsignedLongAccumTy;
12403 case BuiltinType::SatShortAccum:
12405 case BuiltinType::SatAccum:
12406 return SatUnsignedAccumTy;
12407 case BuiltinType::SatLongAccum:
12409 case BuiltinType::ShortFract:
12410 return UnsignedShortFractTy;
12411 case BuiltinType::Fract:
12412 return UnsignedFractTy;
12413 case BuiltinType::LongFract:
12414 return UnsignedLongFractTy;
12415 case BuiltinType::SatShortFract:
12417 case BuiltinType::SatFract:
12418 return SatUnsignedFractTy;
12419 case BuiltinType::SatLongFract:
12421 default:
12422 assert((T->hasUnsignedIntegerRepresentation() ||
12423 T->isUnsignedFixedPointType()) &&
12424 "Unexpected signed integer or fixed point type");
12425 return T;
12426 }
12427}
12428
12430 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12431 T->isFixedPointType()) &&
12432 "Unexpected type");
12433
12434 // Turn <4 x unsigned int> -> <4 x signed int>
12435 if (const auto *VTy = T->getAs<VectorType>())
12436 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12437 VTy->getNumElements(), VTy->getVectorKind());
12438
12439 // For _BitInt, return a signed _BitInt with same width.
12440 if (const auto *EITy = T->getAs<BitIntType>())
12441 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12442
12443 // For enums, get the underlying integer type of the enum, and let the general
12444 // integer type signchanging code handle it.
12445 if (const auto *ED = T->getAsEnumDecl())
12446 T = ED->getIntegerType();
12447
12448 switch (T->castAs<BuiltinType>()->getKind()) {
12449 case BuiltinType::Char_S:
12450 // Plain `char` is mapped to `signed char` even if it's already signed
12451 case BuiltinType::Char_U:
12452 case BuiltinType::UChar:
12453 case BuiltinType::Char8:
12454 return SignedCharTy;
12455 case BuiltinType::UShort:
12456 return ShortTy;
12457 case BuiltinType::UInt:
12458 return IntTy;
12459 case BuiltinType::ULong:
12460 return LongTy;
12461 case BuiltinType::ULongLong:
12462 return LongLongTy;
12463 case BuiltinType::UInt128:
12464 return Int128Ty;
12465 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12466 // there's no matching "signed wchar_t". Therefore we return the signed
12467 // version of its underlying type instead.
12468 case BuiltinType::WChar_U:
12469 return getSignedWCharType();
12470
12471 case BuiltinType::UShortAccum:
12472 return ShortAccumTy;
12473 case BuiltinType::UAccum:
12474 return AccumTy;
12475 case BuiltinType::ULongAccum:
12476 return LongAccumTy;
12477 case BuiltinType::SatUShortAccum:
12478 return SatShortAccumTy;
12479 case BuiltinType::SatUAccum:
12480 return SatAccumTy;
12481 case BuiltinType::SatULongAccum:
12482 return SatLongAccumTy;
12483 case BuiltinType::UShortFract:
12484 return ShortFractTy;
12485 case BuiltinType::UFract:
12486 return FractTy;
12487 case BuiltinType::ULongFract:
12488 return LongFractTy;
12489 case BuiltinType::SatUShortFract:
12490 return SatShortFractTy;
12491 case BuiltinType::SatUFract:
12492 return SatFractTy;
12493 case BuiltinType::SatULongFract:
12494 return SatLongFractTy;
12495 default:
12496 assert(
12497 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12498 "Unexpected signed integer or fixed point type");
12499 return T;
12500 }
12501}
12502
12504
12507
12508//===----------------------------------------------------------------------===//
12509// Builtin Type Computation
12510//===----------------------------------------------------------------------===//
12511
12512/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12513/// pointer over the consumed characters. This returns the resultant type. If
12514/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12515/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12516/// a vector of "i*".
12517///
12518/// RequiresICE is filled in on return to indicate whether the value is required
12519/// to be an Integer Constant Expression.
12520static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12522 bool &RequiresICE,
12523 bool AllowTypeModifiers) {
12524 // Modifiers.
12525 int HowLong = 0;
12526 bool Signed = false, Unsigned = false;
12527 RequiresICE = false;
12528
12529 // Read the prefixed modifiers first.
12530 bool Done = false;
12531 #ifndef NDEBUG
12532 bool IsSpecial = false;
12533 #endif
12534 while (!Done) {
12535 switch (*Str++) {
12536 default: Done = true; --Str; break;
12537 case 'I':
12538 RequiresICE = true;
12539 break;
12540 case 'S':
12541 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12542 assert(!Signed && "Can't use 'S' modifier multiple times!");
12543 Signed = true;
12544 break;
12545 case 'U':
12546 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12547 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12548 Unsigned = true;
12549 break;
12550 case 'L':
12551 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12552 assert(HowLong <= 2 && "Can't have LLLL modifier");
12553 ++HowLong;
12554 break;
12555 case 'N':
12556 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12557 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12558 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12559 #ifndef NDEBUG
12560 IsSpecial = true;
12561 #endif
12562 if (Context.getTargetInfo().getLongWidth() == 32)
12563 ++HowLong;
12564 break;
12565 case 'W':
12566 // This modifier represents int64 type.
12567 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12568 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12569 #ifndef NDEBUG
12570 IsSpecial = true;
12571 #endif
12572 switch (Context.getTargetInfo().getInt64Type()) {
12573 default:
12574 llvm_unreachable("Unexpected integer type");
12576 HowLong = 1;
12577 break;
12579 HowLong = 2;
12580 break;
12581 }
12582 break;
12583 case 'Z':
12584 // This modifier represents int32 type.
12585 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12586 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12587 #ifndef NDEBUG
12588 IsSpecial = true;
12589 #endif
12590 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12591 default:
12592 llvm_unreachable("Unexpected integer type");
12594 HowLong = 0;
12595 break;
12597 HowLong = 1;
12598 break;
12600 HowLong = 2;
12601 break;
12602 }
12603 break;
12604 case 'O':
12605 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12606 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12607 #ifndef NDEBUG
12608 IsSpecial = true;
12609 #endif
12610 if (Context.getLangOpts().OpenCL)
12611 HowLong = 1;
12612 else
12613 HowLong = 2;
12614 break;
12615 }
12616 }
12617
12618 QualType Type;
12619
12620 // Read the base type.
12621 switch (*Str++) {
12622 default:
12623 llvm_unreachable("Unknown builtin type letter!");
12624 case 'x':
12625 assert(HowLong == 0 && !Signed && !Unsigned &&
12626 "Bad modifiers used with 'x'!");
12627 Type = Context.Float16Ty;
12628 break;
12629 case 'y':
12630 assert(HowLong == 0 && !Signed && !Unsigned &&
12631 "Bad modifiers used with 'y'!");
12632 Type = Context.BFloat16Ty;
12633 break;
12634 case 'v':
12635 assert(HowLong == 0 && !Signed && !Unsigned &&
12636 "Bad modifiers used with 'v'!");
12637 Type = Context.VoidTy;
12638 break;
12639 case 'h':
12640 assert(HowLong == 0 && !Signed && !Unsigned &&
12641 "Bad modifiers used with 'h'!");
12642 Type = Context.HalfTy;
12643 break;
12644 case 'f':
12645 assert(HowLong == 0 && !Signed && !Unsigned &&
12646 "Bad modifiers used with 'f'!");
12647 Type = Context.FloatTy;
12648 break;
12649 case 'd':
12650 assert(HowLong < 3 && !Signed && !Unsigned &&
12651 "Bad modifiers used with 'd'!");
12652 if (HowLong == 1)
12653 Type = Context.LongDoubleTy;
12654 else if (HowLong == 2)
12655 Type = Context.Float128Ty;
12656 else
12657 Type = Context.DoubleTy;
12658 break;
12659 case 's':
12660 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12661 if (Unsigned)
12662 Type = Context.UnsignedShortTy;
12663 else
12664 Type = Context.ShortTy;
12665 break;
12666 case 'i':
12667 if (HowLong == 3)
12668 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12669 else if (HowLong == 2)
12670 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12671 else if (HowLong == 1)
12672 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12673 else
12674 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12675 break;
12676 case 'c':
12677 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12678 if (Signed)
12679 Type = Context.SignedCharTy;
12680 else if (Unsigned)
12681 Type = Context.UnsignedCharTy;
12682 else
12683 Type = Context.CharTy;
12684 break;
12685 case 'b': // boolean
12686 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12687 Type = Context.BoolTy;
12688 break;
12689 case 'z': // size_t.
12690 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12691 Type = Context.getSizeType();
12692 break;
12693 case 'w': // wchar_t.
12694 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12695 Type = Context.getWideCharType();
12696 break;
12697 case 'F':
12698 Type = Context.getCFConstantStringType();
12699 break;
12700 case 'G':
12701 Type = Context.getObjCIdType();
12702 break;
12703 case 'H':
12704 Type = Context.getObjCSelType();
12705 break;
12706 case 'M':
12707 Type = Context.getObjCSuperType();
12708 break;
12709 case 'a':
12710 Type = Context.getBuiltinVaListType();
12711 assert(!Type.isNull() && "builtin va list type not initialized!");
12712 break;
12713 case 'A':
12714 // This is a "reference" to a va_list; however, what exactly
12715 // this means depends on how va_list is defined. There are two
12716 // different kinds of va_list: ones passed by value, and ones
12717 // passed by reference. An example of a by-value va_list is
12718 // x86, where va_list is a char*. An example of by-ref va_list
12719 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12720 // we want this argument to be a char*&; for x86-64, we want
12721 // it to be a __va_list_tag*.
12722 Type = Context.getBuiltinVaListType();
12723 assert(!Type.isNull() && "builtin va list type not initialized!");
12724 if (Type->isArrayType())
12725 Type = Context.getArrayDecayedType(Type);
12726 else
12727 Type = Context.getLValueReferenceType(Type);
12728 break;
12729 case 'q': {
12730 char *End;
12731 unsigned NumElements = strtoul(Str, &End, 10);
12732 assert(End != Str && "Missing vector size");
12733 Str = End;
12734
12735 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12736 RequiresICE, false);
12737 assert(!RequiresICE && "Can't require vector ICE");
12738
12739 Type = Context.getScalableVectorType(ElementType, NumElements);
12740 break;
12741 }
12742 case 'Q': {
12743 switch (*Str++) {
12744 case 'a': {
12745 Type = Context.SveCountTy;
12746 break;
12747 }
12748 case 'b': {
12749 Type = Context.AMDGPUBufferRsrcTy;
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 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13382 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13383 }
13384 }
13385 return VTContext.get();
13386}
13387
13389 if (!T)
13390 T = Target;
13391 switch (T->getCXXABI().getKind()) {
13392 case TargetCXXABI::AppleARM64:
13393 case TargetCXXABI::Fuchsia:
13394 case TargetCXXABI::GenericAArch64:
13395 case TargetCXXABI::GenericItanium:
13396 case TargetCXXABI::GenericARM:
13397 case TargetCXXABI::GenericMIPS:
13398 case TargetCXXABI::iOS:
13399 case TargetCXXABI::WebAssembly:
13400 case TargetCXXABI::WatchOS:
13401 case TargetCXXABI::XL:
13403 case TargetCXXABI::Microsoft:
13405 }
13406 llvm_unreachable("Unsupported ABI");
13407}
13408
13410 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13411 "Device mangle context does not support Microsoft mangling.");
13412 switch (T.getCXXABI().getKind()) {
13413 case TargetCXXABI::AppleARM64:
13414 case TargetCXXABI::Fuchsia:
13415 case TargetCXXABI::GenericAArch64:
13416 case TargetCXXABI::GenericItanium:
13417 case TargetCXXABI::GenericARM:
13418 case TargetCXXABI::GenericMIPS:
13419 case TargetCXXABI::iOS:
13420 case TargetCXXABI::WebAssembly:
13421 case TargetCXXABI::WatchOS:
13422 case TargetCXXABI::XL:
13424 *this, getDiagnostics(),
13425 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13426 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13427 return RD->getDeviceLambdaManglingNumber();
13428 return std::nullopt;
13429 },
13430 /*IsAux=*/true);
13431 case TargetCXXABI::Microsoft:
13433 /*IsAux=*/true);
13434 }
13435 llvm_unreachable("Unsupported ABI");
13436}
13437
13439 // If the host and device have different C++ ABIs, mark it as the device
13440 // mangle context so that the mangling needs to retrieve the additional
13441 // device lambda mangling number instead of the regular host one.
13442 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13443 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13445 }
13446
13448}
13449
13450CXXABI::~CXXABI() = default;
13451
13453 return ASTRecordLayouts.getMemorySize() +
13454 llvm::capacity_in_bytes(ObjCLayouts) +
13455 llvm::capacity_in_bytes(KeyFunctions) +
13456 llvm::capacity_in_bytes(ObjCImpls) +
13457 llvm::capacity_in_bytes(BlockVarCopyInits) +
13458 llvm::capacity_in_bytes(DeclAttrs) +
13459 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13460 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13461 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13462 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13463 llvm::capacity_in_bytes(OverriddenMethods) +
13464 llvm::capacity_in_bytes(Types) +
13465 llvm::capacity_in_bytes(VariableArrayTypes);
13466}
13467
13468/// getIntTypeForBitwidth -
13469/// sets integer QualTy according to specified details:
13470/// bitwidth, signed/unsigned.
13471/// Returns empty type if there is no appropriate target types.
13473 unsigned Signed) const {
13475 CanQualType QualTy = getFromTargetType(Ty);
13476 if (!QualTy && DestWidth == 128)
13477 return Signed ? Int128Ty : UnsignedInt128Ty;
13478 return QualTy;
13479}
13480
13481/// getRealTypeForBitwidth -
13482/// sets floating point QualTy according to specified bitwidth.
13483/// Returns empty type if there is no appropriate target types.
13485 FloatModeKind ExplicitType) const {
13486 FloatModeKind Ty =
13487 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13488 switch (Ty) {
13490 return HalfTy;
13492 return FloatTy;
13494 return DoubleTy;
13496 return LongDoubleTy;
13498 return Float128Ty;
13500 return Ibm128Ty;
13502 return {};
13503 }
13504
13505 llvm_unreachable("Unhandled TargetInfo::RealType value");
13506}
13507
13508void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13509 if (Number <= 1)
13510 return;
13511
13512 MangleNumbers[ND] = Number;
13513
13514 if (Listener)
13515 Listener->AddedManglingNumber(ND, Number);
13516}
13517
13519 bool ForAuxTarget) const {
13520 auto I = MangleNumbers.find(ND);
13521 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13522 // CUDA/HIP host compilation encodes host and device mangling numbers
13523 // as lower and upper half of 32 bit integer.
13524 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13525 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13526 } else {
13527 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13528 "number for aux target");
13529 }
13530 return Res > 1 ? Res : 1;
13531}
13532
13533void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13534 if (Number <= 1)
13535 return;
13536
13537 StaticLocalNumbers[VD] = Number;
13538
13539 if (Listener)
13540 Listener->AddedStaticLocalNumbers(VD, Number);
13541}
13542
13544 auto I = StaticLocalNumbers.find(VD);
13545 return I != StaticLocalNumbers.end() ? I->second : 1;
13546}
13547
13549 bool IsDestroying) {
13550 if (!IsDestroying) {
13551 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13552 return;
13553 }
13554 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13555}
13556
13558 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13559}
13560
13562 bool IsTypeAware) {
13563 if (!IsTypeAware) {
13564 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13565 return;
13566 }
13567 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13568}
13569
13571 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13572}
13573
13575 FunctionDecl *OperatorDelete,
13576 OperatorDeleteKind K) const {
13577 switch (K) {
13579 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13580 break;
13582 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13583 OperatorDelete;
13584 break;
13586 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13587 OperatorDelete;
13588 break;
13590 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13591 OperatorDelete;
13592 break;
13593 }
13594}
13595
13597 OperatorDeleteKind K) const {
13598 switch (K) {
13600 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13602 return GlobalOperatorDeletesForVirtualDtor.contains(
13603 Dtor->getCanonicalDecl());
13605 return ArrayOperatorDeletesForVirtualDtor.contains(
13606 Dtor->getCanonicalDecl());
13608 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13609 Dtor->getCanonicalDecl());
13610 }
13611 return false;
13612}
13613
13616 OperatorDeleteKind K) const {
13617 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13618 switch (K) {
13620 if (OperatorDeletesForVirtualDtor.contains(Canon))
13621 return OperatorDeletesForVirtualDtor[Canon];
13622 return nullptr;
13624 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13625 return GlobalOperatorDeletesForVirtualDtor[Canon];
13626 return nullptr;
13628 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13629 return ArrayOperatorDeletesForVirtualDtor[Canon];
13630 return nullptr;
13632 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13633 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13634 return nullptr;
13635 }
13636 return nullptr;
13637}
13638
13640 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13641 return false;
13642 CXXDestructorDecl *Dtor = RD->getDestructor();
13643 // The compiler can't know if new[]/delete[] will be used outside of the DLL,
13644 // so just force vector deleting destructor emission if dllexport is present.
13645 // This matches MSVC behavior.
13646 if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>())
13647 return true;
13648
13649 return RequireVectorDeletingDtor.count(RD);
13650}
13651
13653 const CXXRecordDecl *RD) {
13654 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13655 return;
13656 RequireVectorDeletingDtor.insert(RD);
13657}
13658
13661 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13662 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13663 if (!MCtx)
13665 return *MCtx;
13666}
13667
13670 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13671 std::unique_ptr<MangleNumberingContext> &MCtx =
13672 ExtraMangleNumberingContexts[D];
13673 if (!MCtx)
13675 return *MCtx;
13676}
13677
13678std::unique_ptr<MangleNumberingContext>
13680 return ABI->createMangleNumberingContext();
13681}
13682
13683const CXXConstructorDecl *
13685 return ABI->getCopyConstructorForExceptionObject(
13687}
13688
13690 CXXConstructorDecl *CD) {
13691 return ABI->addCopyConstructorForExceptionObject(
13694}
13695
13697 TypedefNameDecl *DD) {
13698 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13699}
13700
13703 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13704}
13705
13707 DeclaratorDecl *DD) {
13708 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13709}
13710
13712 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13713}
13714
13716 ParamIndices[D] = index;
13717}
13718
13720 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13721 assert(I != ParamIndices.end() &&
13722 "ParmIndices lacks entry set by ParmVarDecl");
13723 return I->second;
13724}
13725
13727 unsigned Length) const {
13728 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13729 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13730 EltTy = EltTy.withConst();
13731
13732 EltTy = adjustStringLiteralBaseType(EltTy);
13733
13734 // Get an array type for the string, according to C99 6.4.5. This includes
13735 // the null terminator character.
13736 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13737 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13738}
13739
13742 StringLiteral *&Result = StringLiteralCache[Key];
13743 if (!Result)
13745 *this, Key, StringLiteralKind::Ordinary,
13746 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13747 SourceLocation());
13748 return Result;
13749}
13750
13751MSGuidDecl *
13753 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13754
13755 llvm::FoldingSetNodeID ID;
13756 MSGuidDecl::Profile(ID, Parts);
13757
13758 void *InsertPos;
13759 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13760 return Existing;
13761
13762 QualType GUIDType = getMSGuidType().withConst();
13763 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13764 MSGuidDecls.InsertNode(New, InsertPos);
13765 return New;
13766}
13767
13770 const APValue &APVal) const {
13771 llvm::FoldingSetNodeID ID;
13773
13774 void *InsertPos;
13775 if (UnnamedGlobalConstantDecl *Existing =
13776 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13777 return Existing;
13778
13780 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13781 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13782 return New;
13783}
13784
13787 assert(T->isRecordType() && "template param object of unexpected type");
13788
13789 // C++ [temp.param]p8:
13790 // [...] a static storage duration object of type 'const T' [...]
13791 T.addConst();
13792
13793 llvm::FoldingSetNodeID ID;
13795
13796 void *InsertPos;
13797 if (TemplateParamObjectDecl *Existing =
13798 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13799 return Existing;
13800
13801 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13802 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13803 return New;
13804}
13805
13807 const llvm::Triple &T = getTargetInfo().getTriple();
13808 if (!T.isOSDarwin())
13809 return false;
13810
13811 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13812 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13813 return false;
13814
13815 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13816 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13817 uint64_t Size = sizeChars.getQuantity();
13818 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13819 unsigned Align = alignChars.getQuantity();
13820 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13821 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13822}
13823
13824bool
13826 const ObjCMethodDecl *MethodImpl) {
13827 // No point trying to match an unavailable/deprecated mothod.
13828 if (MethodDecl->hasAttr<UnavailableAttr>()
13829 || MethodDecl->hasAttr<DeprecatedAttr>())
13830 return false;
13831 if (MethodDecl->getObjCDeclQualifier() !=
13832 MethodImpl->getObjCDeclQualifier())
13833 return false;
13834 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13835 return false;
13836
13837 if (MethodDecl->param_size() != MethodImpl->param_size())
13838 return false;
13839
13840 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13841 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13842 EF = MethodDecl->param_end();
13843 IM != EM && IF != EF; ++IM, ++IF) {
13844 const ParmVarDecl *DeclVar = (*IF);
13845 const ParmVarDecl *ImplVar = (*IM);
13846 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13847 return false;
13848 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13849 return false;
13850 }
13851
13852 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13853}
13854
13856 LangAS AS;
13858 AS = LangAS::Default;
13859 else
13860 AS = QT->getPointeeType().getAddressSpace();
13861
13863}
13864
13867}
13868
13869bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13870 if (X == Y)
13871 return true;
13872 if (!X || !Y)
13873 return false;
13874 llvm::FoldingSetNodeID IDX, IDY;
13875 X->Profile(IDX, *this, /*Canonical=*/true);
13876 Y->Profile(IDY, *this, /*Canonical=*/true);
13877 return IDX == IDY;
13878}
13879
13880// The getCommon* helpers return, for given 'same' X and Y entities given as
13881// inputs, another entity which is also the 'same' as the inputs, but which
13882// is closer to the canonical form of the inputs, each according to a given
13883// criteria.
13884// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13885// the regular ones.
13886
13888 if (!declaresSameEntity(X, Y))
13889 return nullptr;
13890 for (const Decl *DX : X->redecls()) {
13891 // If we reach Y before reaching the first decl, that means X is older.
13892 if (DX == Y)
13893 return X;
13894 // If we reach the first decl, then Y is older.
13895 if (DX->isFirstDecl())
13896 return Y;
13897 }
13898 llvm_unreachable("Corrupt redecls chain");
13899}
13900
13901template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13902static T *getCommonDecl(T *X, T *Y) {
13903 return cast_or_null<T>(
13904 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13905 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13906}
13907
13908template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13909static T *getCommonDeclChecked(T *X, T *Y) {
13910 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13911 const_cast<Decl *>(cast<Decl>(Y))));
13912}
13913
13915 TemplateName Y,
13916 bool IgnoreDeduced = false) {
13917 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13918 return X;
13919 // FIXME: There are cases here where we could find a common template name
13920 // with more sugar. For example one could be a SubstTemplateTemplate*
13921 // replacing the other.
13922 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13923 if (CX.getAsVoidPointer() !=
13925 return TemplateName();
13926 return CX;
13927}
13928
13931 bool IgnoreDeduced) {
13932 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13933 assert(R.getAsVoidPointer() != nullptr);
13934 return R;
13935}
13936
13938 ArrayRef<QualType> Ys, bool Unqualified = false) {
13939 assert(Xs.size() == Ys.size());
13940 SmallVector<QualType, 8> Rs(Xs.size());
13941 for (size_t I = 0; I < Rs.size(); ++I)
13942 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13943 return Rs;
13944}
13945
13946template <class T>
13947static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13948 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13949 : SourceLocation();
13950}
13951
13953 const TemplateArgument &X,
13954 const TemplateArgument &Y) {
13955 if (X.getKind() != Y.getKind())
13956 return TemplateArgument();
13957
13958 switch (X.getKind()) {
13960 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13961 return TemplateArgument();
13962 return TemplateArgument(
13963 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13965 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13966 return TemplateArgument();
13967 return TemplateArgument(
13968 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13969 /*Unqualified=*/true);
13971 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13972 return TemplateArgument();
13973 // FIXME: Try to keep the common sugar.
13974 return X;
13976 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13977 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13978 if (!CTN.getAsVoidPointer())
13979 return TemplateArgument();
13980 return TemplateArgument(CTN);
13981 }
13983 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13985 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13986 if (!CTN.getAsVoidPointer())
13987 return TemplateName();
13988 auto NExpX = X.getNumTemplateExpansions();
13989 assert(NExpX == Y.getNumTemplateExpansions());
13990 return TemplateArgument(CTN, NExpX);
13991 }
13992 default:
13993 // FIXME: Handle the other argument kinds.
13994 return X;
13995 }
13996}
13997
14002 if (Xs.size() != Ys.size())
14003 return true;
14004 R.resize(Xs.size());
14005 for (size_t I = 0; I < R.size(); ++I) {
14006 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14007 if (R[I].isNull())
14008 return true;
14009 }
14010 return false;
14011}
14012
14017 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14018 assert(!Different);
14019 (void)Different;
14020 return R;
14021}
14022
14023template <class T>
14025 bool IsSame) {
14026 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14027 if (KX == KY)
14028 return KX;
14030 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14031 return KX;
14032}
14033
14034/// Returns a NestedNameSpecifier which has only the common sugar
14035/// present in both NNS1 and NNS2.
14038 NestedNameSpecifier NNS2, bool IsSame) {
14039 // If they are identical, all sugar is common.
14040 if (NNS1 == NNS2)
14041 return NNS1;
14042
14043 // IsSame implies both Qualifiers are equivalent.
14044 NestedNameSpecifier Canon = NNS1.getCanonical();
14045 if (Canon != NNS2.getCanonical()) {
14046 assert(!IsSame && "Should be the same NestedNameSpecifier");
14047 // If they are not the same, there is nothing to unify.
14048 return std::nullopt;
14049 }
14050
14051 NestedNameSpecifier R = std::nullopt;
14052 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14053 assert(Kind == NNS2.getKind());
14054 switch (Kind) {
14056 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14057 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14058 auto Kind = Namespace1->getKind();
14059 if (Kind != Namespace2->getKind() ||
14060 (Kind == Decl::NamespaceAlias &&
14061 !declaresSameEntity(Namespace1, Namespace2))) {
14063 Ctx,
14064 ::getCommonDeclChecked(Namespace1->getNamespace(),
14065 Namespace2->getNamespace()),
14066 /*Prefix=*/std::nullopt);
14067 break;
14068 }
14069 // The prefixes for namespaces are not significant, its declaration
14070 // identifies it uniquely.
14071 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14072 /*IsSame=*/false);
14073 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14074 Prefix);
14075 break;
14076 }
14078 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14079 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14080 /*Unqualified=*/true)
14081 .getTypePtr();
14082 R = NestedNameSpecifier(T);
14083 break;
14084 }
14086 // FIXME: Can __super even be used with data members?
14087 // If it's only usable in functions, we will never see it here,
14088 // unless we save the qualifiers used in function types.
14089 // In that case, it might be possible NNS2 is a type,
14090 // in which case we should degrade the result to
14091 // a CXXRecordType.
14093 NNS2.getAsMicrosoftSuper()));
14094 break;
14095 }
14098 // These are singletons.
14099 llvm_unreachable("singletons did not compare equal");
14100 }
14101 assert(R.getCanonical() == Canon);
14102 return R;
14103}
14104
14105template <class T>
14107 const T *Y, bool IsSame) {
14108 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14109}
14110
14111template <class T>
14112static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14113 const T *Y) {
14114 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14115}
14116
14118 QualType X, QualType Y,
14119 Qualifiers &QX,
14120 Qualifiers &QY) {
14121 QualType R = Ctx.getCommonSugaredType(X, Y,
14122 /*Unqualified=*/true);
14123 // Qualifiers common to both element types.
14124 Qualifiers RQ = R.getQualifiers();
14125 // For each side, move to the top level any qualifiers which are not common to
14126 // both element types. The caller must assume top level qualifiers might
14127 // be different, even if they are the same type, and can be treated as sugar.
14128 QX += X.getQualifiers() - RQ;
14129 QY += Y.getQualifiers() - RQ;
14130 return R;
14131}
14132
14133template <class T>
14135 Qualifiers &QX, const T *Y,
14136 Qualifiers &QY) {
14137 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14138 Y->getElementType(), QX, QY);
14139}
14140
14141template <class T>
14142static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14143 const T *Y) {
14144 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14145}
14146
14147template <class T>
14148static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14149 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14150 return X->getSizeExpr();
14151}
14152
14153static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14154 assert(X->getSizeModifier() == Y->getSizeModifier());
14155 return X->getSizeModifier();
14156}
14157
14159 const ArrayType *Y) {
14160 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14161 return X->getIndexTypeCVRQualifiers();
14162}
14163
14164// Merges two type lists such that the resulting vector will contain
14165// each type (in a canonical sense) only once, in the order they appear
14166// from X to Y. If they occur in both X and Y, the result will contain
14167// the common sugared type between them.
14168static void mergeTypeLists(const ASTContext &Ctx,
14171 llvm::DenseMap<QualType, unsigned> Found;
14172 for (auto Ts : {X, Y}) {
14173 for (QualType T : Ts) {
14174 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14175 if (!Res.second) {
14176 QualType &U = Out[Res.first->second];
14177 U = Ctx.getCommonSugaredType(U, T);
14178 } else {
14179 Out.emplace_back(T);
14180 }
14181 }
14182 }
14183}
14184
14185FunctionProtoType::ExceptionSpecInfo
14188 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14189 bool AcceptDependent) const {
14190 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14191
14192 // If either of them can throw anything, that is the result.
14193 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14194 if (EST1 == I)
14195 return ESI1;
14196 if (EST2 == I)
14197 return ESI2;
14198 }
14199
14200 // If either of them is non-throwing, the result is the other.
14201 for (auto I :
14203 if (EST1 == I)
14204 return ESI2;
14205 if (EST2 == I)
14206 return ESI1;
14207 }
14208
14209 // If we're left with value-dependent computed noexcept expressions, we're
14210 // stuck. Before C++17, we can just drop the exception specification entirely,
14211 // since it's not actually part of the canonical type. And this should never
14212 // happen in C++17, because it would mean we were computing the composite
14213 // pointer type of dependent types, which should never happen.
14214 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14215 assert(AcceptDependent &&
14216 "computing composite pointer type of dependent types");
14218 }
14219
14220 // Switch over the possibilities so that people adding new values know to
14221 // update this function.
14222 switch (EST1) {
14223 case EST_None:
14224 case EST_DynamicNone:
14225 case EST_MSAny:
14226 case EST_BasicNoexcept:
14228 case EST_NoexceptFalse:
14229 case EST_NoexceptTrue:
14230 case EST_NoThrow:
14231 llvm_unreachable("These ESTs should be handled above");
14232
14233 case EST_Dynamic: {
14234 // This is the fun case: both exception specifications are dynamic. Form
14235 // the union of the two lists.
14236 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14237 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14238 ESI2.Exceptions);
14240 Result.Exceptions = ExceptionTypeStorage;
14241 return Result;
14242 }
14243
14244 case EST_Unevaluated:
14245 case EST_Uninstantiated:
14246 case EST_Unparsed:
14247 llvm_unreachable("shouldn't see unresolved exception specifications here");
14248 }
14249
14250 llvm_unreachable("invalid ExceptionSpecificationType");
14251}
14252
14254 Qualifiers &QX, const Type *Y,
14255 Qualifiers &QY) {
14256 Type::TypeClass TC = X->getTypeClass();
14257 assert(TC == Y->getTypeClass());
14258 switch (TC) {
14259#define UNEXPECTED_TYPE(Class, Kind) \
14260 case Type::Class: \
14261 llvm_unreachable("Unexpected " Kind ": " #Class);
14262
14263#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14264#define TYPE(Class, Base)
14265#include "clang/AST/TypeNodes.inc"
14266
14267#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14269 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14270 SUGAR_FREE_TYPE(DependentBitInt)
14272 SUGAR_FREE_TYPE(ObjCInterface)
14273 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14274 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14275 SUGAR_FREE_TYPE(UnresolvedUsing)
14276 SUGAR_FREE_TYPE(HLSLAttributedResource)
14277 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14278#undef SUGAR_FREE_TYPE
14279#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14280 NON_UNIQUE_TYPE(TypeOfExpr)
14281 NON_UNIQUE_TYPE(VariableArray)
14282#undef NON_UNIQUE_TYPE
14283
14284 UNEXPECTED_TYPE(TypeOf, "sugar")
14285
14286#undef UNEXPECTED_TYPE
14287
14288 case Type::Auto: {
14289 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14290 assert(AX->getDeducedType().isNull());
14291 assert(AY->getDeducedType().isNull());
14292 assert(AX->getKeyword() == AY->getKeyword());
14293 assert(AX->isInstantiationDependentType() ==
14294 AY->isInstantiationDependentType());
14295 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14296 AY->getTypeConstraintArguments());
14297 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14299 AX->containsUnexpandedParameterPack(),
14300 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14301 AY->getTypeConstraintConcept()),
14302 As);
14303 }
14304 case Type::IncompleteArray: {
14305 const auto *AX = cast<IncompleteArrayType>(X),
14307 return Ctx.getIncompleteArrayType(
14308 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14310 }
14311 case Type::DependentSizedArray: {
14312 const auto *AX = cast<DependentSizedArrayType>(X),
14314 return Ctx.getDependentSizedArrayType(
14315 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14316 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14318 }
14319 case Type::ConstantArray: {
14320 const auto *AX = cast<ConstantArrayType>(X),
14321 *AY = cast<ConstantArrayType>(Y);
14322 assert(AX->getSize() == AY->getSize());
14323 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14324 ? AX->getSizeExpr()
14325 : nullptr;
14326 return Ctx.getConstantArrayType(
14327 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14329 }
14330 case Type::ArrayParameter: {
14331 const auto *AX = cast<ArrayParameterType>(X),
14332 *AY = cast<ArrayParameterType>(Y);
14333 assert(AX->getSize() == AY->getSize());
14334 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14335 ? AX->getSizeExpr()
14336 : nullptr;
14337 auto ArrayTy = Ctx.getConstantArrayType(
14338 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14340 return Ctx.getArrayParameterType(ArrayTy);
14341 }
14342 case Type::Atomic: {
14343 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14344 return Ctx.getAtomicType(
14345 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14346 }
14347 case Type::Complex: {
14348 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14349 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14350 }
14351 case Type::Pointer: {
14352 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14353 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14354 }
14355 case Type::BlockPointer: {
14356 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14357 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14358 }
14359 case Type::ObjCObjectPointer: {
14360 const auto *PX = cast<ObjCObjectPointerType>(X),
14362 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14363 }
14364 case Type::MemberPointer: {
14365 const auto *PX = cast<MemberPointerType>(X),
14366 *PY = cast<MemberPointerType>(Y);
14367 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14368 PY->getMostRecentCXXRecordDecl()));
14369 return Ctx.getMemberPointerType(
14370 getCommonPointeeType(Ctx, PX, PY),
14371 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14372 PX->getMostRecentCXXRecordDecl());
14373 }
14374 case Type::LValueReference: {
14375 const auto *PX = cast<LValueReferenceType>(X),
14377 // FIXME: Preserve PointeeTypeAsWritten.
14378 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14379 PX->isSpelledAsLValue() ||
14380 PY->isSpelledAsLValue());
14381 }
14382 case Type::RValueReference: {
14383 const auto *PX = cast<RValueReferenceType>(X),
14385 // FIXME: Preserve PointeeTypeAsWritten.
14386 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14387 }
14388 case Type::DependentAddressSpace: {
14389 const auto *PX = cast<DependentAddressSpaceType>(X),
14391 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14392 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14393 PX->getAddrSpaceExpr(),
14394 getCommonAttrLoc(PX, PY));
14395 }
14396 case Type::FunctionNoProto: {
14397 const auto *FX = cast<FunctionNoProtoType>(X),
14399 assert(FX->getExtInfo() == FY->getExtInfo());
14400 return Ctx.getFunctionNoProtoType(
14401 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14402 FX->getExtInfo());
14403 }
14404 case Type::FunctionProto: {
14405 const auto *FX = cast<FunctionProtoType>(X),
14406 *FY = cast<FunctionProtoType>(Y);
14407 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14408 EPIY = FY->getExtProtoInfo();
14409 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14410 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14411 assert(!EPIX.ExtParameterInfos ||
14412 llvm::equal(
14413 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14414 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14415 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14416 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14417 assert(EPIX.Variadic == EPIY.Variadic);
14418
14419 // FIXME: Can we handle an empty EllipsisLoc?
14420 // Use emtpy EllipsisLoc if X and Y differ.
14421
14422 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14423
14424 QualType R =
14425 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14426 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14427 /*Unqualified=*/true);
14428
14429 SmallVector<QualType, 8> Exceptions;
14431 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14432 return Ctx.getFunctionType(R, P, EPIX);
14433 }
14434 case Type::ObjCObject: {
14435 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14436 assert(
14437 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14438 OY->getProtocols().begin(), OY->getProtocols().end(),
14439 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14440 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14441 }) &&
14442 "protocol lists must be the same");
14443 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14444 OY->getTypeArgsAsWritten());
14445 return Ctx.getObjCObjectType(
14446 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14447 OX->getProtocols(),
14448 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14449 }
14450 case Type::ConstantMatrix: {
14451 const auto *MX = cast<ConstantMatrixType>(X),
14452 *MY = cast<ConstantMatrixType>(Y);
14453 assert(MX->getNumRows() == MY->getNumRows());
14454 assert(MX->getNumColumns() == MY->getNumColumns());
14455 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14456 MX->getNumRows(), MX->getNumColumns());
14457 }
14458 case Type::DependentSizedMatrix: {
14459 const auto *MX = cast<DependentSizedMatrixType>(X),
14461 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14462 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14463 return Ctx.getDependentSizedMatrixType(
14464 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14465 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14466 }
14467 case Type::Vector: {
14468 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14469 assert(VX->getNumElements() == VY->getNumElements());
14470 assert(VX->getVectorKind() == VY->getVectorKind());
14471 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14472 VX->getNumElements(), VX->getVectorKind());
14473 }
14474 case Type::ExtVector: {
14475 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14476 assert(VX->getNumElements() == VY->getNumElements());
14477 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14478 VX->getNumElements());
14479 }
14480 case Type::DependentSizedExtVector: {
14481 const auto *VX = cast<DependentSizedExtVectorType>(X),
14484 getCommonSizeExpr(Ctx, VX, VY),
14485 getCommonAttrLoc(VX, VY));
14486 }
14487 case Type::DependentVector: {
14488 const auto *VX = cast<DependentVectorType>(X),
14490 assert(VX->getVectorKind() == VY->getVectorKind());
14491 return Ctx.getDependentVectorType(
14492 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14493 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14494 }
14495 case Type::Enum:
14496 case Type::Record:
14497 case Type::InjectedClassName: {
14498 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14499 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14500 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14501 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14502 /*OwnedTag=*/false);
14503 }
14504 case Type::TemplateSpecialization: {
14505 const auto *TX = cast<TemplateSpecializationType>(X),
14507 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14508 TY->template_arguments());
14510 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14511 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14512 TY->getTemplateName(),
14513 /*IgnoreDeduced=*/true),
14514 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14515 }
14516 case Type::Decltype: {
14517 const auto *DX = cast<DecltypeType>(X);
14518 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14519 assert(DX->isDependentType());
14520 assert(DY->isDependentType());
14521 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14522 // As Decltype is not uniqued, building a common type would be wasteful.
14523 return QualType(DX, 0);
14524 }
14525 case Type::PackIndexing: {
14526 const auto *DX = cast<PackIndexingType>(X);
14527 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14528 assert(DX->isDependentType());
14529 assert(DY->isDependentType());
14530 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14531 return QualType(DX, 0);
14532 }
14533 case Type::DependentName: {
14534 const auto *NX = cast<DependentNameType>(X),
14535 *NY = cast<DependentNameType>(Y);
14536 assert(NX->getIdentifier() == NY->getIdentifier());
14537 return Ctx.getDependentNameType(
14538 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14539 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14540 }
14541 case Type::OverflowBehavior: {
14542 const auto *NX = cast<OverflowBehaviorType>(X),
14544 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14545 return Ctx.getOverflowBehaviorType(
14546 NX->getBehaviorKind(),
14547 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14548 NY->getUnderlyingType(), QX, QY));
14549 }
14550 case Type::UnaryTransform: {
14551 const auto *TX = cast<UnaryTransformType>(X),
14552 *TY = cast<UnaryTransformType>(Y);
14553 assert(TX->getUTTKind() == TY->getUTTKind());
14554 return Ctx.getUnaryTransformType(
14555 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14556 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14557 TY->getUnderlyingType()),
14558 TX->getUTTKind());
14559 }
14560 case Type::PackExpansion: {
14561 const auto *PX = cast<PackExpansionType>(X),
14562 *PY = cast<PackExpansionType>(Y);
14563 assert(PX->getNumExpansions() == PY->getNumExpansions());
14564 return Ctx.getPackExpansionType(
14565 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14566 PX->getNumExpansions(), false);
14567 }
14568 case Type::Pipe: {
14569 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14570 assert(PX->isReadOnly() == PY->isReadOnly());
14571 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14573 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14574 }
14575 case Type::TemplateTypeParm: {
14576 const auto *TX = cast<TemplateTypeParmType>(X),
14578 assert(TX->getDepth() == TY->getDepth());
14579 assert(TX->getIndex() == TY->getIndex());
14580 assert(TX->isParameterPack() == TY->isParameterPack());
14581 return Ctx.getTemplateTypeParmType(
14582 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14583 getCommonDecl(TX->getDecl(), TY->getDecl()));
14584 }
14585 }
14586 llvm_unreachable("Unknown Type Class");
14587}
14588
14590 const Type *Y,
14591 SplitQualType Underlying) {
14592 Type::TypeClass TC = X->getTypeClass();
14593 if (TC != Y->getTypeClass())
14594 return QualType();
14595 switch (TC) {
14596#define UNEXPECTED_TYPE(Class, Kind) \
14597 case Type::Class: \
14598 llvm_unreachable("Unexpected " Kind ": " #Class);
14599#define TYPE(Class, Base)
14600#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14601#include "clang/AST/TypeNodes.inc"
14602
14603#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14606 CANONICAL_TYPE(BlockPointer)
14609 CANONICAL_TYPE(ConstantArray)
14610 CANONICAL_TYPE(ArrayParameter)
14611 CANONICAL_TYPE(ConstantMatrix)
14613 CANONICAL_TYPE(ExtVector)
14614 CANONICAL_TYPE(FunctionNoProto)
14615 CANONICAL_TYPE(FunctionProto)
14616 CANONICAL_TYPE(IncompleteArray)
14617 CANONICAL_TYPE(HLSLAttributedResource)
14618 CANONICAL_TYPE(HLSLInlineSpirv)
14619 CANONICAL_TYPE(LValueReference)
14620 CANONICAL_TYPE(ObjCInterface)
14621 CANONICAL_TYPE(ObjCObject)
14622 CANONICAL_TYPE(ObjCObjectPointer)
14623 CANONICAL_TYPE(OverflowBehavior)
14627 CANONICAL_TYPE(RValueReference)
14628 CANONICAL_TYPE(VariableArray)
14630#undef CANONICAL_TYPE
14631
14632#undef UNEXPECTED_TYPE
14633
14634 case Type::Adjusted: {
14635 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14636 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14637 if (!Ctx.hasSameType(OX, OY))
14638 return QualType();
14639 // FIXME: It's inefficient to have to unify the original types.
14640 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14641 Ctx.getQualifiedType(Underlying));
14642 }
14643 case Type::Decayed: {
14644 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14645 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14646 if (!Ctx.hasSameType(OX, OY))
14647 return QualType();
14648 // FIXME: It's inefficient to have to unify the original types.
14649 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14650 Ctx.getQualifiedType(Underlying));
14651 }
14652 case Type::Attributed: {
14653 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14654 AttributedType::Kind Kind = AX->getAttrKind();
14655 if (Kind != AY->getAttrKind())
14656 return QualType();
14657 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14658 if (!Ctx.hasSameType(MX, MY))
14659 return QualType();
14660 // FIXME: It's inefficient to have to unify the modified types.
14661 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14662 Ctx.getQualifiedType(Underlying),
14663 AX->getAttr());
14664 }
14665 case Type::BTFTagAttributed: {
14666 const auto *BX = cast<BTFTagAttributedType>(X);
14667 const BTFTypeTagAttr *AX = BX->getAttr();
14668 // The attribute is not uniqued, so just compare the tag.
14669 if (AX->getBTFTypeTag() !=
14670 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14671 return QualType();
14672 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14673 }
14674 case Type::Auto: {
14675 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14676
14677 AutoTypeKeyword KW = AX->getKeyword();
14678 if (KW != AY->getKeyword())
14679 return QualType();
14680
14681 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14682 AY->getTypeConstraintConcept());
14684 if (CD &&
14685 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14686 AY->getTypeConstraintArguments())) {
14687 CD = nullptr; // The arguments differ, so make it unconstrained.
14688 As.clear();
14689 }
14690
14691 // Both auto types can't be dependent, otherwise they wouldn't have been
14692 // sugar. This implies they can't contain unexpanded packs either.
14693 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14694 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14695 }
14696 case Type::PackIndexing:
14697 case Type::Decltype:
14698 return QualType();
14699 case Type::DeducedTemplateSpecialization:
14700 // FIXME: Try to merge these.
14701 return QualType();
14702 case Type::MacroQualified: {
14703 const auto *MX = cast<MacroQualifiedType>(X),
14704 *MY = cast<MacroQualifiedType>(Y);
14705 const IdentifierInfo *IX = MX->getMacroIdentifier();
14706 if (IX != MY->getMacroIdentifier())
14707 return QualType();
14708 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14709 }
14710 case Type::SubstTemplateTypeParm: {
14711 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14713 Decl *CD =
14714 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14715 if (!CD)
14716 return QualType();
14717 unsigned Index = SX->getIndex();
14718 if (Index != SY->getIndex())
14719 return QualType();
14720 auto PackIndex = SX->getPackIndex();
14721 if (PackIndex != SY->getPackIndex())
14722 return QualType();
14723 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14724 CD, Index, PackIndex,
14725 SX->getFinal() && SY->getFinal());
14726 }
14727 case Type::ObjCTypeParam:
14728 // FIXME: Try to merge these.
14729 return QualType();
14730 case Type::Paren:
14731 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14732
14733 case Type::TemplateSpecialization: {
14734 const auto *TX = cast<TemplateSpecializationType>(X),
14736 TemplateName CTN =
14737 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14738 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14739 if (!CTN.getAsVoidPointer())
14740 return QualType();
14742 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14743 TY->template_arguments()))
14744 return QualType();
14746 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14747 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14748 }
14749 case Type::Typedef: {
14750 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14751 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14752 if (!CD)
14753 return QualType();
14754 return Ctx.getTypedefType(
14755 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14756 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14757 Ctx.getQualifiedType(Underlying));
14758 }
14759 case Type::TypeOf: {
14760 // The common sugar between two typeof expressions, where one is
14761 // potentially a typeof_unqual and the other is not, we unify to the
14762 // qualified type as that retains the most information along with the type.
14763 // We only return a typeof_unqual type when both types are unqual types.
14768 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14769 }
14770 case Type::TypeOfExpr:
14771 return QualType();
14772
14773 case Type::UnaryTransform: {
14774 const auto *UX = cast<UnaryTransformType>(X),
14775 *UY = cast<UnaryTransformType>(Y);
14776 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14777 if (KX != UY->getUTTKind())
14778 return QualType();
14779 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14780 if (!Ctx.hasSameType(BX, BY))
14781 return QualType();
14782 // FIXME: It's inefficient to have to unify the base types.
14783 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14784 Ctx.getQualifiedType(Underlying), KX);
14785 }
14786 case Type::Using: {
14787 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14788 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14789 if (!CD)
14790 return QualType();
14791 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14792 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14793 CD, Ctx.getQualifiedType(Underlying));
14794 }
14795 case Type::MemberPointer: {
14796 const auto *PX = cast<MemberPointerType>(X),
14797 *PY = cast<MemberPointerType>(Y);
14798 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14799 assert(Cls == PY->getMostRecentCXXRecordDecl());
14800 return Ctx.getMemberPointerType(
14801 ::getCommonPointeeType(Ctx, PX, PY),
14802 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14803 }
14804 case Type::CountAttributed: {
14805 const auto *DX = cast<CountAttributedType>(X),
14807 if (DX->isCountInBytes() != DY->isCountInBytes())
14808 return QualType();
14809 if (DX->isOrNull() != DY->isOrNull())
14810 return QualType();
14811 Expr *CEX = DX->getCountExpr();
14812 Expr *CEY = DY->getCountExpr();
14813 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14814 if (Ctx.hasSameExpr(CEX, CEY))
14815 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14816 DX->isCountInBytes(), DX->isOrNull(),
14817 CDX);
14818 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14819 return QualType();
14820 // Two declarations with the same integer constant may still differ in their
14821 // expression pointers, so we need to evaluate them.
14822 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14823 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14824 if (VX != VY)
14825 return QualType();
14826 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14827 DX->isCountInBytes(), DX->isOrNull(),
14828 CDX);
14829 }
14830 case Type::PredefinedSugar:
14831 assert(cast<PredefinedSugarType>(X)->getKind() !=
14833 return QualType();
14834 }
14835 llvm_unreachable("Unhandled Type Class");
14836}
14837
14838static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14840 while (true) {
14841 QTotal.addConsistentQualifiers(T.Quals);
14843 if (NT == QualType(T.Ty, 0))
14844 break;
14845 R.push_back(T);
14846 T = NT.split();
14847 }
14848 return R;
14849}
14850
14852 bool Unqualified) const {
14853 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14854 if (X == Y)
14855 return X;
14856 if (!Unqualified) {
14857 if (X.isCanonical())
14858 return X;
14859 if (Y.isCanonical())
14860 return Y;
14861 }
14862
14863 SplitQualType SX = X.split(), SY = Y.split();
14864 Qualifiers QX, QY;
14865 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14866 // until we reach their underlying "canonical nodes". Note these are not
14867 // necessarily canonical types, as they may still have sugared properties.
14868 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14869 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14870
14871 // If this is an ArrayType, the element qualifiers are interchangeable with
14872 // the top level qualifiers.
14873 // * In case the canonical nodes are the same, the elements types are already
14874 // the same.
14875 // * Otherwise, the element types will be made the same, and any different
14876 // element qualifiers will be moved up to the top level qualifiers, per
14877 // 'getCommonArrayElementType'.
14878 // In both cases, this means there may be top level qualifiers which differ
14879 // between X and Y. If so, these differing qualifiers are redundant with the
14880 // element qualifiers, and can be removed without changing the canonical type.
14881 // The desired behaviour is the same as for the 'Unqualified' case here:
14882 // treat the redundant qualifiers as sugar, remove the ones which are not
14883 // common to both sides.
14884 bool KeepCommonQualifiers =
14886
14887 if (SX.Ty != SY.Ty) {
14888 // The canonical nodes differ. Build a common canonical node out of the two,
14889 // unifying their sugar. This may recurse back here.
14890 SX.Ty =
14891 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14892 } else {
14893 // The canonical nodes were identical: We may have desugared too much.
14894 // Add any common sugar back in.
14895 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14896 QX -= SX.Quals;
14897 QY -= SY.Quals;
14898 SX = Xs.pop_back_val();
14899 SY = Ys.pop_back_val();
14900 }
14901 }
14902 if (KeepCommonQualifiers)
14904 else
14905 assert(QX == QY);
14906
14907 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14908 // related. Walk up these nodes, unifying them and adding the result.
14909 while (!Xs.empty() && !Ys.empty()) {
14910 auto Underlying = SplitQualType(
14911 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14912 SX = Xs.pop_back_val();
14913 SY = Ys.pop_back_val();
14914 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14916 // Stop at the first pair which is unrelated.
14917 if (!SX.Ty) {
14918 SX.Ty = Underlying.Ty;
14919 break;
14920 }
14921 QX -= Underlying.Quals;
14922 };
14923
14924 // Add back the missing accumulated qualifiers, which were stripped off
14925 // with the sugar nodes we could not unify.
14926 QualType R = getQualifiedType(SX.Ty, QX);
14927 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14928 return R;
14929}
14930
14932 assert(Ty->isFixedPointType());
14933
14935 return Ty;
14936
14937 switch (Ty->castAs<BuiltinType>()->getKind()) {
14938 default:
14939 llvm_unreachable("Not a saturated fixed point type!");
14940 case BuiltinType::SatShortAccum:
14941 return ShortAccumTy;
14942 case BuiltinType::SatAccum:
14943 return AccumTy;
14944 case BuiltinType::SatLongAccum:
14945 return LongAccumTy;
14946 case BuiltinType::SatUShortAccum:
14947 return UnsignedShortAccumTy;
14948 case BuiltinType::SatUAccum:
14949 return UnsignedAccumTy;
14950 case BuiltinType::SatULongAccum:
14951 return UnsignedLongAccumTy;
14952 case BuiltinType::SatShortFract:
14953 return ShortFractTy;
14954 case BuiltinType::SatFract:
14955 return FractTy;
14956 case BuiltinType::SatLongFract:
14957 return LongFractTy;
14958 case BuiltinType::SatUShortFract:
14959 return UnsignedShortFractTy;
14960 case BuiltinType::SatUFract:
14961 return UnsignedFractTy;
14962 case BuiltinType::SatULongFract:
14963 return UnsignedLongFractTy;
14964 }
14965}
14966
14968 assert(Ty->isFixedPointType());
14969
14970 if (Ty->isSaturatedFixedPointType()) return Ty;
14971
14972 switch (Ty->castAs<BuiltinType>()->getKind()) {
14973 default:
14974 llvm_unreachable("Not a fixed point type!");
14975 case BuiltinType::ShortAccum:
14976 return SatShortAccumTy;
14977 case BuiltinType::Accum:
14978 return SatAccumTy;
14979 case BuiltinType::LongAccum:
14980 return SatLongAccumTy;
14981 case BuiltinType::UShortAccum:
14983 case BuiltinType::UAccum:
14984 return SatUnsignedAccumTy;
14985 case BuiltinType::ULongAccum:
14987 case BuiltinType::ShortFract:
14988 return SatShortFractTy;
14989 case BuiltinType::Fract:
14990 return SatFractTy;
14991 case BuiltinType::LongFract:
14992 return SatLongFractTy;
14993 case BuiltinType::UShortFract:
14995 case BuiltinType::UFract:
14996 return SatUnsignedFractTy;
14997 case BuiltinType::ULongFract:
14999 }
15000}
15001
15003 if (LangOpts.OpenCL)
15005
15006 if (LangOpts.CUDA)
15008
15009 return getLangASFromTargetAS(AS);
15010}
15011
15012// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15013// doesn't include ASTContext.h
15014template
15016 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15018 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15019 const clang::ASTContext &Ctx, Decl *Value);
15020
15022 assert(Ty->isFixedPointType());
15023
15024 const TargetInfo &Target = getTargetInfo();
15025 switch (Ty->castAs<BuiltinType>()->getKind()) {
15026 default:
15027 llvm_unreachable("Not a fixed point type!");
15028 case BuiltinType::ShortAccum:
15029 case BuiltinType::SatShortAccum:
15030 return Target.getShortAccumScale();
15031 case BuiltinType::Accum:
15032 case BuiltinType::SatAccum:
15033 return Target.getAccumScale();
15034 case BuiltinType::LongAccum:
15035 case BuiltinType::SatLongAccum:
15036 return Target.getLongAccumScale();
15037 case BuiltinType::UShortAccum:
15038 case BuiltinType::SatUShortAccum:
15039 return Target.getUnsignedShortAccumScale();
15040 case BuiltinType::UAccum:
15041 case BuiltinType::SatUAccum:
15042 return Target.getUnsignedAccumScale();
15043 case BuiltinType::ULongAccum:
15044 case BuiltinType::SatULongAccum:
15045 return Target.getUnsignedLongAccumScale();
15046 case BuiltinType::ShortFract:
15047 case BuiltinType::SatShortFract:
15048 return Target.getShortFractScale();
15049 case BuiltinType::Fract:
15050 case BuiltinType::SatFract:
15051 return Target.getFractScale();
15052 case BuiltinType::LongFract:
15053 case BuiltinType::SatLongFract:
15054 return Target.getLongFractScale();
15055 case BuiltinType::UShortFract:
15056 case BuiltinType::SatUShortFract:
15057 return Target.getUnsignedShortFractScale();
15058 case BuiltinType::UFract:
15059 case BuiltinType::SatUFract:
15060 return Target.getUnsignedFractScale();
15061 case BuiltinType::ULongFract:
15062 case BuiltinType::SatULongFract:
15063 return Target.getUnsignedLongFractScale();
15064 }
15065}
15066
15068 assert(Ty->isFixedPointType());
15069
15070 const TargetInfo &Target = getTargetInfo();
15071 switch (Ty->castAs<BuiltinType>()->getKind()) {
15072 default:
15073 llvm_unreachable("Not a fixed point type!");
15074 case BuiltinType::ShortAccum:
15075 case BuiltinType::SatShortAccum:
15076 return Target.getShortAccumIBits();
15077 case BuiltinType::Accum:
15078 case BuiltinType::SatAccum:
15079 return Target.getAccumIBits();
15080 case BuiltinType::LongAccum:
15081 case BuiltinType::SatLongAccum:
15082 return Target.getLongAccumIBits();
15083 case BuiltinType::UShortAccum:
15084 case BuiltinType::SatUShortAccum:
15085 return Target.getUnsignedShortAccumIBits();
15086 case BuiltinType::UAccum:
15087 case BuiltinType::SatUAccum:
15088 return Target.getUnsignedAccumIBits();
15089 case BuiltinType::ULongAccum:
15090 case BuiltinType::SatULongAccum:
15091 return Target.getUnsignedLongAccumIBits();
15092 case BuiltinType::ShortFract:
15093 case BuiltinType::SatShortFract:
15094 case BuiltinType::Fract:
15095 case BuiltinType::SatFract:
15096 case BuiltinType::LongFract:
15097 case BuiltinType::SatLongFract:
15098 case BuiltinType::UShortFract:
15099 case BuiltinType::SatUShortFract:
15100 case BuiltinType::UFract:
15101 case BuiltinType::SatUFract:
15102 case BuiltinType::ULongFract:
15103 case BuiltinType::SatULongFract:
15104 return 0;
15105 }
15106}
15107
15108llvm::FixedPointSemantics
15110 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15111 "Can only get the fixed point semantics for a "
15112 "fixed point or integer type.");
15113 if (Ty->isIntegerType())
15114 return llvm::FixedPointSemantics::GetIntegerSemantics(
15115 getIntWidth(Ty), Ty->isSignedIntegerType());
15116
15117 bool isSigned = Ty->isSignedFixedPointType();
15118 return llvm::FixedPointSemantics(
15119 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15121 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15122}
15123
15124llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15125 assert(Ty->isFixedPointType());
15126 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15127}
15128
15129llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15130 assert(Ty->isFixedPointType());
15131 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15132}
15133
15135 assert(Ty->isUnsignedFixedPointType() &&
15136 "Expected unsigned fixed point type");
15137
15138 switch (Ty->castAs<BuiltinType>()->getKind()) {
15139 case BuiltinType::UShortAccum:
15140 return ShortAccumTy;
15141 case BuiltinType::UAccum:
15142 return AccumTy;
15143 case BuiltinType::ULongAccum:
15144 return LongAccumTy;
15145 case BuiltinType::SatUShortAccum:
15146 return SatShortAccumTy;
15147 case BuiltinType::SatUAccum:
15148 return SatAccumTy;
15149 case BuiltinType::SatULongAccum:
15150 return SatLongAccumTy;
15151 case BuiltinType::UShortFract:
15152 return ShortFractTy;
15153 case BuiltinType::UFract:
15154 return FractTy;
15155 case BuiltinType::ULongFract:
15156 return LongFractTy;
15157 case BuiltinType::SatUShortFract:
15158 return SatShortFractTy;
15159 case BuiltinType::SatUFract:
15160 return SatFractTy;
15161 case BuiltinType::SatULongFract:
15162 return SatLongFractTy;
15163 default:
15164 llvm_unreachable("Unexpected unsigned fixed point type");
15165 }
15166}
15167
15168// Given a list of FMV features, return a concatenated list of the
15169// corresponding backend features (which may contain duplicates).
15170static std::vector<std::string> getFMVBackendFeaturesFor(
15171 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15172 std::vector<std::string> BackendFeats;
15173 llvm::AArch64::ExtensionSet FeatureBits;
15174 for (StringRef F : FMVFeatStrings)
15175 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15176 if (FMVExt->ID)
15177 FeatureBits.enable(*FMVExt->ID);
15178 FeatureBits.toLLVMFeatureList(BackendFeats);
15179 return BackendFeats;
15180}
15181
15182ParsedTargetAttr
15183ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15184 assert(TD != nullptr);
15185 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15186
15187 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15188 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15189 });
15190 return ParsedAttr;
15191}
15192
15193void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15194 const FunctionDecl *FD) const {
15195 if (FD)
15196 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15197 else
15198 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15199 Target->getTargetOpts().CPU,
15200 Target->getTargetOpts().Features);
15201}
15202
15203// Fills in the supplied string map with the set of target features for the
15204// passed in function.
15205void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15206 GlobalDecl GD) const {
15207 StringRef TargetCPU = Target->getTargetOpts().CPU;
15208 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15209 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15211
15212 // Make a copy of the features as passed on the command line into the
15213 // beginning of the additional features from the function to override.
15214 // AArch64 handles command line option features in parseTargetAttr().
15215 if (!Target->getTriple().isAArch64())
15216 ParsedAttr.Features.insert(
15217 ParsedAttr.Features.begin(),
15218 Target->getTargetOpts().FeaturesAsWritten.begin(),
15219 Target->getTargetOpts().FeaturesAsWritten.end());
15220
15221 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15222 TargetCPU = ParsedAttr.CPU;
15223
15224 // Now populate the feature map, first with the TargetCPU which is either
15225 // the default or a new one from the target attribute string. Then we'll use
15226 // the passed in features (FeaturesAsWritten) along with the new ones from
15227 // the attribute.
15228 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15229 ParsedAttr.Features);
15230 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15232 Target->getCPUSpecificCPUDispatchFeatures(
15233 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15234 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15235 Features.insert(Features.begin(),
15236 Target->getTargetOpts().FeaturesAsWritten.begin(),
15237 Target->getTargetOpts().FeaturesAsWritten.end());
15238 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15239 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15240 if (Target->getTriple().isAArch64()) {
15242 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15243 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15244 Features.insert(Features.begin(),
15245 Target->getTargetOpts().FeaturesAsWritten.begin(),
15246 Target->getTargetOpts().FeaturesAsWritten.end());
15247 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15248 } else if (Target->getTriple().isRISCV()) {
15249 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15250 std::vector<std::string> Features;
15251 if (VersionStr != "default") {
15252 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15253 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15254 ParsedAttr.Features.end());
15255 }
15256 Features.insert(Features.begin(),
15257 Target->getTargetOpts().FeaturesAsWritten.begin(),
15258 Target->getTargetOpts().FeaturesAsWritten.end());
15259 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15260 } else {
15261 std::vector<std::string> Features;
15262 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15263 if (VersionStr.starts_with("arch="))
15264 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15265 else if (VersionStr != "default")
15266 Features.push_back((StringRef{"+"} + VersionStr).str());
15267 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15268 }
15269 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15270 std::vector<std::string> Features;
15271 if (Target->getTriple().isRISCV()) {
15272 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15273 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15274 ParsedAttr.Features.end());
15275 } else {
15276 assert(Target->getTriple().isAArch64());
15278 TV->getFeatures(Feats);
15279 Features = getFMVBackendFeaturesFor(Feats);
15280 }
15281 Features.insert(Features.begin(),
15282 Target->getTargetOpts().FeaturesAsWritten.begin(),
15283 Target->getTargetOpts().FeaturesAsWritten.end());
15284 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15285 } else {
15286 FeatureMap = Target->getTargetOpts().FeatureMap;
15287 }
15288}
15289
15291 CanQualType KernelNameType,
15292 const FunctionDecl *FD) {
15293 // Host and device compilation may use different ABIs and different ABIs
15294 // may allocate name mangling discriminators differently. A discriminator
15295 // override is used to ensure consistent discriminator allocation across
15296 // host and device compilation.
15297 auto DeviceDiscriminatorOverrider =
15298 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15299 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15300 if (RD->isLambda())
15301 return RD->getDeviceLambdaManglingNumber();
15302 return std::nullopt;
15303 };
15304 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15305 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15306
15307 // Construct a mangled name for the SYCL kernel caller offload entry point.
15308 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15309 // name the SYCL kernel caller offload entry point function. This mangling
15310 // does not suffice to clearly identify symbols that correspond to SYCL
15311 // kernel caller functions, nor is this mangling natural for targets that
15312 // use a non-Itanium ABI.
15313 std::string Buffer;
15314 Buffer.reserve(128);
15315 llvm::raw_string_ostream Out(Buffer);
15316 MC->mangleCanonicalTypeName(KernelNameType, Out);
15317 std::string KernelName = Out.str();
15318
15319 return {KernelNameType, FD, KernelName};
15320}
15321
15323 // If the function declaration to register is invalid or dependent, the
15324 // registration attempt is ignored.
15325 if (FD->isInvalidDecl() || FD->isTemplated())
15326 return;
15327
15328 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15329 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15330
15331 // Be tolerant of multiple registration attempts so long as each attempt
15332 // is for the same entity. Callers are obligated to detect and diagnose
15333 // conflicting kernel names prior to calling this function.
15334 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15335 auto IT = SYCLKernels.find(KernelNameType);
15336 assert((IT == SYCLKernels.end() ||
15337 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15338 "SYCL kernel name conflict");
15339 (void)IT;
15340 SYCLKernels.insert(std::make_pair(
15341 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15342}
15343
15345 CanQualType KernelNameType = getCanonicalType(T);
15346 return SYCLKernels.at(KernelNameType);
15347}
15348
15350 CanQualType KernelNameType = getCanonicalType(T);
15351 auto IT = SYCLKernels.find(KernelNameType);
15352 if (IT != SYCLKernels.end())
15353 return &IT->second;
15354 return nullptr;
15355}
15356
15358 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15359 return *OMPTraitInfoVector.back();
15360}
15361
15364 const ASTContext::SectionInfo &Section) {
15365 if (Section.Decl)
15366 return DB << Section.Decl;
15367 return DB << "a prior #pragma section";
15368}
15369
15370bool ASTContext::mayExternalize(const Decl *D) const {
15371 bool IsInternalVar =
15372 isa<VarDecl>(D) &&
15374 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15375 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15376 (D->hasAttr<CUDAConstantAttr>() &&
15377 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15378 // CUDA/HIP: managed variables need to be externalized since it is
15379 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15380 // anonymous name space needs to be externalized to avoid duplicate symbols.
15381 return (IsInternalVar &&
15382 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15383 (D->hasAttr<CUDAGlobalAttr>() &&
15385 GVA_Internal);
15386}
15387
15389 return mayExternalize(D) &&
15390 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15392}
15393
15394StringRef ASTContext::getCUIDHash() const {
15395 if (!CUIDHash.empty())
15396 return CUIDHash;
15397 if (LangOpts.CUID.empty())
15398 return StringRef();
15399 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15400 return CUIDHash;
15401}
15402
15403const CXXRecordDecl *
15405 assert(ThisClass);
15406 assert(ThisClass->isPolymorphic());
15407 const CXXRecordDecl *PrimaryBase = ThisClass;
15408 while (1) {
15409 assert(PrimaryBase);
15410 assert(PrimaryBase->isPolymorphic());
15411 auto &Layout = getASTRecordLayout(PrimaryBase);
15412 auto Base = Layout.getPrimaryBase();
15413 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15414 break;
15415 PrimaryBase = Base;
15416 }
15417 return PrimaryBase;
15418}
15419
15421 StringRef MangledName) {
15422 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15423 assert(Method->isVirtual());
15424 bool DefaultIncludesPointerAuth =
15425 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15426
15427 if (!DefaultIncludesPointerAuth)
15428 return true;
15429
15430 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15431 if (Existing != ThunksToBeAbbreviated.end())
15432 return Existing->second.contains(MangledName.str());
15433
15434 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15435 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15436 auto VtableContext = getVTableContext();
15437 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15438 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15439 for (const auto &Thunk : *ThunkInfos) {
15440 SmallString<256> ElidedName;
15441 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15442 if (Destructor)
15443 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15444 Thunk, /* elideOverrideInfo */ true,
15445 ElidedNameStream);
15446 else
15447 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15448 ElidedNameStream);
15449 SmallString<256> MangledName;
15450 llvm::raw_svector_ostream mangledNameStream(MangledName);
15451 if (Destructor)
15452 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15453 Thunk, /* elideOverrideInfo */ false,
15454 mangledNameStream);
15455 else
15456 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15457 mangledNameStream);
15458
15459 Thunks[ElidedName].push_back(std::string(MangledName));
15460 }
15461 }
15462 llvm::StringSet<> SimplifiedThunkNames;
15463 for (auto &ThunkList : Thunks) {
15464 llvm::sort(ThunkList.second);
15465 SimplifiedThunkNames.insert(ThunkList.second[0]);
15466 }
15467 bool Result = SimplifiedThunkNames.contains(MangledName);
15468 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15469 return Result;
15470}
15471
15473 // Check for trivially-destructible here because non-trivially-destructible
15474 // types will always cause the type and any types derived from it to be
15475 // considered non-trivially-copyable. The same cannot be said for
15476 // trivially-copyable because deleting special members of a type derived from
15477 // a non-trivially-copyable type can cause the derived type to be considered
15478 // trivially copyable.
15479 if (getLangOpts().PointerFieldProtectionTagged)
15480 return !isa<CXXRecordDecl>(RD) ||
15481 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15482 return true;
15483}
15484
15485static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15486 std::vector<PFPField> &Fields, bool IncludeVBases) {
15487 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15488 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15489 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15490 for (unsigned i = 0; i != AT->getSize(); ++i)
15491 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15492 Fields, true);
15493 }
15494 }
15495 auto *Decl = Ty->getAsCXXRecordDecl();
15496 // isPFPType() is inherited from bases and members (including via arrays), so
15497 // we can early exit if it is false. Unions are excluded per the API
15498 // documentation.
15499 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15500 return;
15501 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15502 for (FieldDecl *Field : Decl->fields()) {
15503 CharUnits FieldOffset =
15504 Offset +
15505 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15506 if (Ctx.isPFPField(Field))
15507 Fields.push_back({FieldOffset, Field});
15508 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15509 /*IncludeVBases=*/true);
15510 }
15511 // Pass false for IncludeVBases below because vbases are only included in
15512 // layout for top-level types, i.e. not bases or vbases.
15513 for (CXXBaseSpecifier &Base : Decl->bases()) {
15514 if (Base.isVirtual())
15515 continue;
15516 CharUnits BaseOffset =
15517 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15518 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15519 /*IncludeVBases=*/false);
15520 }
15521 if (IncludeVBases) {
15522 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15523 CharUnits BaseOffset =
15524 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15525 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15526 /*IncludeVBases=*/false);
15527 }
15528 }
15529}
15530
15531std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15532 std::vector<PFPField> PFPFields;
15533 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15534 return PFPFields;
15535}
15536
15538 return !findPFPFields(Ty).empty();
15539}
15540
15541bool ASTContext::isPFPField(const FieldDecl *FD) const {
15542 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15543 return RD->isPFPType() && FD->getType()->isPointerType() &&
15544 !FD->hasAttr<NoFieldProtectionAttr>();
15545 return false;
15546}
15547
15549 auto *FD = dyn_cast<FieldDecl>(VD);
15550 if (!FD)
15551 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15552 if (isPFPField(FD))
15554}
15555
15557 if (E->getNumComponents() == 0)
15558 return;
15559 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15560 if (Comp.getKind() != OffsetOfNode::Field)
15561 return;
15562 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15564}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static 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:473
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:2839
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
*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:801
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType 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:802
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 classNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
void setClassNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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:797
Builtin::Context & BuiltinInfo
Definition ASTContext.h:799
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:951
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:798
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:986
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:917
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:581
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:800
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:989
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h: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:803
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:850
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:573
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:995
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:871
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 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:916
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
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
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.
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:3497
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3518
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:3900
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3730
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3744
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3748
QualType getElementType() const
Definition TypeBase.h:3742
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3752
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:8192
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8240
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8257
unsigned getNumBits() const
Definition TypeBase.h:8252
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4674
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Pointer to a block type.
Definition TypeBase.h:3550
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3567
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:3172
Kind getKind() const
Definition TypeBase.h:3220
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:2611
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
CXXDestructorDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isVirtual() const
Definition DeclCXX.h:2191
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2232
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
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2131
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:3283
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3298
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:3768
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3864
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3824
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3883
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3844
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4395
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4414
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4460
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4411
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3444
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3480
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3533
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h: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:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:560
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp: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:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h: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:4069
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4091
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8285
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4019
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4048
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4109
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4134
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4481
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4501
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:6260
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6265
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4235
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4260
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4013
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4231
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4245
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4129
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4186
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:4211
@ 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:4050
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:4275
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:5549
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:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4753
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3245
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
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:4701
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:2000
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2689
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3892
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3748
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:4418
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2410
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:4079
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5283
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5714
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5752
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5115
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5149
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4893
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4909
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5819
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5622
unsigned getNumParams() const
Definition TypeBase.h:5593
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4024
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5628
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5788
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5784
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4622
CallingConv getCC() const
Definition TypeBase.h:4681
unsigned getRegParm() const
Definition TypeBase.h:4674
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4670
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4693
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4537
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4577
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
ExtInfo getExtInfo() const
Definition TypeBase.h:4867
QualType getReturnType() const
Definition TypeBase.h:4851
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:5055
Represents a C array with an unspecified size.
Definition TypeBase.h:3917
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3934
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3625
@ 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:4401
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4438
MSGuidDeclParts Parts
Definition DeclCXX.h:4403
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6194
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4366
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4359
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3661
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3704
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h: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:3332
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
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:7950
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:952
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:8006
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8087
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:959
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8081
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8163
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8043
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8064
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8018
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8058
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1853
qual_range quals() const
Definition TypeBase.h:8125
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8070
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:4364
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3310
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3324
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:1790
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
QualType getOriginalType() const
Definition Decl.cpp:2967
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8223
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:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3351
PredefinedSugarKind Kind
Definition TypeBase.h:8299
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:8472
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2911
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8519
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8477
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:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
QualType getCanonicalType() const
Definition TypeBase.h:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8409
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3617
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
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:8445
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8392
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:3051
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8420
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:8328
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8335
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:3643
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:4327
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5247
bool hasFlexibleArrayMember() const
Definition Decl.h:4360
field_range fields() const
Definition Decl.h:4530
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5233
RecordDecl * getMostRecentDecl()
Definition Decl.h:4353
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5292
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4511
bool field_empty() const
Definition Decl.h:4538
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:3581
QualType getPointeeType() const
Definition TypeBase.h:3599
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3607
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:3717
TagTypeKind TagKind
Definition Decl.h:3722
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3954
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4907
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4900
bool isUnion() const
Definition Decl.h:3928
TagKind getTagKind() const
Definition Decl.h:3917
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:326
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:858
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:751
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:333
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:342
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:347
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:356
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:335
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:338
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:351
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:505
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:407
IntType getSizeType() const
Definition TargetInfo.h:388
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:975
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:759
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:389
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h: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:3513
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:6226
A container of type source information.
Definition TypeBase.h:8359
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:1839
bool isBlockPointerType() const
Definition TypeBase.h:8645
bool isVoidType() const
Definition TypeBase.h:8991
bool isObjCBuiltinType() const
Definition TypeBase.h:8855
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2721
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2230
bool isFloat16Type() const
Definition TypeBase.h:9000
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:8728
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:2469
bool isArrayType() const
Definition TypeBase.h:8724
bool isCharType() const
Definition Type.cpp:2157
QualType getLocallyUnqualifiedSingleStepDesugaredType() const
Pull a single level of sugar off of this locally-unqualified type.
Definition Type.cpp:522
bool isPointerType() const
Definition TypeBase.h:8625
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8740
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
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:9079
bool isEnumeralType() const
Definition TypeBase.h:8756
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8825
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9113
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2907
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2798
bool isBitIntType() const
Definition TypeBase.h:8900
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8748
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9051
bool isHalfType() const
Definition TypeBase.h:8995
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9067
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3127
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2287
@ SizeT
The "size_t" type.
Definition TypeBase.h:2281
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2284
bool isObjCIdType() const
Definition TypeBase.h:8837
bool isOverflowBehaviorType() const
Definition TypeBase.h:8796
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:9075
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9271
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:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
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:9093
bool isVectorType() const
Definition TypeBase.h:8764
bool isObjCClassType() const
Definition TypeBase.h:8843
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2703
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2638
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2929
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:2284
bool isAnyPointerType() const
Definition TypeBase.h:8633
TypeClass getTypeClass() const
Definition TypeBase.h:2391
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2417
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
bool isObjCRetainableType() const
Definition Type.cpp:5364
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5094
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5762
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
QualType getUnderlyingType() const
Definition Decl.h:3617
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6170
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:4458
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4486
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6031
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6068
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4040
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4105
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3795
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3466
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3445
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6108
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:5582
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:2822
bool hasInit() const
Definition Decl.cpp:2410
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:2473
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
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:1551
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2387
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:2791
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3974
Expr * getSizeExpr() const
Definition TypeBase.h:3988
Represents a GCC generic vector type.
Definition TypeBase.h:4183
unsigned getNumElements() const
Definition TypeBase.h:4198
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4207
VectorKind getVectorKind() const
Definition TypeBase.h:4203
QualType getElementType() const
Definition TypeBase.h:4197
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:42
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:1798
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8523
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
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:3727
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5944
@ Struct
The "struct" keyword.
Definition TypeBase.h:5941
@ Class
The "class" keyword.
Definition TypeBase.h:5950
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.
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4153
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4162
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4150
@ Generic
not a target-specific vector type
Definition TypeBase.h:4144
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4168
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4171
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4165
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:5914
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5919
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5935
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5916
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5925
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5922
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5928
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5932
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:5372
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5374
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5377
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5380
Extra information about a function prototype.
Definition TypeBase.h:5400
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5446
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5405
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5450
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5439
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:3327
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h: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