Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
55#include "clang/Basic/LLVM.h"
57#include "clang/Basic/Linkage.h"
58#include "clang/Basic/Module.h"
68#include "llvm/ADT/APFixedPoint.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/APSInt.h"
71#include "llvm/ADT/ArrayRef.h"
72#include "llvm/ADT/DenseMap.h"
73#include "llvm/ADT/DenseSet.h"
74#include "llvm/ADT/FoldingSet.h"
75#include "llvm/ADT/PointerUnion.h"
76#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/SmallVector.h"
79#include "llvm/ADT/StringExtras.h"
80#include "llvm/ADT/StringRef.h"
81#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
82#include "llvm/Support/Capacity.h"
83#include "llvm/Support/Casting.h"
84#include "llvm/Support/Compiler.h"
85#include "llvm/Support/ErrorHandling.h"
86#include "llvm/Support/MD5.h"
87#include "llvm/Support/MathExtras.h"
88#include "llvm/Support/SipHash.h"
89#include "llvm/Support/raw_ostream.h"
90#include "llvm/TargetParser/AArch64TargetParser.h"
91#include "llvm/TargetParser/Triple.h"
92#include <algorithm>
93#include <cassert>
94#include <cstddef>
95#include <cstdint>
96#include <cstdlib>
97#include <map>
98#include <memory>
99#include <optional>
100#include <string>
101#include <tuple>
102#include <utility>
103
104using namespace clang;
105
116
117/// \returns The locations that are relevant when searching for Doc comments
118/// related to \p D.
121 assert(D);
122
123 // User can not attach documentation to implicit declarations.
124 if (D->isImplicit())
125 return {};
126
127 // User can not attach documentation to implicit instantiations.
128 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
129 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
130 return {};
131 }
132
133 if (const auto *VD = dyn_cast<VarDecl>(D)) {
134 if (VD->isStaticDataMember() &&
135 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136 return {};
137 }
138
139 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
140 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
141 return {};
142 }
143
144 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
145 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
146 if (TSK == TSK_ImplicitInstantiation ||
147 TSK == TSK_Undeclared)
148 return {};
149 }
150
151 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
152 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
153 return {};
154 }
155 if (const auto *TD = dyn_cast<TagDecl>(D)) {
156 // When tag declaration (but not definition!) is part of the
157 // decl-specifier-seq of some other declaration, it doesn't get comment
158 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
159 return {};
160 }
161 // TODO: handle comments for function parameters properly.
162 if (isa<ParmVarDecl>(D))
163 return {};
164
165 // TODO: we could look up template parameter documentation in the template
166 // documentation.
170 return {};
171
173 // Find declaration location.
174 // For Objective-C declarations we generally don't expect to have multiple
175 // declarators, thus use declaration starting location as the "declaration
176 // location".
177 // For all other declarations multiple declarators are used quite frequently,
178 // so we use the location of the identifier as the "declaration location".
179 SourceLocation BaseLocation;
183 // Allow association with Y across {} in `typedef struct X {} Y`.
185 BaseLocation = D->getBeginLoc();
186 else
187 BaseLocation = D->getLocation();
188
189 if (!D->getLocation().isMacroID()) {
190 Locations.emplace_back(BaseLocation);
191 } else {
192 const auto *DeclCtx = D->getDeclContext();
193
194 // When encountering definitions generated from a macro (that are not
195 // contained by another declaration in the macro) we need to try and find
196 // the comment at the location of the expansion but if there is no comment
197 // there we should retry to see if there is a comment inside the macro as
198 // well. To this end we return first BaseLocation to first look at the
199 // expansion site, the second value is the spelling location of the
200 // beginning of the declaration defined inside the macro.
201 if (!(DeclCtx &&
202 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
203 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
204 }
205
206 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
207 // we don't refer to the macro argument location at the expansion site (this
208 // can happen if the name's spelling is provided via macro argument), and
209 // always to the declaration itself.
210 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
211 }
212
213 return Locations;
214}
215
217 const Decl *D, const SourceLocation RepresentativeLocForDecl,
218 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
219 // If the declaration doesn't map directly to a location in a file, we
220 // can't find the comment.
221 if (RepresentativeLocForDecl.isInvalid() ||
222 !RepresentativeLocForDecl.isFileID())
223 return nullptr;
224
225 // If there are no comments anywhere, we won't find anything.
226 if (CommentsInTheFile.empty())
227 return nullptr;
228
229 // Decompose the location for the declaration and find the beginning of the
230 // file buffer.
231 const FileIDAndOffset DeclLocDecomp =
232 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
233
234 // Slow path.
235 auto OffsetCommentBehindDecl =
236 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
237
238 // First check whether we have a trailing comment.
239 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
240 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
241 if ((CommentBehindDecl->isDocumentation() ||
242 LangOpts.CommentOpts.ParseAllComments) &&
243 CommentBehindDecl->isTrailingComment() &&
246
247 // Check that Doxygen trailing comment comes after the declaration, starts
248 // on the same line and in the same file as the declaration.
249 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
250 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
251 OffsetCommentBehindDecl->first)) {
252 return CommentBehindDecl;
253 }
254 }
255 }
256
257 // The comment just after the declaration was not a trailing comment.
258 // Let's look at the previous comment.
259 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
260 return nullptr;
261
262 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
263 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
264
265 // Check that we actually have a non-member Doxygen comment.
266 if (!(CommentBeforeDecl->isDocumentation() ||
267 LangOpts.CommentOpts.ParseAllComments) ||
268 CommentBeforeDecl->isTrailingComment())
269 return nullptr;
270
271 // Decompose the end of the comment.
272 const unsigned CommentEndOffset =
273 Comments.getCommentEndOffset(CommentBeforeDecl);
274
275 // Get the corresponding buffer.
276 bool Invalid = false;
277 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
278 &Invalid).data();
279 if (Invalid)
280 return nullptr;
281
282 // Extract text between the comment and declaration.
283 StringRef Text(Buffer + CommentEndOffset,
284 DeclLocDecomp.second - CommentEndOffset);
285
286 // There should be no other declarations or preprocessor directives between
287 // comment and declaration.
288 if (Text.find_last_of(";{}#@") != StringRef::npos)
289 return nullptr;
290
291 return CommentBeforeDecl;
292}
293
295 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
296
297 for (const auto DeclLoc : DeclLocs) {
298 // If the declaration doesn't map directly to a location in a file, we
299 // can't find the comment.
300 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
301 continue;
302
304 ExternalSource->ReadComments();
305 CommentsLoaded = true;
306 }
307
308 if (Comments.empty())
309 continue;
310
311 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
312 if (!File.isValid())
313 continue;
314
315 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
316 if (!CommentsInThisFile || CommentsInThisFile->empty())
317 continue;
318
319 if (RawComment *Comment =
320 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile))
321 return Comment;
322 }
323
324 return nullptr;
325}
326
328 assert(LangOpts.RetainCommentsFromSystemHeaders ||
329 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
330 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
331}
332
334 const Decl *D,
335 const Decl **OriginalDecl) const {
336 if (!D) {
337 if (OriginalDecl)
338 OriginalDecl = nullptr;
339 return nullptr;
340 }
341
342 D = &adjustDeclToTemplate(*D);
343
344 // Any comment directly attached to D?
345 {
346 auto DeclComment = DeclRawComments.find(D);
347 if (DeclComment != DeclRawComments.end()) {
348 if (OriginalDecl)
349 *OriginalDecl = D;
350 return DeclComment->second;
351 }
352 }
353
354 // Any comment attached to any redeclaration of D?
355 const Decl *CanonicalD = D->getCanonicalDecl();
356 if (!CanonicalD)
357 return nullptr;
358
359 {
360 auto RedeclComment = RedeclChainComments.find(CanonicalD);
361 if (RedeclComment != RedeclChainComments.end()) {
362 if (OriginalDecl)
363 *OriginalDecl = RedeclComment->second;
364 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
365 assert(CommentAtRedecl != DeclRawComments.end() &&
366 "This decl is supposed to have comment attached.");
367 return CommentAtRedecl->second;
368 }
369 }
370
371 // Any redeclarations of D that we haven't checked for comments yet?
372 const Decl *LastCheckedRedecl = [&]() {
373 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
374 bool CanUseCommentlessCache = false;
375 if (LastChecked) {
376 for (auto *Redecl : CanonicalD->redecls()) {
377 if (Redecl == D) {
378 CanUseCommentlessCache = true;
379 break;
380 }
381 if (Redecl == LastChecked)
382 break;
383 }
384 }
385 // FIXME: This could be improved so that even if CanUseCommentlessCache
386 // is false, once we've traversed past CanonicalD we still skip ahead
387 // LastChecked.
388 return CanUseCommentlessCache ? LastChecked : nullptr;
389 }();
390
391 for (const Decl *Redecl : D->redecls()) {
392 assert(Redecl);
393 // Skip all redeclarations that have been checked previously.
394 if (LastCheckedRedecl) {
395 if (LastCheckedRedecl == Redecl) {
396 LastCheckedRedecl = nullptr;
397 }
398 continue;
399 }
400 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
401 if (RedeclComment) {
402 cacheRawCommentForDecl(*Redecl, *RedeclComment);
403 if (OriginalDecl)
404 *OriginalDecl = Redecl;
405 return RedeclComment;
406 }
407 CommentlessRedeclChains[CanonicalD] = Redecl;
408 }
409
410 if (OriginalDecl)
411 *OriginalDecl = nullptr;
412 return nullptr;
413}
414
416 const RawComment &Comment) const {
417 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
418 DeclRawComments.try_emplace(&OriginalD, &Comment);
419 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
420 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
421 CommentlessRedeclChains.erase(CanonicalDecl);
422}
423
424static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
426 const DeclContext *DC = ObjCMethod->getDeclContext();
427 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
428 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
429 if (!ID)
430 return;
431 // Add redeclared method here.
432 for (const auto *Ext : ID->known_extensions()) {
433 if (ObjCMethodDecl *RedeclaredMethod =
434 Ext->getMethod(ObjCMethod->getSelector(),
435 ObjCMethod->isInstanceMethod()))
436 Redeclared.push_back(RedeclaredMethod);
437 }
438 }
439}
440
442 const Preprocessor *PP) {
443 if (Comments.empty() || Decls.empty())
444 return;
445
446 FileID File;
447 for (const Decl *D : Decls) {
448 if (D->isInvalidDecl())
449 continue;
450
451 D = &adjustDeclToTemplate(*D);
452 SourceLocation Loc = D->getLocation();
453 if (Loc.isValid()) {
454 // See if there are any new comments that are not attached to a decl.
455 // The location doesn't have to be precise - we care only about the file.
456 File = SourceMgr.getDecomposedLoc(Loc).first;
457 break;
458 }
459 }
460
461 if (File.isInvalid())
462 return;
463
464 auto CommentsInThisFile = Comments.getCommentsInFile(File);
465 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
466 CommentsInThisFile->rbegin()->second->isAttached())
467 return;
468
469 // There is at least one comment not attached to a decl.
470 // Maybe it should be attached to one of Decls?
471 //
472 // Note that this way we pick up not only comments that precede the
473 // declaration, but also comments that *follow* the declaration -- thanks to
474 // the lookahead in the lexer: we've consumed the semicolon and looked
475 // ahead through comments.
476 for (const Decl *D : Decls) {
477 assert(D);
478 if (D->isInvalidDecl())
479 continue;
480
481 D = &adjustDeclToTemplate(*D);
482
483 if (DeclRawComments.count(D) > 0)
484 continue;
485
486 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
487
488 for (const auto DeclLoc : DeclLocs) {
489 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
490 continue;
491
492 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
493 D, DeclLoc, *CommentsInThisFile)) {
494 cacheRawCommentForDecl(*D, *DocComment);
495 comments::FullComment *FC = DocComment->parse(*this, PP, D);
496 ParsedComments[D->getCanonicalDecl()] = FC;
497 break;
498 }
499 }
500 }
501}
502
504 const Decl *D) const {
505 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
506 ThisDeclInfo->CommentDecl = D;
507 ThisDeclInfo->IsFilled = false;
508 ThisDeclInfo->fill();
509 ThisDeclInfo->CommentDecl = FC->getDecl();
510 if (!ThisDeclInfo->TemplateParameters)
511 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
513 new (*this) comments::FullComment(FC->getBlocks(),
514 ThisDeclInfo);
515 return CFC;
516}
517
520 return RC ? RC->parse(*this, nullptr, D) : nullptr;
521}
522
524 const Decl *D,
525 const Preprocessor *PP) const {
526 if (!D || D->isInvalidDecl())
527 return nullptr;
528 D = &adjustDeclToTemplate(*D);
529
530 const Decl *Canonical = D->getCanonicalDecl();
531 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
532 ParsedComments.find(Canonical);
533
534 if (Pos != ParsedComments.end()) {
535 if (Canonical != D) {
536 comments::FullComment *FC = Pos->second;
538 return CFC;
539 }
540 return Pos->second;
541 }
542
543 const Decl *OriginalDecl = nullptr;
544
545 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
546 if (!RC) {
549 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
550 if (OMD && OMD->isPropertyAccessor())
551 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
552 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
553 return cloneFullComment(FC, D);
554 if (OMD)
555 addRedeclaredMethods(OMD, Overridden);
556 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
557 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
558 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
559 return cloneFullComment(FC, D);
560 }
561 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
562 // Attach any tag type's documentation to its typedef if latter
563 // does not have one of its own.
564 QualType QT = TD->getUnderlyingType();
565 if (const auto *TT = QT->getAs<TagType>())
566 if (comments::FullComment *FC =
567 getCommentForDecl(TT->getOriginalDecl(), 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)) {
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/// Check if a type can have its sanitizer instrumentation elided based on its
786/// presence within an ignorelist.
788 const QualType &Ty) const {
789 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
790 return NoSanitizeL->containsType(Mask, TyName);
791}
792
794 auto Kind = getTargetInfo().getCXXABI().getKind();
795 return getLangOpts().CXXABI.value_or(Kind);
796}
797
798CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
799 if (!LangOpts.CPlusPlus) return nullptr;
800
801 switch (getCXXABIKind()) {
802 case TargetCXXABI::AppleARM64:
803 case TargetCXXABI::Fuchsia:
804 case TargetCXXABI::GenericARM: // Same as Itanium at this level
805 case TargetCXXABI::iOS:
806 case TargetCXXABI::WatchOS:
807 case TargetCXXABI::GenericAArch64:
808 case TargetCXXABI::GenericMIPS:
809 case TargetCXXABI::GenericItanium:
810 case TargetCXXABI::WebAssembly:
811 case TargetCXXABI::XL:
812 return CreateItaniumCXXABI(*this);
813 case TargetCXXABI::Microsoft:
814 return CreateMicrosoftCXXABI(*this);
815 }
816 llvm_unreachable("Invalid CXXABI type!");
817}
818
820 if (!InterpContext) {
821 InterpContext.reset(new interp::Context(*this));
822 }
823 return *InterpContext;
824}
825
827 if (!ParentMapCtx)
828 ParentMapCtx.reset(new ParentMapContext(*this));
829 return *ParentMapCtx;
830}
831
833 const LangOptions &LangOpts) {
834 switch (LangOpts.getAddressSpaceMapMangling()) {
836 return TI.useAddressSpaceMapMangling();
838 return true;
840 return false;
841 }
842 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
843}
844
846 IdentifierTable &idents, SelectorTable &sels,
848 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
849 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
850 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
851 DependentSizedMatrixTypes(this_()),
852 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
853 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
854 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
855 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
856 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
857 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
858 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
859 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
860 LangOpts.XRayNeverInstrumentFiles,
861 LangOpts.XRayAttrListFiles, SM)),
862 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
863 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
864 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
865 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
866 CompCategories(this_()), LastSDM(nullptr, 0) {
868}
869
871 // Release the DenseMaps associated with DeclContext objects.
872 // FIXME: Is this the ideal solution?
873 ReleaseDeclContextMaps();
874
875 // Call all of the deallocation functions on all of their targets.
876 for (auto &Pair : Deallocations)
877 (Pair.first)(Pair.second);
878 Deallocations.clear();
879
880 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
881 // because they can contain DenseMaps.
882 for (llvm::DenseMap<const ObjCInterfaceDecl *,
884 I = ObjCLayouts.begin(),
885 E = ObjCLayouts.end();
886 I != E;)
887 // Increment in loop to prevent using deallocated memory.
888 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
889 R->Destroy(*this);
890 ObjCLayouts.clear();
891
892 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
893 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
894 // Increment in loop to prevent using deallocated memory.
895 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
896 R->Destroy(*this);
897 }
898 ASTRecordLayouts.clear();
899
900 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
901 AEnd = DeclAttrs.end();
902 A != AEnd; ++A)
903 A->second->~AttrVec();
904 DeclAttrs.clear();
905
906 for (const auto &Value : ModuleInitializers)
907 Value.second->~PerModuleInitializers();
908 ModuleInitializers.clear();
909
910 XRayFilter.reset();
911 NoSanitizeL.reset();
912}
913
915
916void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
917 TraversalScope = TopLevelDecls;
919}
920
921void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
922 Deallocations.push_back({Callback, Data});
923}
924
925void
929
931 llvm::errs() << "\n*** AST Context Stats:\n";
932 llvm::errs() << " " << Types.size() << " types total.\n";
933
934 unsigned counts[] = {
935#define TYPE(Name, Parent) 0,
936#define ABSTRACT_TYPE(Name, Parent)
937#include "clang/AST/TypeNodes.inc"
938 0 // Extra
939 };
940
941 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
942 Type *T = Types[i];
943 counts[(unsigned)T->getTypeClass()]++;
944 }
945
946 unsigned Idx = 0;
947 unsigned TotalBytes = 0;
948#define TYPE(Name, Parent) \
949 if (counts[Idx]) \
950 llvm::errs() << " " << counts[Idx] << " " << #Name \
951 << " types, " << sizeof(Name##Type) << " each " \
952 << "(" << counts[Idx] * sizeof(Name##Type) \
953 << " bytes)\n"; \
954 TotalBytes += counts[Idx] * sizeof(Name##Type); \
955 ++Idx;
956#define ABSTRACT_TYPE(Name, Parent)
957#include "clang/AST/TypeNodes.inc"
958
959 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
960
961 // Implicit special member functions.
962 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
964 << " implicit default constructors created\n";
965 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
967 << " implicit copy constructors created\n";
969 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
971 << " implicit move constructors created\n";
972 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
974 << " implicit copy assignment operators created\n";
976 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
978 << " implicit move assignment operators created\n";
979 llvm::errs() << NumImplicitDestructorsDeclared << "/"
981 << " implicit destructors created\n";
982
983 if (ExternalSource) {
984 llvm::errs() << "\n";
985 ExternalSource->PrintStats();
986 }
987
988 BumpAlloc.PrintStats();
989}
990
992 bool NotifyListeners) {
993 if (NotifyListeners)
994 if (auto *Listener = getASTMutationListener();
996 Listener->RedefinedHiddenDefinition(ND, M);
997
998 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
999}
1000
1002 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1003 if (It == MergedDefModules.end())
1004 return;
1005
1006 auto &Merged = It->second;
1007 llvm::DenseSet<Module*> Found;
1008 for (Module *&M : Merged)
1009 if (!Found.insert(M).second)
1010 M = nullptr;
1011 llvm::erase(Merged, nullptr);
1012}
1013
1016 auto MergedIt =
1017 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1018 if (MergedIt == MergedDefModules.end())
1019 return {};
1020 return MergedIt->second;
1021}
1022
1023void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1024 if (LazyInitializers.empty())
1025 return;
1026
1027 auto *Source = Ctx.getExternalSource();
1028 assert(Source && "lazy initializers but no external source");
1029
1030 auto LazyInits = std::move(LazyInitializers);
1031 LazyInitializers.clear();
1032
1033 for (auto ID : LazyInits)
1034 Initializers.push_back(Source->GetExternalDecl(ID));
1035
1036 assert(LazyInitializers.empty() &&
1037 "GetExternalDecl for lazy module initializer added more inits");
1038}
1039
1041 // One special case: if we add a module initializer that imports another
1042 // module, and that module's only initializer is an ImportDecl, simplify.
1043 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1044 auto It = ModuleInitializers.find(ID->getImportedModule());
1045
1046 // Maybe the ImportDecl does nothing at all. (Common case.)
1047 if (It == ModuleInitializers.end())
1048 return;
1049
1050 // Maybe the ImportDecl only imports another ImportDecl.
1051 auto &Imported = *It->second;
1052 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1053 Imported.resolve(*this);
1054 auto *OnlyDecl = Imported.Initializers.front();
1055 if (isa<ImportDecl>(OnlyDecl))
1056 D = OnlyDecl;
1057 }
1058 }
1059
1060 auto *&Inits = ModuleInitializers[M];
1061 if (!Inits)
1062 Inits = new (*this) PerModuleInitializers;
1063 Inits->Initializers.push_back(D);
1064}
1065
1068 auto *&Inits = ModuleInitializers[M];
1069 if (!Inits)
1070 Inits = new (*this) PerModuleInitializers;
1071 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1072 IDs.begin(), IDs.end());
1073}
1074
1076 auto It = ModuleInitializers.find(M);
1077 if (It == ModuleInitializers.end())
1078 return {};
1079
1080 auto *Inits = It->second;
1081 Inits->resolve(*this);
1082 return Inits->Initializers;
1083}
1084
1086 assert(M->isNamedModule());
1087 assert(!CurrentCXXNamedModule &&
1088 "We should set named module for ASTContext for only once");
1089 CurrentCXXNamedModule = M;
1090}
1091
1092bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1093 if (!M1 != !M2)
1094 return false;
1095
1096 /// Get the representative module for M. The representative module is the
1097 /// first module unit for a specific primary module name. So that the module
1098 /// units have the same representative module belongs to the same module.
1099 ///
1100 /// The process is helpful to reduce the expensive string operations.
1101 auto GetRepresentativeModule = [this](const Module *M) {
1102 auto Iter = SameModuleLookupSet.find(M);
1103 if (Iter != SameModuleLookupSet.end())
1104 return Iter->second;
1105
1106 const Module *RepresentativeModule =
1107 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1108 .first->second;
1109 SameModuleLookupSet[M] = RepresentativeModule;
1110 return RepresentativeModule;
1111 };
1112
1113 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1114 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1115}
1116
1118 if (!ExternCContext)
1119 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1120
1121 return ExternCContext;
1122}
1123
1134
1135#define BuiltinTemplate(BTName) \
1136 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1137 if (!Decl##BTName) \
1138 Decl##BTName = \
1139 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1140 return Decl##BTName; \
1141 }
1142#include "clang/Basic/BuiltinTemplates.inc"
1143
1145 RecordDecl::TagKind TK) const {
1146 SourceLocation Loc;
1147 RecordDecl *NewDecl;
1148 if (getLangOpts().CPlusPlus)
1149 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1150 Loc, &Idents.get(Name));
1151 else
1152 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1153 &Idents.get(Name));
1154 NewDecl->setImplicit();
1155 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1156 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1157 return NewDecl;
1158}
1159
1161 StringRef Name) const {
1164 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1165 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1166 NewDecl->setImplicit();
1167 return NewDecl;
1168}
1169
1171 if (!Int128Decl)
1172 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1173 return Int128Decl;
1174}
1175
1177 if (!UInt128Decl)
1178 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1179 return UInt128Decl;
1180}
1181
1182void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1183 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1185 Types.push_back(Ty);
1186}
1187
1189 const TargetInfo *AuxTarget) {
1190 assert((!this->Target || this->Target == &Target) &&
1191 "Incorrect target reinitialization");
1192 assert(VoidTy.isNull() && "Context reinitialized?");
1193
1194 this->Target = &Target;
1195 this->AuxTarget = AuxTarget;
1196
1197 ABI.reset(createCXXABI(Target));
1198 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1199
1200 // C99 6.2.5p19.
1201 InitBuiltinType(VoidTy, BuiltinType::Void);
1202
1203 // C99 6.2.5p2.
1204 InitBuiltinType(BoolTy, BuiltinType::Bool);
1205 // C99 6.2.5p3.
1206 if (LangOpts.CharIsSigned)
1207 InitBuiltinType(CharTy, BuiltinType::Char_S);
1208 else
1209 InitBuiltinType(CharTy, BuiltinType::Char_U);
1210 // C99 6.2.5p4.
1211 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1212 InitBuiltinType(ShortTy, BuiltinType::Short);
1213 InitBuiltinType(IntTy, BuiltinType::Int);
1214 InitBuiltinType(LongTy, BuiltinType::Long);
1215 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1216
1217 // C99 6.2.5p6.
1218 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1219 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1220 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1221 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1222 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1223
1224 // C99 6.2.5p10.
1225 InitBuiltinType(FloatTy, BuiltinType::Float);
1226 InitBuiltinType(DoubleTy, BuiltinType::Double);
1227 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1228
1229 // GNU extension, __float128 for IEEE quadruple precision
1230 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1231
1232 // __ibm128 for IBM extended precision
1233 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1234
1235 // C11 extension ISO/IEC TS 18661-3
1236 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1237
1238 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1239 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1240 InitBuiltinType(AccumTy, BuiltinType::Accum);
1241 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1242 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1243 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1244 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1245 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1246 InitBuiltinType(FractTy, BuiltinType::Fract);
1247 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1248 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1249 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1250 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1251 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1252 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1253 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1254 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1255 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1256 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1257 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1258 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1259 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1260 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1261 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1262 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1263
1264 // GNU extension, 128-bit integers.
1265 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1266 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1267
1268 // C++ 3.9.1p5
1269 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1270 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1271 else // -fshort-wchar makes wchar_t be unsigned.
1272 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1273 if (LangOpts.CPlusPlus && LangOpts.WChar)
1275 else {
1276 // C99 (or C++ using -fno-wchar).
1277 WideCharTy = getFromTargetType(Target.getWCharType());
1278 }
1279
1280 WIntTy = getFromTargetType(Target.getWIntType());
1281
1282 // C++20 (proposed)
1283 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1284
1285 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1286 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1287 else // C99
1288 Char16Ty = getFromTargetType(Target.getChar16Type());
1289
1290 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1291 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1292 else // C99
1293 Char32Ty = getFromTargetType(Target.getChar32Type());
1294
1295 // Placeholder type for type-dependent expressions whose type is
1296 // completely unknown. No code should ever check a type against
1297 // DependentTy and users should never see it; however, it is here to
1298 // help diagnose failures to properly check for type-dependent
1299 // expressions.
1300 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1301
1302 // Placeholder type for functions.
1303 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1304
1305 // Placeholder type for bound members.
1306 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1307
1308 // Placeholder type for unresolved templates.
1309 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1310
1311 // Placeholder type for pseudo-objects.
1312 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1313
1314 // "any" type; useful for debugger-like clients.
1315 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1316
1317 // Placeholder type for unbridged ARC casts.
1318 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1319
1320 // Placeholder type for builtin functions.
1321 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1322
1323 // Placeholder type for OMP array sections.
1324 if (LangOpts.OpenMP) {
1325 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1326 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1327 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1328 }
1329 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1330 // don't bother, as we're just using the same type as OMP.
1331 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1332 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1333 }
1334 if (LangOpts.MatrixTypes)
1335 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1336
1337 // Builtin types for 'id', 'Class', and 'SEL'.
1338 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1339 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1340 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1341
1342 if (LangOpts.OpenCL) {
1343#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1344 InitBuiltinType(SingletonId, BuiltinType::Id);
1345#include "clang/Basic/OpenCLImageTypes.def"
1346
1347 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1348 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1349 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1350 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1351 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1352
1353#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1354 InitBuiltinType(Id##Ty, BuiltinType::Id);
1355#include "clang/Basic/OpenCLExtensionTypes.def"
1356 }
1357
1358 if (LangOpts.HLSL) {
1359#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1360 InitBuiltinType(SingletonId, BuiltinType::Id);
1361#include "clang/Basic/HLSLIntangibleTypes.def"
1362 }
1363
1364 if (Target.hasAArch64ACLETypes() ||
1365 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1366#define SVE_TYPE(Name, Id, SingletonId) \
1367 InitBuiltinType(SingletonId, BuiltinType::Id);
1368#include "clang/Basic/AArch64ACLETypes.def"
1369 }
1370
1371 if (Target.getTriple().isPPC64()) {
1372#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1373 InitBuiltinType(Id##Ty, BuiltinType::Id);
1374#include "clang/Basic/PPCTypes.def"
1375#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1376 InitBuiltinType(Id##Ty, BuiltinType::Id);
1377#include "clang/Basic/PPCTypes.def"
1378 }
1379
1380 if (Target.hasRISCVVTypes()) {
1381#define RVV_TYPE(Name, Id, SingletonId) \
1382 InitBuiltinType(SingletonId, BuiltinType::Id);
1383#include "clang/Basic/RISCVVTypes.def"
1384 }
1385
1386 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1387#define WASM_TYPE(Name, Id, SingletonId) \
1388 InitBuiltinType(SingletonId, BuiltinType::Id);
1389#include "clang/Basic/WebAssemblyReferenceTypes.def"
1390 }
1391
1392 if (Target.getTriple().isAMDGPU() ||
1393 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1394#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1395 InitBuiltinType(SingletonId, BuiltinType::Id);
1396#include "clang/Basic/AMDGPUTypes.def"
1397 }
1398
1399 // Builtin type for __objc_yes and __objc_no
1400 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1402
1403 ObjCConstantStringType = QualType();
1404
1405 ObjCSuperType = QualType();
1406
1407 // void * type
1408 if (LangOpts.OpenCLGenericAddressSpace) {
1409 auto Q = VoidTy.getQualifiers();
1410 Q.setAddressSpace(LangAS::opencl_generic);
1412 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1413 } else {
1415 }
1416
1417 // nullptr type (C++0x 2.14.7)
1418 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1419
1420 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1421 InitBuiltinType(HalfTy, BuiltinType::Half);
1422
1423 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1424
1425 // Builtin type used to help define __builtin_va_list.
1426 VaListTagDecl = nullptr;
1427
1428 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1429 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1432 }
1433}
1434
1436 return SourceMgr.getDiagnostics();
1437}
1438
1440 AttrVec *&Result = DeclAttrs[D];
1441 if (!Result) {
1442 void *Mem = Allocate(sizeof(AttrVec));
1443 Result = new (Mem) AttrVec;
1444 }
1445
1446 return *Result;
1447}
1448
1449/// Erase the attributes corresponding to the given declaration.
1451 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1452 if (Pos != DeclAttrs.end()) {
1453 Pos->second->~AttrVec();
1454 DeclAttrs.erase(Pos);
1455 }
1456}
1457
1458// FIXME: Remove ?
1461 assert(Var->isStaticDataMember() && "Not a static data member");
1463 .dyn_cast<MemberSpecializationInfo *>();
1464}
1465
1468 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1469 TemplateOrInstantiation.find(Var);
1470 if (Pos == TemplateOrInstantiation.end())
1471 return {};
1472
1473 return Pos->second;
1474}
1475
1476void
1479 SourceLocation PointOfInstantiation) {
1480 assert(Inst->isStaticDataMember() && "Not a static data member");
1481 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1483 Tmpl, TSK, PointOfInstantiation));
1484}
1485
1486void
1489 assert(!TemplateOrInstantiation[Inst] &&
1490 "Already noted what the variable was instantiated from");
1491 TemplateOrInstantiation[Inst] = TSI;
1492}
1493
1494NamedDecl *
1496 return InstantiatedFromUsingDecl.lookup(UUD);
1497}
1498
1499void
1501 assert((isa<UsingDecl>(Pattern) ||
1504 "pattern decl is not a using decl");
1505 assert((isa<UsingDecl>(Inst) ||
1508 "instantiation did not produce a using decl");
1509 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1510 InstantiatedFromUsingDecl[Inst] = Pattern;
1511}
1512
1515 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1516}
1517
1519 UsingEnumDecl *Pattern) {
1520 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1521 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1522}
1523
1526 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1527}
1528
1529void
1531 UsingShadowDecl *Pattern) {
1532 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1533 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1534}
1535
1536FieldDecl *
1538 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1539}
1540
1542 FieldDecl *Tmpl) {
1543 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1544 "Instantiated field decl is not unnamed");
1545 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1546 "Template field decl is not unnamed");
1547 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1548 "Already noted what unnamed field was instantiated from");
1549
1550 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1551}
1552
1557
1562
1563unsigned
1565 auto Range = overridden_methods(Method);
1566 return Range.end() - Range.begin();
1567}
1568
1571 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1572 OverriddenMethods.find(Method->getCanonicalDecl());
1573 if (Pos == OverriddenMethods.end())
1574 return overridden_method_range(nullptr, nullptr);
1575 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1576}
1577
1579 const CXXMethodDecl *Overridden) {
1580 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1581 OverriddenMethods[Method].push_back(Overridden);
1582}
1583
1585 const NamedDecl *D,
1586 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1587 assert(D);
1588
1589 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1590 Overridden.append(overridden_methods_begin(CXXMethod),
1591 overridden_methods_end(CXXMethod));
1592 return;
1593 }
1594
1595 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1596 if (!Method)
1597 return;
1598
1600 Method->getOverriddenMethods(OverDecls);
1601 Overridden.append(OverDecls.begin(), OverDecls.end());
1602}
1603
1604std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1606 assert(RD);
1607 CXXRecordDecl *D = RD->getDefinition();
1608 auto it = RelocatableClasses.find(D);
1609 if (it != RelocatableClasses.end())
1610 return it->getSecond();
1611 return std::nullopt;
1612}
1613
1616 assert(RD);
1617 CXXRecordDecl *D = RD->getDefinition();
1618 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1619 RelocatableClasses.insert({D, Info});
1620}
1621
1623 const ASTContext &Context, const CXXRecordDecl *Class) {
1624 if (!Class->isPolymorphic())
1625 return false;
1626 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1627 using AuthAttr = VTablePointerAuthenticationAttr;
1628 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1629 if (!ExplicitAuth)
1630 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1631 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1632 ExplicitAuth->getAddressDiscrimination();
1633 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1634 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1635 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1636}
1637
1638ASTContext::PointerAuthContent
1639ASTContext::findPointerAuthContent(QualType T) const {
1640 assert(isPointerAuthenticationAvailable());
1641
1642 T = T.getCanonicalType();
1643 if (T->isDependentType())
1644 return PointerAuthContent::None;
1645
1646 if (T.hasAddressDiscriminatedPointerAuth())
1647 return PointerAuthContent::AddressDiscriminatedData;
1648 const RecordDecl *RD = T->getAsRecordDecl();
1649 if (!RD)
1650 return PointerAuthContent::None;
1651
1652 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1653 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1654 return Existing->second;
1655
1656 PointerAuthContent Result = PointerAuthContent::None;
1657
1658 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1659 auto [ResultIter, DidAdd] =
1660 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1661 (void)ResultIter;
1662 (void)DidAdd;
1663 assert(DidAdd);
1664 return Result;
1665 };
1666 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1667 static_assert(PointerAuthContent::None <
1668 PointerAuthContent::AddressDiscriminatedVTable);
1669 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1670 PointerAuthContent::AddressDiscriminatedData);
1671 if (NewResult > Result)
1672 Result = NewResult;
1673 return Result != PointerAuthContent::AddressDiscriminatedData;
1674 };
1675 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1677 !ShouldContinueAfterUpdate(
1678 PointerAuthContent::AddressDiscriminatedVTable))
1679 return SaveResultAndReturn();
1680 for (auto Base : CXXRD->bases()) {
1681 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1682 return SaveResultAndReturn();
1683 }
1684 }
1685 for (auto *FieldDecl : RD->fields()) {
1686 if (!ShouldContinueAfterUpdate(
1687 findPointerAuthContent(FieldDecl->getType())))
1688 return SaveResultAndReturn();
1689 }
1690 return SaveResultAndReturn();
1691}
1692
1694 assert(!Import->getNextLocalImport() &&
1695 "Import declaration already in the chain");
1696 assert(!Import->isFromASTFile() && "Non-local import declaration");
1697 if (!FirstLocalImport) {
1698 FirstLocalImport = Import;
1699 LastLocalImport = Import;
1700 return;
1701 }
1702
1703 LastLocalImport->setNextLocalImport(Import);
1704 LastLocalImport = Import;
1705}
1706
1707//===----------------------------------------------------------------------===//
1708// Type Sizing and Analysis
1709//===----------------------------------------------------------------------===//
1710
1711/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1712/// scalar floating point type.
1713const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1714 switch (T->castAs<BuiltinType>()->getKind()) {
1715 default:
1716 llvm_unreachable("Not a floating point type!");
1717 case BuiltinType::BFloat16:
1718 return Target->getBFloat16Format();
1719 case BuiltinType::Float16:
1720 return Target->getHalfFormat();
1721 case BuiltinType::Half:
1722 return Target->getHalfFormat();
1723 case BuiltinType::Float: return Target->getFloatFormat();
1724 case BuiltinType::Double: return Target->getDoubleFormat();
1725 case BuiltinType::Ibm128:
1726 return Target->getIbm128Format();
1727 case BuiltinType::LongDouble:
1728 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1729 return AuxTarget->getLongDoubleFormat();
1730 return Target->getLongDoubleFormat();
1731 case BuiltinType::Float128:
1732 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1733 return AuxTarget->getFloat128Format();
1734 return Target->getFloat128Format();
1735 }
1736}
1737
1738CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1739 unsigned Align = Target->getCharWidth();
1740
1741 const unsigned AlignFromAttr = D->getMaxAlignment();
1742 if (AlignFromAttr)
1743 Align = AlignFromAttr;
1744
1745 // __attribute__((aligned)) can increase or decrease alignment
1746 // *except* on a struct or struct member, where it only increases
1747 // alignment unless 'packed' is also specified.
1748 //
1749 // It is an error for alignas to decrease alignment, so we can
1750 // ignore that possibility; Sema should diagnose it.
1751 bool UseAlignAttrOnly;
1752 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1753 UseAlignAttrOnly =
1754 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1755 else
1756 UseAlignAttrOnly = AlignFromAttr != 0;
1757 // If we're using the align attribute only, just ignore everything
1758 // else about the declaration and its type.
1759 if (UseAlignAttrOnly) {
1760 // do nothing
1761 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1762 QualType T = VD->getType();
1763 if (const auto *RT = T->getAs<ReferenceType>()) {
1764 if (ForAlignof)
1765 T = RT->getPointeeType();
1766 else
1767 T = getPointerType(RT->getPointeeType());
1768 }
1769 QualType BaseT = getBaseElementType(T);
1770 if (T->isFunctionType())
1771 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1772 else if (!BaseT->isIncompleteType()) {
1773 // Adjust alignments of declarations with array type by the
1774 // large-array alignment on the target.
1775 if (const ArrayType *arrayType = getAsArrayType(T)) {
1776 unsigned MinWidth = Target->getLargeArrayMinWidth();
1777 if (!ForAlignof && MinWidth) {
1779 Align = std::max(Align, Target->getLargeArrayAlign());
1782 Align = std::max(Align, Target->getLargeArrayAlign());
1783 }
1784 }
1785 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1786 if (BaseT.getQualifiers().hasUnaligned())
1787 Align = Target->getCharWidth();
1788 }
1789
1790 // Ensure minimum alignment for global variables.
1791 if (const auto *VD = dyn_cast<VarDecl>(D))
1792 if (VD->hasGlobalStorage() && !ForAlignof) {
1793 uint64_t TypeSize =
1794 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1795 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1796 }
1797
1798 // Fields can be subject to extra alignment constraints, like if
1799 // the field is packed, the struct is packed, or the struct has a
1800 // a max-field-alignment constraint (#pragma pack). So calculate
1801 // the actual alignment of the field within the struct, and then
1802 // (as we're expected to) constrain that by the alignment of the type.
1803 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1804 const RecordDecl *Parent = Field->getParent();
1805 // We can only produce a sensible answer if the record is valid.
1806 if (!Parent->isInvalidDecl()) {
1807 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1808
1809 // Start with the record's overall alignment.
1810 unsigned FieldAlign = toBits(Layout.getAlignment());
1811
1812 // Use the GCD of that and the offset within the record.
1813 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1814 if (Offset > 0) {
1815 // Alignment is always a power of 2, so the GCD will be a power of 2,
1816 // which means we get to do this crazy thing instead of Euclid's.
1817 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1818 if (LowBitOfOffset < FieldAlign)
1819 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1820 }
1821
1822 Align = std::min(Align, FieldAlign);
1823 }
1824 }
1825 }
1826
1827 // Some targets have hard limitation on the maximum requestable alignment in
1828 // aligned attribute for static variables.
1829 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1830 const auto *VD = dyn_cast<VarDecl>(D);
1831 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1832 Align = std::min(Align, MaxAlignedAttr);
1833
1834 return toCharUnitsFromBits(Align);
1835}
1836
1838 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1839}
1840
1841// getTypeInfoDataSizeInChars - Return the size of a type, in
1842// chars. If the type is a record, its data size is returned. This is
1843// the size of the memcpy that's performed when assigning this type
1844// using a trivial copy/move assignment operator.
1847
1848 // In C++, objects can sometimes be allocated into the tail padding
1849 // of a base-class subobject. We decide whether that's possible
1850 // during class layout, so here we can just trust the layout results.
1851 if (getLangOpts().CPlusPlus) {
1852 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1853 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1854 Info.Width = layout.getDataSize();
1855 }
1856 }
1857
1858 return Info;
1859}
1860
1861/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1862/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1865 const ConstantArrayType *CAT) {
1866 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1867 uint64_t Size = CAT->getZExtSize();
1868 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1869 (uint64_t)(-1)/Size) &&
1870 "Overflow in array type char size evaluation");
1871 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1872 unsigned Align = EltInfo.Align.getQuantity();
1873 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1874 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1875 Width = llvm::alignTo(Width, Align);
1878 EltInfo.AlignRequirement);
1879}
1880
1882 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1883 return getConstantArrayInfoInChars(*this, CAT);
1884 TypeInfo Info = getTypeInfo(T);
1887}
1888
1892
1894 // HLSL doesn't promote all small integer types to int, it
1895 // just uses the rank-based promotion rules for all types.
1896 if (getLangOpts().HLSL)
1897 return false;
1898
1899 if (const auto *BT = T->getAs<BuiltinType>())
1900 switch (BT->getKind()) {
1901 case BuiltinType::Bool:
1902 case BuiltinType::Char_S:
1903 case BuiltinType::Char_U:
1904 case BuiltinType::SChar:
1905 case BuiltinType::UChar:
1906 case BuiltinType::Short:
1907 case BuiltinType::UShort:
1908 case BuiltinType::WChar_S:
1909 case BuiltinType::WChar_U:
1910 case BuiltinType::Char8:
1911 case BuiltinType::Char16:
1912 case BuiltinType::Char32:
1913 return true;
1914 default:
1915 return false;
1916 }
1917
1918 // Enumerated types are promotable to their compatible integer types
1919 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1920 if (const auto *ED = T->getAsEnumDecl()) {
1921 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1922 ED->isScoped())
1923 return false;
1924
1925 return true;
1926 }
1927
1928 return false;
1929}
1930
1934
1936 return isAlignmentRequired(T.getTypePtr());
1937}
1938
1940 bool NeedsPreferredAlignment) const {
1941 // An alignment on a typedef overrides anything else.
1942 if (const auto *TT = T->getAs<TypedefType>())
1943 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1944 return Align;
1945
1946 // If we have an (array of) complete type, we're done.
1948 if (!T->isIncompleteType())
1949 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
1950
1951 // If we had an array type, its element type might be a typedef
1952 // type with an alignment attribute.
1953 if (const auto *TT = T->getAs<TypedefType>())
1954 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1955 return Align;
1956
1957 // Otherwise, see if the declaration of the type had an attribute.
1958 if (const auto *TD = T->getAsTagDecl())
1959 return TD->getMaxAlignment();
1960
1961 return 0;
1962}
1963
1965 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1966 if (I != MemoizedTypeInfo.end())
1967 return I->second;
1968
1969 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1970 TypeInfo TI = getTypeInfoImpl(T);
1971 MemoizedTypeInfo[T] = TI;
1972 return TI;
1973}
1974
1975/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1976/// method does not work on incomplete types.
1977///
1978/// FIXME: Pointers into different addr spaces could have different sizes and
1979/// alignment requirements: getPointerInfo should take an AddrSpace, this
1980/// should take a QualType, &c.
1981TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1982 uint64_t Width = 0;
1983 unsigned Align = 8;
1986 switch (T->getTypeClass()) {
1987#define TYPE(Class, Base)
1988#define ABSTRACT_TYPE(Class, Base)
1989#define NON_CANONICAL_TYPE(Class, Base)
1990#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1991#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1992 case Type::Class: \
1993 assert(!T->isDependentType() && "should not see dependent types here"); \
1994 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1995#include "clang/AST/TypeNodes.inc"
1996 llvm_unreachable("Should not see dependent types");
1997
1998 case Type::FunctionNoProto:
1999 case Type::FunctionProto:
2000 // GCC extension: alignof(function) = 32 bits
2001 Width = 0;
2002 Align = 32;
2003 break;
2004
2005 case Type::IncompleteArray:
2006 case Type::VariableArray:
2007 case Type::ConstantArray:
2008 case Type::ArrayParameter: {
2009 // Model non-constant sized arrays as size zero, but track the alignment.
2010 uint64_t Size = 0;
2011 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2012 Size = CAT->getZExtSize();
2013
2014 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2015 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2016 "Overflow in array type bit size evaluation");
2017 Width = EltInfo.Width * Size;
2018 Align = EltInfo.Align;
2019 AlignRequirement = EltInfo.AlignRequirement;
2020 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2021 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2022 Width = llvm::alignTo(Width, Align);
2023 break;
2024 }
2025
2026 case Type::ExtVector:
2027 case Type::Vector: {
2028 const auto *VT = cast<VectorType>(T);
2029 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2030 Width = VT->isPackedVectorBoolType(*this)
2031 ? VT->getNumElements()
2032 : EltInfo.Width * VT->getNumElements();
2033 // Enforce at least byte size and alignment.
2034 Width = std::max<unsigned>(8, Width);
2035 Align = std::max<unsigned>(8, Width);
2036
2037 // If the alignment is not a power of 2, round up to the next power of 2.
2038 // This happens for non-power-of-2 length vectors.
2039 if (Align & (Align-1)) {
2040 Align = llvm::bit_ceil(Align);
2041 Width = llvm::alignTo(Width, Align);
2042 }
2043 // Adjust the alignment based on the target max.
2044 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2045 if (TargetVectorAlign && TargetVectorAlign < Align)
2046 Align = TargetVectorAlign;
2047 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2048 // Adjust the alignment for fixed-length SVE vectors. This is important
2049 // for non-power-of-2 vector lengths.
2050 Align = 128;
2051 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2052 // Adjust the alignment for fixed-length SVE predicates.
2053 Align = 16;
2054 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2055 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2056 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2057 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2058 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2059 // Adjust the alignment for fixed-length RVV vectors.
2060 Align = std::min<unsigned>(64, Width);
2061 break;
2062 }
2063
2064 case Type::ConstantMatrix: {
2065 const auto *MT = cast<ConstantMatrixType>(T);
2066 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2067 // The internal layout of a matrix value is implementation defined.
2068 // Initially be ABI compatible with arrays with respect to alignment and
2069 // size.
2070 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2071 Align = ElementInfo.Align;
2072 break;
2073 }
2074
2075 case Type::Builtin:
2076 switch (cast<BuiltinType>(T)->getKind()) {
2077 default: llvm_unreachable("Unknown builtin type!");
2078 case BuiltinType::Void:
2079 // GCC extension: alignof(void) = 8 bits.
2080 Width = 0;
2081 Align = 8;
2082 break;
2083 case BuiltinType::Bool:
2084 Width = Target->getBoolWidth();
2085 Align = Target->getBoolAlign();
2086 break;
2087 case BuiltinType::Char_S:
2088 case BuiltinType::Char_U:
2089 case BuiltinType::UChar:
2090 case BuiltinType::SChar:
2091 case BuiltinType::Char8:
2092 Width = Target->getCharWidth();
2093 Align = Target->getCharAlign();
2094 break;
2095 case BuiltinType::WChar_S:
2096 case BuiltinType::WChar_U:
2097 Width = Target->getWCharWidth();
2098 Align = Target->getWCharAlign();
2099 break;
2100 case BuiltinType::Char16:
2101 Width = Target->getChar16Width();
2102 Align = Target->getChar16Align();
2103 break;
2104 case BuiltinType::Char32:
2105 Width = Target->getChar32Width();
2106 Align = Target->getChar32Align();
2107 break;
2108 case BuiltinType::UShort:
2109 case BuiltinType::Short:
2110 Width = Target->getShortWidth();
2111 Align = Target->getShortAlign();
2112 break;
2113 case BuiltinType::UInt:
2114 case BuiltinType::Int:
2115 Width = Target->getIntWidth();
2116 Align = Target->getIntAlign();
2117 break;
2118 case BuiltinType::ULong:
2119 case BuiltinType::Long:
2120 Width = Target->getLongWidth();
2121 Align = Target->getLongAlign();
2122 break;
2123 case BuiltinType::ULongLong:
2124 case BuiltinType::LongLong:
2125 Width = Target->getLongLongWidth();
2126 Align = Target->getLongLongAlign();
2127 break;
2128 case BuiltinType::Int128:
2129 case BuiltinType::UInt128:
2130 Width = 128;
2131 Align = Target->getInt128Align();
2132 break;
2133 case BuiltinType::ShortAccum:
2134 case BuiltinType::UShortAccum:
2135 case BuiltinType::SatShortAccum:
2136 case BuiltinType::SatUShortAccum:
2137 Width = Target->getShortAccumWidth();
2138 Align = Target->getShortAccumAlign();
2139 break;
2140 case BuiltinType::Accum:
2141 case BuiltinType::UAccum:
2142 case BuiltinType::SatAccum:
2143 case BuiltinType::SatUAccum:
2144 Width = Target->getAccumWidth();
2145 Align = Target->getAccumAlign();
2146 break;
2147 case BuiltinType::LongAccum:
2148 case BuiltinType::ULongAccum:
2149 case BuiltinType::SatLongAccum:
2150 case BuiltinType::SatULongAccum:
2151 Width = Target->getLongAccumWidth();
2152 Align = Target->getLongAccumAlign();
2153 break;
2154 case BuiltinType::ShortFract:
2155 case BuiltinType::UShortFract:
2156 case BuiltinType::SatShortFract:
2157 case BuiltinType::SatUShortFract:
2158 Width = Target->getShortFractWidth();
2159 Align = Target->getShortFractAlign();
2160 break;
2161 case BuiltinType::Fract:
2162 case BuiltinType::UFract:
2163 case BuiltinType::SatFract:
2164 case BuiltinType::SatUFract:
2165 Width = Target->getFractWidth();
2166 Align = Target->getFractAlign();
2167 break;
2168 case BuiltinType::LongFract:
2169 case BuiltinType::ULongFract:
2170 case BuiltinType::SatLongFract:
2171 case BuiltinType::SatULongFract:
2172 Width = Target->getLongFractWidth();
2173 Align = Target->getLongFractAlign();
2174 break;
2175 case BuiltinType::BFloat16:
2176 if (Target->hasBFloat16Type()) {
2177 Width = Target->getBFloat16Width();
2178 Align = Target->getBFloat16Align();
2179 } else if ((getLangOpts().SYCLIsDevice ||
2180 (getLangOpts().OpenMP &&
2181 getLangOpts().OpenMPIsTargetDevice)) &&
2182 AuxTarget->hasBFloat16Type()) {
2183 Width = AuxTarget->getBFloat16Width();
2184 Align = AuxTarget->getBFloat16Align();
2185 }
2186 break;
2187 case BuiltinType::Float16:
2188 case BuiltinType::Half:
2189 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2190 !getLangOpts().OpenMPIsTargetDevice) {
2191 Width = Target->getHalfWidth();
2192 Align = Target->getHalfAlign();
2193 } else {
2194 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2195 "Expected OpenMP device compilation.");
2196 Width = AuxTarget->getHalfWidth();
2197 Align = AuxTarget->getHalfAlign();
2198 }
2199 break;
2200 case BuiltinType::Float:
2201 Width = Target->getFloatWidth();
2202 Align = Target->getFloatAlign();
2203 break;
2204 case BuiltinType::Double:
2205 Width = Target->getDoubleWidth();
2206 Align = Target->getDoubleAlign();
2207 break;
2208 case BuiltinType::Ibm128:
2209 Width = Target->getIbm128Width();
2210 Align = Target->getIbm128Align();
2211 break;
2212 case BuiltinType::LongDouble:
2213 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2214 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2215 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2216 Width = AuxTarget->getLongDoubleWidth();
2217 Align = AuxTarget->getLongDoubleAlign();
2218 } else {
2219 Width = Target->getLongDoubleWidth();
2220 Align = Target->getLongDoubleAlign();
2221 }
2222 break;
2223 case BuiltinType::Float128:
2224 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2225 !getLangOpts().OpenMPIsTargetDevice) {
2226 Width = Target->getFloat128Width();
2227 Align = Target->getFloat128Align();
2228 } else {
2229 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2230 "Expected OpenMP device compilation.");
2231 Width = AuxTarget->getFloat128Width();
2232 Align = AuxTarget->getFloat128Align();
2233 }
2234 break;
2235 case BuiltinType::NullPtr:
2236 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2237 Width = Target->getPointerWidth(LangAS::Default);
2238 Align = Target->getPointerAlign(LangAS::Default);
2239 break;
2240 case BuiltinType::ObjCId:
2241 case BuiltinType::ObjCClass:
2242 case BuiltinType::ObjCSel:
2243 Width = Target->getPointerWidth(LangAS::Default);
2244 Align = Target->getPointerAlign(LangAS::Default);
2245 break;
2246 case BuiltinType::OCLSampler:
2247 case BuiltinType::OCLEvent:
2248 case BuiltinType::OCLClkEvent:
2249 case BuiltinType::OCLQueue:
2250 case BuiltinType::OCLReserveID:
2251#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2252 case BuiltinType::Id:
2253#include "clang/Basic/OpenCLImageTypes.def"
2254#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2255 case BuiltinType::Id:
2256#include "clang/Basic/OpenCLExtensionTypes.def"
2257 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2258 Width = Target->getPointerWidth(AS);
2259 Align = Target->getPointerAlign(AS);
2260 break;
2261 // The SVE types are effectively target-specific. The length of an
2262 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2263 // of 128 bits. There is one predicate bit for each vector byte, so the
2264 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2265 //
2266 // Because the length is only known at runtime, we use a dummy value
2267 // of 0 for the static length. The alignment values are those defined
2268 // by the Procedure Call Standard for the Arm Architecture.
2269#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2270 case BuiltinType::Id: \
2271 Width = 0; \
2272 Align = 128; \
2273 break;
2274#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2275 case BuiltinType::Id: \
2276 Width = 0; \
2277 Align = 16; \
2278 break;
2279#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2280 case BuiltinType::Id: \
2281 Width = 0; \
2282 Align = 16; \
2283 break;
2284#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2285 case BuiltinType::Id: \
2286 Width = Bits; \
2287 Align = Bits; \
2288 break;
2289#include "clang/Basic/AArch64ACLETypes.def"
2290#define PPC_VECTOR_TYPE(Name, Id, Size) \
2291 case BuiltinType::Id: \
2292 Width = Size; \
2293 Align = Size; \
2294 break;
2295#include "clang/Basic/PPCTypes.def"
2296#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2297 IsFP, IsBF) \
2298 case BuiltinType::Id: \
2299 Width = 0; \
2300 Align = ElBits; \
2301 break;
2302#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2303 case BuiltinType::Id: \
2304 Width = 0; \
2305 Align = 8; \
2306 break;
2307#include "clang/Basic/RISCVVTypes.def"
2308#define WASM_TYPE(Name, Id, SingletonId) \
2309 case BuiltinType::Id: \
2310 Width = 0; \
2311 Align = 8; \
2312 break;
2313#include "clang/Basic/WebAssemblyReferenceTypes.def"
2314#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2315 case BuiltinType::ID: \
2316 Width = WIDTH; \
2317 Align = ALIGN; \
2318 break;
2319#include "clang/Basic/AMDGPUTypes.def"
2320#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2321#include "clang/Basic/HLSLIntangibleTypes.def"
2322 Width = Target->getPointerWidth(LangAS::Default);
2323 Align = Target->getPointerAlign(LangAS::Default);
2324 break;
2325 }
2326 break;
2327 case Type::ObjCObjectPointer:
2328 Width = Target->getPointerWidth(LangAS::Default);
2329 Align = Target->getPointerAlign(LangAS::Default);
2330 break;
2331 case Type::BlockPointer:
2332 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2333 Width = Target->getPointerWidth(AS);
2334 Align = Target->getPointerAlign(AS);
2335 break;
2336 case Type::LValueReference:
2337 case Type::RValueReference:
2338 // alignof and sizeof should never enter this code path here, so we go
2339 // the pointer route.
2340 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2341 Width = Target->getPointerWidth(AS);
2342 Align = Target->getPointerAlign(AS);
2343 break;
2344 case Type::Pointer:
2345 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2346 Width = Target->getPointerWidth(AS);
2347 Align = Target->getPointerAlign(AS);
2348 break;
2349 case Type::MemberPointer: {
2350 const auto *MPT = cast<MemberPointerType>(T);
2351 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2352 Width = MPI.Width;
2353 Align = MPI.Align;
2354 break;
2355 }
2356 case Type::Complex: {
2357 // Complex types have the same alignment as their elements, but twice the
2358 // size.
2359 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2360 Width = EltInfo.Width * 2;
2361 Align = EltInfo.Align;
2362 break;
2363 }
2364 case Type::ObjCObject:
2365 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2366 case Type::Adjusted:
2367 case Type::Decayed:
2368 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2369 case Type::ObjCInterface: {
2370 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2371 if (ObjCI->getDecl()->isInvalidDecl()) {
2372 Width = 8;
2373 Align = 8;
2374 break;
2375 }
2376 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2377 Width = toBits(Layout.getSize());
2378 Align = toBits(Layout.getAlignment());
2379 break;
2380 }
2381 case Type::BitInt: {
2382 const auto *EIT = cast<BitIntType>(T);
2383 Align = Target->getBitIntAlign(EIT->getNumBits());
2384 Width = Target->getBitIntWidth(EIT->getNumBits());
2385 break;
2386 }
2387 case Type::Record:
2388 case Type::Enum: {
2389 const auto *TT = cast<TagType>(T);
2390 const TagDecl *TD = TT->getOriginalDecl()->getDefinitionOrSelf();
2391
2392 if (TD->isInvalidDecl()) {
2393 Width = 8;
2394 Align = 8;
2395 break;
2396 }
2397
2398 if (isa<EnumType>(TT)) {
2399 const EnumDecl *ED = cast<EnumDecl>(TD);
2400 TypeInfo Info =
2402 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2403 Info.Align = AttrAlign;
2405 }
2406 return Info;
2407 }
2408
2409 const auto *RD = cast<RecordDecl>(TD);
2410 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2411 Width = toBits(Layout.getSize());
2412 Align = toBits(Layout.getAlignment());
2413 AlignRequirement = RD->hasAttr<AlignedAttr>()
2415 : AlignRequirementKind::None;
2416 break;
2417 }
2418
2419 case Type::SubstTemplateTypeParm:
2421 getReplacementType().getTypePtr());
2422
2423 case Type::Auto:
2424 case Type::DeducedTemplateSpecialization: {
2425 const auto *A = cast<DeducedType>(T);
2426 assert(!A->getDeducedType().isNull() &&
2427 "cannot request the size of an undeduced or dependent auto type");
2428 return getTypeInfo(A->getDeducedType().getTypePtr());
2429 }
2430
2431 case Type::Paren:
2432 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2433
2434 case Type::MacroQualified:
2435 return getTypeInfo(
2437
2438 case Type::ObjCTypeParam:
2439 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2440
2441 case Type::Using:
2442 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2443
2444 case Type::Typedef: {
2445 const auto *TT = cast<TypedefType>(T);
2446 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2447 // If the typedef has an aligned attribute on it, it overrides any computed
2448 // alignment we have. This violates the GCC documentation (which says that
2449 // attribute(aligned) can only round up) but matches its implementation.
2450 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2451 Align = AttrAlign;
2452 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2453 } else {
2454 Align = Info.Align;
2455 AlignRequirement = Info.AlignRequirement;
2456 }
2457 Width = Info.Width;
2458 break;
2459 }
2460
2461 case Type::Attributed:
2462 return getTypeInfo(
2463 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2464
2465 case Type::CountAttributed:
2466 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2467
2468 case Type::BTFTagAttributed:
2469 return getTypeInfo(
2470 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2471
2472 case Type::HLSLAttributedResource:
2473 return getTypeInfo(
2474 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2475
2476 case Type::HLSLInlineSpirv: {
2477 const auto *ST = cast<HLSLInlineSpirvType>(T);
2478 // Size is specified in bytes, convert to bits
2479 Width = ST->getSize() * 8;
2480 Align = ST->getAlignment();
2481 if (Width == 0 && Align == 0) {
2482 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2483 Width = 32;
2484 Align = 32;
2485 }
2486 break;
2487 }
2488
2489 case Type::Atomic: {
2490 // Start with the base type information.
2491 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2492 Width = Info.Width;
2493 Align = Info.Align;
2494
2495 if (!Width) {
2496 // An otherwise zero-sized type should still generate an
2497 // atomic operation.
2498 Width = Target->getCharWidth();
2499 assert(Align);
2500 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2501 // If the size of the type doesn't exceed the platform's max
2502 // atomic promotion width, make the size and alignment more
2503 // favorable to atomic operations:
2504
2505 // Round the size up to a power of 2.
2506 Width = llvm::bit_ceil(Width);
2507
2508 // Set the alignment equal to the size.
2509 Align = static_cast<unsigned>(Width);
2510 }
2511 }
2512 break;
2513
2514 case Type::PredefinedSugar:
2515 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2516
2517 case Type::Pipe:
2518 Width = Target->getPointerWidth(LangAS::opencl_global);
2519 Align = Target->getPointerAlign(LangAS::opencl_global);
2520 break;
2521 }
2522
2523 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2524 return TypeInfo(Width, Align, AlignRequirement);
2525}
2526
2528 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2529 if (I != MemoizedUnadjustedAlign.end())
2530 return I->second;
2531
2532 unsigned UnadjustedAlign;
2533 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2534 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getOriginalDecl());
2535 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2536 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2537 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2538 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2539 } else {
2540 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2541 }
2542
2543 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2544 return UnadjustedAlign;
2545}
2546
2548 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2549 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2550 return SimdAlign;
2551}
2552
2553/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2555 return CharUnits::fromQuantity(BitSize / getCharWidth());
2556}
2557
2558/// toBits - Convert a size in characters to a size in characters.
2559int64_t ASTContext::toBits(CharUnits CharSize) const {
2560 return CharSize.getQuantity() * getCharWidth();
2561}
2562
2563/// getTypeSizeInChars - Return the size of the specified type, in characters.
2564/// This method does not work on incomplete types.
2571
2572/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2573/// characters. This method does not work on incomplete types.
2580
2581/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2582/// type, in characters, before alignment adjustments. This method does
2583/// not work on incomplete types.
2590
2591/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2592/// type for the current target in bits. This can be different than the ABI
2593/// alignment in cases where it is beneficial for performance or backwards
2594/// compatibility preserving to overalign a data type. (Note: despite the name,
2595/// the preferred alignment is ABI-impacting, and not an optimization.)
2597 TypeInfo TI = getTypeInfo(T);
2598 unsigned ABIAlign = TI.Align;
2599
2600 T = T->getBaseElementTypeUnsafe();
2601
2602 // The preferred alignment of member pointers is that of a pointer.
2603 if (T->isMemberPointerType())
2604 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2605
2606 if (!Target->allowsLargerPreferedTypeAlignment())
2607 return ABIAlign;
2608
2609 if (const auto *RD = T->getAsRecordDecl()) {
2610 // When used as part of a typedef, or together with a 'packed' attribute,
2611 // the 'aligned' attribute can be used to decrease alignment. Note that the
2612 // 'packed' case is already taken into consideration when computing the
2613 // alignment, we only need to handle the typedef case here.
2615 RD->isInvalidDecl())
2616 return ABIAlign;
2617
2618 unsigned PreferredAlign = static_cast<unsigned>(
2619 toBits(getASTRecordLayout(RD).PreferredAlignment));
2620 assert(PreferredAlign >= ABIAlign &&
2621 "PreferredAlign should be at least as large as ABIAlign.");
2622 return PreferredAlign;
2623 }
2624
2625 // Double (and, for targets supporting AIX `power` alignment, long double) and
2626 // long long should be naturally aligned (despite requiring less alignment) if
2627 // possible.
2628 if (const auto *CT = T->getAs<ComplexType>())
2629 T = CT->getElementType().getTypePtr();
2630 if (const auto *ED = T->getAsEnumDecl())
2631 T = ED->getIntegerType().getTypePtr();
2632 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2633 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2634 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2635 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2636 Target->defaultsToAIXPowerAlignment()))
2637 // Don't increase the alignment if an alignment attribute was specified on a
2638 // typedef declaration.
2639 if (!TI.isAlignRequired())
2640 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2641
2642 return ABIAlign;
2643}
2644
2645/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2646/// for __attribute__((aligned)) on this target, to be used if no alignment
2647/// value is specified.
2651
2652/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2653/// to a global variable of the specified type.
2655 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2656 return std::max(getPreferredTypeAlign(T),
2657 getMinGlobalAlignOfVar(TypeSize, VD));
2658}
2659
2660/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2661/// should be given to a global variable of the specified type.
2666
2668 const VarDecl *VD) const {
2669 // Make the default handling as that of a non-weak definition in the
2670 // current translation unit.
2671 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2672 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2673}
2674
2676 CharUnits Offset = CharUnits::Zero();
2677 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2678 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2679 Offset += Layout->getBaseClassOffset(Base);
2680 Layout = &getASTRecordLayout(Base);
2681 }
2682 return Offset;
2683}
2684
2686 const ValueDecl *MPD = MP.getMemberPointerDecl();
2689 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2691 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2692 const CXXRecordDecl *Base = RD;
2693 const CXXRecordDecl *Derived = Path[I];
2694 if (DerivedMember)
2695 std::swap(Base, Derived);
2697 RD = Path[I];
2698 }
2699 if (DerivedMember)
2701 return ThisAdjustment;
2702}
2703
2704/// DeepCollectObjCIvars -
2705/// This routine first collects all declared, but not synthesized, ivars in
2706/// super class and then collects all ivars, including those synthesized for
2707/// current class. This routine is used for implementation of current class
2708/// when all ivars, declared and synthesized are known.
2710 bool leafClass,
2712 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2713 DeepCollectObjCIvars(SuperClass, false, Ivars);
2714 if (!leafClass) {
2715 llvm::append_range(Ivars, OI->ivars());
2716 } else {
2717 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2718 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2719 Iv= Iv->getNextIvar())
2720 Ivars.push_back(Iv);
2721 }
2722}
2723
2724/// CollectInheritedProtocols - Collect all protocols in current class and
2725/// those inherited by it.
2728 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2729 // We can use protocol_iterator here instead of
2730 // all_referenced_protocol_iterator since we are walking all categories.
2731 for (auto *Proto : OI->all_referenced_protocols()) {
2732 CollectInheritedProtocols(Proto, Protocols);
2733 }
2734
2735 // Categories of this Interface.
2736 for (const auto *Cat : OI->visible_categories())
2737 CollectInheritedProtocols(Cat, Protocols);
2738
2739 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2740 while (SD) {
2741 CollectInheritedProtocols(SD, Protocols);
2742 SD = SD->getSuperClass();
2743 }
2744 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2745 for (auto *Proto : OC->protocols()) {
2746 CollectInheritedProtocols(Proto, Protocols);
2747 }
2748 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2749 // Insert the protocol.
2750 if (!Protocols.insert(
2751 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2752 return;
2753
2754 for (auto *Proto : OP->protocols())
2755 CollectInheritedProtocols(Proto, Protocols);
2756 }
2757}
2758
2760 const RecordDecl *RD,
2761 bool CheckIfTriviallyCopyable) {
2762 assert(RD->isUnion() && "Must be union type");
2763 CharUnits UnionSize =
2764 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2765
2766 for (const auto *Field : RD->fields()) {
2767 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2768 CheckIfTriviallyCopyable))
2769 return false;
2770 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2771 if (FieldSize != UnionSize)
2772 return false;
2773 }
2774 return !RD->field_empty();
2775}
2776
2777static int64_t getSubobjectOffset(const FieldDecl *Field,
2778 const ASTContext &Context,
2779 const clang::ASTRecordLayout & /*Layout*/) {
2780 return Context.getFieldOffset(Field);
2781}
2782
2783static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2784 const ASTContext &Context,
2785 const clang::ASTRecordLayout &Layout) {
2786 return Context.toBits(Layout.getBaseClassOffset(RD));
2787}
2788
2789static std::optional<int64_t>
2791 const RecordDecl *RD,
2792 bool CheckIfTriviallyCopyable);
2793
2794static std::optional<int64_t>
2795getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2796 bool CheckIfTriviallyCopyable) {
2797 if (const auto *RD = Field->getType()->getAsRecordDecl();
2798 RD && !RD->isUnion())
2799 return structHasUniqueObjectRepresentations(Context, RD,
2800 CheckIfTriviallyCopyable);
2801
2802 // A _BitInt type may not be unique if it has padding bits
2803 // but if it is a bitfield the padding bits are not used.
2804 bool IsBitIntType = Field->getType()->isBitIntType();
2805 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2806 !Context.hasUniqueObjectRepresentations(Field->getType(),
2807 CheckIfTriviallyCopyable))
2808 return std::nullopt;
2809
2810 int64_t FieldSizeInBits =
2811 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2812 if (Field->isBitField()) {
2813 // If we have explicit padding bits, they don't contribute bits
2814 // to the actual object representation, so return 0.
2815 if (Field->isUnnamedBitField())
2816 return 0;
2817
2818 int64_t BitfieldSize = Field->getBitWidthValue();
2819 if (IsBitIntType) {
2820 if ((unsigned)BitfieldSize >
2821 cast<BitIntType>(Field->getType())->getNumBits())
2822 return std::nullopt;
2823 } else if (BitfieldSize > FieldSizeInBits) {
2824 return std::nullopt;
2825 }
2826 FieldSizeInBits = BitfieldSize;
2827 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2828 Field->getType(), CheckIfTriviallyCopyable)) {
2829 return std::nullopt;
2830 }
2831 return FieldSizeInBits;
2832}
2833
2834static std::optional<int64_t>
2836 bool CheckIfTriviallyCopyable) {
2837 return structHasUniqueObjectRepresentations(Context, RD,
2838 CheckIfTriviallyCopyable);
2839}
2840
2841template <typename RangeT>
2843 const RangeT &Subobjects, int64_t CurOffsetInBits,
2844 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2845 bool CheckIfTriviallyCopyable) {
2846 for (const auto *Subobject : Subobjects) {
2847 std::optional<int64_t> SizeInBits =
2848 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2849 if (!SizeInBits)
2850 return std::nullopt;
2851 if (*SizeInBits != 0) {
2852 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2853 if (Offset != CurOffsetInBits)
2854 return std::nullopt;
2855 CurOffsetInBits += *SizeInBits;
2856 }
2857 }
2858 return CurOffsetInBits;
2859}
2860
2861static std::optional<int64_t>
2863 const RecordDecl *RD,
2864 bool CheckIfTriviallyCopyable) {
2865 assert(!RD->isUnion() && "Must be struct/class type");
2866 const auto &Layout = Context.getASTRecordLayout(RD);
2867
2868 int64_t CurOffsetInBits = 0;
2869 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2870 if (ClassDecl->isDynamicClass())
2871 return std::nullopt;
2872
2874 for (const auto &Base : ClassDecl->bases()) {
2875 // Empty types can be inherited from, and non-empty types can potentially
2876 // have tail padding, so just make sure there isn't an error.
2877 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2878 }
2879
2880 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2881 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2882 });
2883
2884 std::optional<int64_t> OffsetAfterBases =
2886 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2887 if (!OffsetAfterBases)
2888 return std::nullopt;
2889 CurOffsetInBits = *OffsetAfterBases;
2890 }
2891
2892 std::optional<int64_t> OffsetAfterFields =
2894 RD->fields(), CurOffsetInBits, Context, Layout,
2895 CheckIfTriviallyCopyable);
2896 if (!OffsetAfterFields)
2897 return std::nullopt;
2898 CurOffsetInBits = *OffsetAfterFields;
2899
2900 return CurOffsetInBits;
2901}
2902
2904 QualType Ty, bool CheckIfTriviallyCopyable) const {
2905 // C++17 [meta.unary.prop]:
2906 // The predicate condition for a template specialization
2907 // has_unique_object_representations<T> shall be satisfied if and only if:
2908 // (9.1) - T is trivially copyable, and
2909 // (9.2) - any two objects of type T with the same value have the same
2910 // object representation, where:
2911 // - two objects of array or non-union class type are considered to have
2912 // the same value if their respective sequences of direct subobjects
2913 // have the same values, and
2914 // - two objects of union type are considered to have the same value if
2915 // they have the same active member and the corresponding members have
2916 // the same value.
2917 // The set of scalar types for which this condition holds is
2918 // implementation-defined. [ Note: If a type has padding bits, the condition
2919 // does not hold; otherwise, the condition holds true for unsigned integral
2920 // types. -- end note ]
2921 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2922
2923 // Arrays are unique only if their element type is unique.
2924 if (Ty->isArrayType())
2926 CheckIfTriviallyCopyable);
2927
2928 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2929 "hasUniqueObjectRepresentations should not be called with an "
2930 "incomplete type");
2931
2932 // (9.1) - T is trivially copyable...
2933 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
2934 return false;
2935
2936 // All integrals and enums are unique.
2937 if (Ty->isIntegralOrEnumerationType()) {
2938 // Address discriminated integer types are not unique.
2940 return false;
2941 // Except _BitInt types that have padding bits.
2942 if (const auto *BIT = Ty->getAs<BitIntType>())
2943 return getTypeSize(BIT) == BIT->getNumBits();
2944
2945 return true;
2946 }
2947
2948 // All other pointers are unique.
2949 if (Ty->isPointerType())
2951
2952 if (const auto *MPT = Ty->getAs<MemberPointerType>())
2953 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2954
2955 if (const auto *Record = Ty->getAsRecordDecl()) {
2956 if (Record->isInvalidDecl())
2957 return false;
2958
2959 if (Record->isUnion())
2961 CheckIfTriviallyCopyable);
2962
2963 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
2964 *this, Record, CheckIfTriviallyCopyable);
2965
2966 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
2967 }
2968
2969 // FIXME: More cases to handle here (list by rsmith):
2970 // vectors (careful about, eg, vector of 3 foo)
2971 // _Complex int and friends
2972 // _Atomic T
2973 // Obj-C block pointers
2974 // Obj-C object pointers
2975 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2976 // clk_event_t, queue_t, reserve_id_t)
2977 // There're also Obj-C class types and the Obj-C selector type, but I think it
2978 // makes sense for those to return false here.
2979
2980 return false;
2981}
2982
2984 unsigned count = 0;
2985 // Count ivars declared in class extension.
2986 for (const auto *Ext : OI->known_extensions())
2987 count += Ext->ivar_size();
2988
2989 // Count ivar defined in this class's implementation. This
2990 // includes synthesized ivars.
2991 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2992 count += ImplDecl->ivar_size();
2993
2994 return count;
2995}
2996
2998 if (!E)
2999 return false;
3000
3001 // nullptr_t is always treated as null.
3002 if (E->getType()->isNullPtrType()) return true;
3003
3004 if (E->getType()->isAnyPointerType() &&
3007 return true;
3008
3009 // Unfortunately, __null has type 'int'.
3010 if (isa<GNUNullExpr>(E)) return true;
3011
3012 return false;
3013}
3014
3015/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3016/// exists.
3018 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3019 I = ObjCImpls.find(D);
3020 if (I != ObjCImpls.end())
3021 return cast<ObjCImplementationDecl>(I->second);
3022 return nullptr;
3023}
3024
3025/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3026/// exists.
3028 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3029 I = ObjCImpls.find(D);
3030 if (I != ObjCImpls.end())
3031 return cast<ObjCCategoryImplDecl>(I->second);
3032 return nullptr;
3033}
3034
3035/// Set the implementation of ObjCInterfaceDecl.
3037 ObjCImplementationDecl *ImplD) {
3038 assert(IFaceD && ImplD && "Passed null params");
3039 ObjCImpls[IFaceD] = ImplD;
3040}
3041
3042/// Set the implementation of ObjCCategoryDecl.
3044 ObjCCategoryImplDecl *ImplD) {
3045 assert(CatD && ImplD && "Passed null params");
3046 ObjCImpls[CatD] = ImplD;
3047}
3048
3049const ObjCMethodDecl *
3051 return ObjCMethodRedecls.lookup(MD);
3052}
3053
3055 const ObjCMethodDecl *Redecl) {
3056 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3057 ObjCMethodRedecls[MD] = Redecl;
3058}
3059
3061 const NamedDecl *ND) const {
3062 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3063 return ID;
3064 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3065 return CD->getClassInterface();
3066 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3067 return IMD->getClassInterface();
3068
3069 return nullptr;
3070}
3071
3072/// Get the copy initialization expression of VarDecl, or nullptr if
3073/// none exists.
3075 assert(VD && "Passed null params");
3076 assert(VD->hasAttr<BlocksAttr>() &&
3077 "getBlockVarCopyInits - not __block var");
3078 auto I = BlockVarCopyInits.find(VD);
3079 if (I != BlockVarCopyInits.end())
3080 return I->second;
3081 return {nullptr, false};
3082}
3083
3084/// Set the copy initialization expression of a block var decl.
3086 bool CanThrow) {
3087 assert(VD && CopyExpr && "Passed null params");
3088 assert(VD->hasAttr<BlocksAttr>() &&
3089 "setBlockVarCopyInits - not __block var");
3090 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3091}
3092
3094 unsigned DataSize) const {
3095 if (!DataSize)
3097 else
3098 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3099 "incorrect data size provided to CreateTypeSourceInfo!");
3100
3101 auto *TInfo =
3102 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3103 new (TInfo) TypeSourceInfo(T, DataSize);
3104 return TInfo;
3105}
3106
3108 SourceLocation L) const {
3110 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3111 return DI;
3112}
3113
3114const ASTRecordLayout &
3116 return getObjCLayout(D);
3117}
3118
3121 bool &AnyNonCanonArgs) {
3122 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3123 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3124 return CanonArgs;
3125}
3126
3129 bool AnyNonCanonArgs = false;
3130 for (auto &Arg : Args) {
3131 TemplateArgument OrigArg = Arg;
3133 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3134 }
3135 return AnyNonCanonArgs;
3136}
3137
3138//===----------------------------------------------------------------------===//
3139// Type creation/memoization methods
3140//===----------------------------------------------------------------------===//
3141
3143ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3144 unsigned fastQuals = quals.getFastQualifiers();
3145 quals.removeFastQualifiers();
3146
3147 // Check if we've already instantiated this type.
3148 llvm::FoldingSetNodeID ID;
3149 ExtQuals::Profile(ID, baseType, quals);
3150 void *insertPos = nullptr;
3151 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3152 assert(eq->getQualifiers() == quals);
3153 return QualType(eq, fastQuals);
3154 }
3155
3156 // If the base type is not canonical, make the appropriate canonical type.
3157 QualType canon;
3158 if (!baseType->isCanonicalUnqualified()) {
3159 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3160 canonSplit.Quals.addConsistentQualifiers(quals);
3161 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3162
3163 // Re-find the insert position.
3164 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3165 }
3166
3167 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3168 ExtQualNodes.InsertNode(eq, insertPos);
3169 return QualType(eq, fastQuals);
3170}
3171
3173 LangAS AddressSpace) const {
3174 QualType CanT = getCanonicalType(T);
3175 if (CanT.getAddressSpace() == AddressSpace)
3176 return T;
3177
3178 // If we are composing extended qualifiers together, merge together
3179 // into one ExtQuals node.
3180 QualifierCollector Quals;
3181 const Type *TypeNode = Quals.strip(T);
3182
3183 // If this type already has an address space specified, it cannot get
3184 // another one.
3185 assert(!Quals.hasAddressSpace() &&
3186 "Type cannot be in multiple addr spaces!");
3187 Quals.addAddressSpace(AddressSpace);
3188
3189 return getExtQualType(TypeNode, Quals);
3190}
3191
3193 // If the type is not qualified with an address space, just return it
3194 // immediately.
3195 if (!T.hasAddressSpace())
3196 return T;
3197
3198 QualifierCollector Quals;
3199 const Type *TypeNode;
3200 // For arrays, strip the qualifier off the element type, then reconstruct the
3201 // array type
3202 if (T.getTypePtr()->isArrayType()) {
3203 T = getUnqualifiedArrayType(T, Quals);
3204 TypeNode = T.getTypePtr();
3205 } else {
3206 // If we are composing extended qualifiers together, merge together
3207 // into one ExtQuals node.
3208 while (T.hasAddressSpace()) {
3209 TypeNode = Quals.strip(T);
3210
3211 // If the type no longer has an address space after stripping qualifiers,
3212 // jump out.
3213 if (!QualType(TypeNode, 0).hasAddressSpace())
3214 break;
3215
3216 // There might be sugar in the way. Strip it and try again.
3217 T = T.getSingleStepDesugaredType(*this);
3218 }
3219 }
3220
3221 Quals.removeAddressSpace();
3222
3223 // Removal of the address space can mean there are no longer any
3224 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3225 // or required.
3226 if (Quals.hasNonFastQualifiers())
3227 return getExtQualType(TypeNode, Quals);
3228 else
3229 return QualType(TypeNode, Quals.getFastQualifiers());
3230}
3231
3232uint16_t
3234 assert(RD->isPolymorphic() &&
3235 "Attempted to get vtable pointer discriminator on a monomorphic type");
3236 std::unique_ptr<MangleContext> MC(createMangleContext());
3237 SmallString<256> Str;
3238 llvm::raw_svector_ostream Out(Str);
3239 MC->mangleCXXVTable(RD, Out);
3240 return llvm::getPointerAuthStableSipHash(Str);
3241}
3242
3243/// Encode a function type for use in the discriminator of a function pointer
3244/// type. We can't use the itanium scheme for this since C has quite permissive
3245/// rules for type compatibility that we need to be compatible with.
3246///
3247/// Formally, this function associates every function pointer type T with an
3248/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3249/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3250/// compatibility requires equivalent treatment under the ABI, so
3251/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3252/// a subset of ~. Crucially, however, it must be a proper subset because
3253/// CCompatible is not an equivalence relation: for example, int[] is compatible
3254/// with both int[1] and int[2], but the latter are not compatible with each
3255/// other. Therefore this encoding function must be careful to only distinguish
3256/// types if there is no third type with which they are both required to be
3257/// compatible.
3259 raw_ostream &OS, QualType QT) {
3260 // FIXME: Consider address space qualifiers.
3261 const Type *T = QT.getCanonicalType().getTypePtr();
3262
3263 // FIXME: Consider using the C++ type mangling when we encounter a construct
3264 // that is incompatible with C.
3265
3266 switch (T->getTypeClass()) {
3267 case Type::Atomic:
3269 Ctx, OS, cast<AtomicType>(T)->getValueType());
3270
3271 case Type::LValueReference:
3272 OS << "R";
3275 return;
3276 case Type::RValueReference:
3277 OS << "O";
3280 return;
3281
3282 case Type::Pointer:
3283 // C11 6.7.6.1p2:
3284 // For two pointer types to be compatible, both shall be identically
3285 // qualified and both shall be pointers to compatible types.
3286 // FIXME: we should also consider pointee types.
3287 OS << "P";
3288 return;
3289
3290 case Type::ObjCObjectPointer:
3291 case Type::BlockPointer:
3292 OS << "P";
3293 return;
3294
3295 case Type::Complex:
3296 OS << "C";
3298 Ctx, OS, cast<ComplexType>(T)->getElementType());
3299
3300 case Type::VariableArray:
3301 case Type::ConstantArray:
3302 case Type::IncompleteArray:
3303 case Type::ArrayParameter:
3304 // C11 6.7.6.2p6:
3305 // For two array types to be compatible, both shall have compatible
3306 // element types, and if both size specifiers are present, and are integer
3307 // constant expressions, then both size specifiers shall have the same
3308 // constant value [...]
3309 //
3310 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3311 // width of the array.
3312 OS << "A";
3314 Ctx, OS, cast<ArrayType>(T)->getElementType());
3315
3316 case Type::ObjCInterface:
3317 case Type::ObjCObject:
3318 OS << "<objc_object>";
3319 return;
3320
3321 case Type::Enum: {
3322 // C11 6.7.2.2p4:
3323 // Each enumerated type shall be compatible with char, a signed integer
3324 // type, or an unsigned integer type.
3325 //
3326 // So we have to treat enum types as integers.
3327 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3329 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3330 }
3331
3332 case Type::FunctionNoProto:
3333 case Type::FunctionProto: {
3334 // C11 6.7.6.3p15:
3335 // For two function types to be compatible, both shall specify compatible
3336 // return types. Moreover, the parameter type lists, if both are present,
3337 // shall agree in the number of parameters and in the use of the ellipsis
3338 // terminator; corresponding parameters shall have compatible types.
3339 //
3340 // That paragraph goes on to describe how unprototyped functions are to be
3341 // handled, which we ignore here. Unprototyped function pointers are hashed
3342 // as though they were prototyped nullary functions since thats probably
3343 // what the user meant. This behavior is non-conforming.
3344 // FIXME: If we add a "custom discriminator" function type attribute we
3345 // should encode functions as their discriminators.
3346 OS << "F";
3347 const auto *FuncType = cast<FunctionType>(T);
3348 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3349 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3350 for (QualType Param : FPT->param_types()) {
3351 Param = Ctx.getSignatureParameterType(Param);
3352 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3353 }
3354 if (FPT->isVariadic())
3355 OS << "z";
3356 }
3357 OS << "E";
3358 return;
3359 }
3360
3361 case Type::MemberPointer: {
3362 OS << "M";
3363 const auto *MPT = T->castAs<MemberPointerType>();
3365 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3366 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3367 return;
3368 }
3369 case Type::ExtVector:
3370 case Type::Vector:
3371 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3372 break;
3373
3374 // Don't bother discriminating based on these types.
3375 case Type::Pipe:
3376 case Type::BitInt:
3377 case Type::ConstantMatrix:
3378 OS << "?";
3379 return;
3380
3381 case Type::Builtin: {
3382 const auto *BTy = T->castAs<BuiltinType>();
3383 switch (BTy->getKind()) {
3384#define SIGNED_TYPE(Id, SingletonId) \
3385 case BuiltinType::Id: \
3386 OS << "i"; \
3387 return;
3388#define UNSIGNED_TYPE(Id, SingletonId) \
3389 case BuiltinType::Id: \
3390 OS << "i"; \
3391 return;
3392#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3393#define BUILTIN_TYPE(Id, SingletonId)
3394#include "clang/AST/BuiltinTypes.def"
3395 llvm_unreachable("placeholder types should not appear here.");
3396
3397 case BuiltinType::Half:
3398 OS << "Dh";
3399 return;
3400 case BuiltinType::Float:
3401 OS << "f";
3402 return;
3403 case BuiltinType::Double:
3404 OS << "d";
3405 return;
3406 case BuiltinType::LongDouble:
3407 OS << "e";
3408 return;
3409 case BuiltinType::Float16:
3410 OS << "DF16_";
3411 return;
3412 case BuiltinType::Float128:
3413 OS << "g";
3414 return;
3415
3416 case BuiltinType::Void:
3417 OS << "v";
3418 return;
3419
3420 case BuiltinType::ObjCId:
3421 case BuiltinType::ObjCClass:
3422 case BuiltinType::ObjCSel:
3423 case BuiltinType::NullPtr:
3424 OS << "P";
3425 return;
3426
3427 // Don't bother discriminating based on OpenCL types.
3428 case BuiltinType::OCLSampler:
3429 case BuiltinType::OCLEvent:
3430 case BuiltinType::OCLClkEvent:
3431 case BuiltinType::OCLQueue:
3432 case BuiltinType::OCLReserveID:
3433 case BuiltinType::BFloat16:
3434 case BuiltinType::VectorQuad:
3435 case BuiltinType::VectorPair:
3436 case BuiltinType::DMR1024:
3437 case BuiltinType::DMR2048:
3438 OS << "?";
3439 return;
3440
3441 // Don't bother discriminating based on these seldom-used types.
3442 case BuiltinType::Ibm128:
3443 return;
3444#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3445 case BuiltinType::Id: \
3446 return;
3447#include "clang/Basic/OpenCLImageTypes.def"
3448#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3449 case BuiltinType::Id: \
3450 return;
3451#include "clang/Basic/OpenCLExtensionTypes.def"
3452#define SVE_TYPE(Name, Id, SingletonId) \
3453 case BuiltinType::Id: \
3454 return;
3455#include "clang/Basic/AArch64ACLETypes.def"
3456#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3457 case BuiltinType::Id: \
3458 return;
3459#include "clang/Basic/HLSLIntangibleTypes.def"
3460 case BuiltinType::Dependent:
3461 llvm_unreachable("should never get here");
3462#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3463#include "clang/Basic/AMDGPUTypes.def"
3464 case BuiltinType::WasmExternRef:
3465#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3466#include "clang/Basic/RISCVVTypes.def"
3467 llvm_unreachable("not yet implemented");
3468 }
3469 llvm_unreachable("should never get here");
3470 }
3471 case Type::Record: {
3472 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3473 const IdentifierInfo *II = RD->getIdentifier();
3474
3475 // In C++, an immediate typedef of an anonymous struct or union
3476 // is considered to name it for ODR purposes, but C's specification
3477 // of type compatibility does not have a similar rule. Using the typedef
3478 // name in function type discriminators anyway, as we do here,
3479 // therefore technically violates the C standard: two function pointer
3480 // types defined in terms of two typedef'd anonymous structs with
3481 // different names are formally still compatible, but we are assigning
3482 // them different discriminators and therefore incompatible ABIs.
3483 //
3484 // This is a relatively minor violation that significantly improves
3485 // discrimination in some cases and has not caused problems in
3486 // practice. Regardless, it is now part of the ABI in places where
3487 // function type discrimination is used, and it can no longer be
3488 // changed except on new platforms.
3489
3490 if (!II)
3491 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3492 II = Typedef->getDeclName().getAsIdentifierInfo();
3493
3494 if (!II) {
3495 OS << "<anonymous_record>";
3496 return;
3497 }
3498 OS << II->getLength() << II->getName();
3499 return;
3500 }
3501 case Type::HLSLAttributedResource:
3502 case Type::HLSLInlineSpirv:
3503 llvm_unreachable("should never get here");
3504 break;
3505 case Type::DeducedTemplateSpecialization:
3506 case Type::Auto:
3507#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3508#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3509#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3510#define ABSTRACT_TYPE(Class, Base)
3511#define TYPE(Class, Base)
3512#include "clang/AST/TypeNodes.inc"
3513 llvm_unreachable("unexpected non-canonical or dependent type!");
3514 return;
3515 }
3516}
3517
3519 assert(!T->isDependentType() &&
3520 "cannot compute type discriminator of a dependent type");
3521
3522 SmallString<256> Str;
3523 llvm::raw_svector_ostream Out(Str);
3524
3525 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3526 T = T->getPointeeType();
3527
3528 if (T->isFunctionType()) {
3530 } else {
3531 T = T.getUnqualifiedType();
3532 // Calls to member function pointers don't need to worry about
3533 // language interop or the laxness of the C type compatibility rules.
3534 // We just mangle the member pointer type directly, which is
3535 // implicitly much stricter about type matching. However, we do
3536 // strip any top-level exception specification before this mangling.
3537 // C++23 requires calls to work when the function type is convertible
3538 // to the pointer type by a function pointer conversion, which can
3539 // change the exception specification. This does not technically
3540 // require the exception specification to not affect representation,
3541 // because the function pointer conversion is still always a direct
3542 // value conversion and therefore an opportunity to resign the
3543 // pointer. (This is in contrast to e.g. qualification conversions,
3544 // which can be applied in nested pointer positions, effectively
3545 // requiring qualified and unqualified representations to match.)
3546 // However, it is pragmatic to ignore exception specifications
3547 // because it allows a certain amount of `noexcept` mismatching
3548 // to not become a visible ODR problem. This also leaves some
3549 // room for the committee to add laxness to function pointer
3550 // conversions in future standards.
3551 if (auto *MPT = T->getAs<MemberPointerType>())
3552 if (MPT->isMemberFunctionPointer()) {
3553 QualType PointeeType = MPT->getPointeeType();
3554 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3555 EST_None) {
3557 T = getMemberPointerType(FT, MPT->getQualifier(),
3558 MPT->getMostRecentCXXRecordDecl());
3559 }
3560 }
3561 std::unique_ptr<MangleContext> MC(createMangleContext());
3562 MC->mangleCanonicalTypeName(T, Out);
3563 }
3564
3565 return llvm::getPointerAuthStableSipHash(Str);
3566}
3567
3569 Qualifiers::GC GCAttr) const {
3570 QualType CanT = getCanonicalType(T);
3571 if (CanT.getObjCGCAttr() == GCAttr)
3572 return T;
3573
3574 if (const auto *ptr = T->getAs<PointerType>()) {
3575 QualType Pointee = ptr->getPointeeType();
3576 if (Pointee->isAnyPointerType()) {
3577 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3578 return getPointerType(ResultType);
3579 }
3580 }
3581
3582 // If we are composing extended qualifiers together, merge together
3583 // into one ExtQuals node.
3584 QualifierCollector Quals;
3585 const Type *TypeNode = Quals.strip(T);
3586
3587 // If this type already has an ObjCGC specified, it cannot get
3588 // another one.
3589 assert(!Quals.hasObjCGCAttr() &&
3590 "Type cannot have multiple ObjCGCs!");
3591 Quals.addObjCGCAttr(GCAttr);
3592
3593 return getExtQualType(TypeNode, Quals);
3594}
3595
3597 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3598 QualType Pointee = Ptr->getPointeeType();
3599 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3600 return getPointerType(removeAddrSpaceQualType(Pointee));
3601 }
3602 }
3603 return T;
3604}
3605
3607 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3608 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3609 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3610
3611 llvm::FoldingSetNodeID ID;
3612 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3613
3614 void *InsertPos = nullptr;
3615 CountAttributedType *CATy =
3616 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3617 if (CATy)
3618 return QualType(CATy, 0);
3619
3620 QualType CanonTy = getCanonicalType(WrappedTy);
3621 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3622 DependentDecls.size());
3624 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3625 OrNull, DependentDecls);
3626 Types.push_back(CATy);
3627 CountAttributedTypes.InsertNode(CATy, InsertPos);
3628
3629 return QualType(CATy, 0);
3630}
3631
3634 llvm::function_ref<QualType(QualType)> Adjust) const {
3635 switch (Orig->getTypeClass()) {
3636 case Type::Attributed: {
3637 const auto *AT = cast<AttributedType>(Orig);
3638 return getAttributedType(AT->getAttrKind(),
3639 adjustType(AT->getModifiedType(), Adjust),
3640 adjustType(AT->getEquivalentType(), Adjust),
3641 AT->getAttr());
3642 }
3643
3644 case Type::BTFTagAttributed: {
3645 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3646 return getBTFTagAttributedType(BTFT->getAttr(),
3647 adjustType(BTFT->getWrappedType(), Adjust));
3648 }
3649
3650 case Type::Paren:
3651 return getParenType(
3652 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3653
3654 case Type::Adjusted: {
3655 const auto *AT = cast<AdjustedType>(Orig);
3656 return getAdjustedType(AT->getOriginalType(),
3657 adjustType(AT->getAdjustedType(), Adjust));
3658 }
3659
3660 case Type::MacroQualified: {
3661 const auto *MQT = cast<MacroQualifiedType>(Orig);
3662 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3663 MQT->getMacroIdentifier());
3664 }
3665
3666 default:
3667 return Adjust(Orig);
3668 }
3669}
3670
3672 FunctionType::ExtInfo Info) {
3673 if (T->getExtInfo() == Info)
3674 return T;
3675
3677 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3678 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3679 } else {
3680 const auto *FPT = cast<FunctionProtoType>(T);
3681 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3682 EPI.ExtInfo = Info;
3683 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3684 }
3685
3686 return cast<FunctionType>(Result.getTypePtr());
3687}
3688
3690 QualType ResultType) {
3691 return adjustType(FunctionType, [&](QualType Orig) {
3692 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3693 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3694
3695 const auto *FPT = Orig->castAs<FunctionProtoType>();
3696 return getFunctionType(ResultType, FPT->getParamTypes(),
3697 FPT->getExtProtoInfo());
3698 });
3699}
3700
3702 QualType ResultType) {
3703 FD = FD->getMostRecentDecl();
3704 while (true) {
3705 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3706 if (FunctionDecl *Next = FD->getPreviousDecl())
3707 FD = Next;
3708 else
3709 break;
3710 }
3712 L->DeducedReturnType(FD, ResultType);
3713}
3714
3715/// Get a function type and produce the equivalent function type with the
3716/// specified exception specification. Type sugar that can be present on a
3717/// declaration of a function with an exception specification is permitted
3718/// and preserved. Other type sugar (for instance, typedefs) is not.
3720 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3721 return adjustType(Orig, [&](QualType Ty) {
3722 const auto *Proto = Ty->castAs<FunctionProtoType>();
3723 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3724 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3725 });
3726}
3727
3735
3737 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3738 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3739 SmallVector<QualType, 16> Args(Proto->param_types().size());
3740 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3741 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3742 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3743 }
3744
3745 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3746 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3747 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3748 }
3749
3750 return T;
3751}
3752
3758
3760 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3761 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3762 EPI.ExtParameterInfos = nullptr;
3763 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3764 }
3765 return T;
3766}
3767
3773
3776 bool AsWritten) {
3777 // Update the type.
3778 QualType Updated =
3780 FD->setType(Updated);
3781
3782 if (!AsWritten)
3783 return;
3784
3785 // Update the type in the type source information too.
3786 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3787 // If the type and the type-as-written differ, we may need to update
3788 // the type-as-written too.
3789 if (TSInfo->getType() != FD->getType())
3790 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3791
3792 // FIXME: When we get proper type location information for exceptions,
3793 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3794 // up the TypeSourceInfo;
3795 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3796 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3797 "TypeLoc size mismatch from updating exception specification");
3798 TSInfo->overrideType(Updated);
3799 }
3800}
3801
3802/// getComplexType - Return the uniqued reference to the type for a complex
3803/// number with the specified element type.
3805 // Unique pointers, to guarantee there is only one pointer of a particular
3806 // structure.
3807 llvm::FoldingSetNodeID ID;
3809
3810 void *InsertPos = nullptr;
3811 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3812 return QualType(CT, 0);
3813
3814 // If the pointee type isn't canonical, this won't be a canonical type either,
3815 // so fill in the canonical type field.
3816 QualType Canonical;
3817 if (!T.isCanonical()) {
3818 Canonical = getComplexType(getCanonicalType(T));
3819
3820 // Get the new insert position for the node we care about.
3821 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3822 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3823 }
3824 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3825 Types.push_back(New);
3826 ComplexTypes.InsertNode(New, InsertPos);
3827 return QualType(New, 0);
3828}
3829
3830/// getPointerType - Return the uniqued reference to the type for a pointer to
3831/// the specified type.
3833 // Unique pointers, to guarantee there is only one pointer of a particular
3834 // structure.
3835 llvm::FoldingSetNodeID ID;
3837
3838 void *InsertPos = nullptr;
3839 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3840 return QualType(PT, 0);
3841
3842 // If the pointee type isn't canonical, this won't be a canonical type either,
3843 // so fill in the canonical type field.
3844 QualType Canonical;
3845 if (!T.isCanonical()) {
3846 Canonical = getPointerType(getCanonicalType(T));
3847
3848 // Get the new insert position for the node we care about.
3849 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3850 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3851 }
3852 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3853 Types.push_back(New);
3854 PointerTypes.InsertNode(New, InsertPos);
3855 return QualType(New, 0);
3856}
3857
3859 llvm::FoldingSetNodeID ID;
3860 AdjustedType::Profile(ID, Orig, New);
3861 void *InsertPos = nullptr;
3862 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3863 if (AT)
3864 return QualType(AT, 0);
3865
3866 QualType Canonical = getCanonicalType(New);
3867
3868 // Get the new insert position for the node we care about.
3869 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3870 assert(!AT && "Shouldn't be in the map!");
3871
3872 AT = new (*this, alignof(AdjustedType))
3873 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3874 Types.push_back(AT);
3875 AdjustedTypes.InsertNode(AT, InsertPos);
3876 return QualType(AT, 0);
3877}
3878
3880 llvm::FoldingSetNodeID ID;
3881 AdjustedType::Profile(ID, Orig, Decayed);
3882 void *InsertPos = nullptr;
3883 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3884 if (AT)
3885 return QualType(AT, 0);
3886
3887 QualType Canonical = getCanonicalType(Decayed);
3888
3889 // Get the new insert position for the node we care about.
3890 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3891 assert(!AT && "Shouldn't be in the map!");
3892
3893 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3894 Types.push_back(AT);
3895 AdjustedTypes.InsertNode(AT, InsertPos);
3896 return QualType(AT, 0);
3897}
3898
3900 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3901
3902 QualType Decayed;
3903
3904 // C99 6.7.5.3p7:
3905 // A declaration of a parameter as "array of type" shall be
3906 // adjusted to "qualified pointer to type", where the type
3907 // qualifiers (if any) are those specified within the [ and ] of
3908 // the array type derivation.
3909 if (T->isArrayType())
3910 Decayed = getArrayDecayedType(T);
3911
3912 // C99 6.7.5.3p8:
3913 // A declaration of a parameter as "function returning type"
3914 // shall be adjusted to "pointer to function returning type", as
3915 // in 6.3.2.1.
3916 if (T->isFunctionType())
3917 Decayed = getPointerType(T);
3918
3919 return getDecayedType(T, Decayed);
3920}
3921
3923 if (Ty->isArrayParameterType())
3924 return Ty;
3925 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3926 QualType DTy = Ty.getDesugaredType(*this);
3927 const auto *ATy = cast<ConstantArrayType>(DTy);
3928 llvm::FoldingSetNodeID ID;
3929 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3930 ATy->getSizeExpr(), ATy->getSizeModifier(),
3931 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3932 void *InsertPos = nullptr;
3933 ArrayParameterType *AT =
3934 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3935 if (AT)
3936 return QualType(AT, 0);
3937
3938 QualType Canonical;
3939 if (!DTy.isCanonical()) {
3940 Canonical = getArrayParameterType(getCanonicalType(Ty));
3941
3942 // Get the new insert position for the node we care about.
3943 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
3944 assert(!AT && "Shouldn't be in the map!");
3945 }
3946
3947 AT = new (*this, alignof(ArrayParameterType))
3948 ArrayParameterType(ATy, Canonical);
3949 Types.push_back(AT);
3950 ArrayParameterTypes.InsertNode(AT, InsertPos);
3951 return QualType(AT, 0);
3952}
3953
3954/// getBlockPointerType - Return the uniqued reference to the type for
3955/// a pointer to the specified block.
3957 assert(T->isFunctionType() && "block of function types only");
3958 // Unique pointers, to guarantee there is only one block of a particular
3959 // structure.
3960 llvm::FoldingSetNodeID ID;
3962
3963 void *InsertPos = nullptr;
3964 if (BlockPointerType *PT =
3965 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3966 return QualType(PT, 0);
3967
3968 // If the block pointee type isn't canonical, this won't be a canonical
3969 // type either so fill in the canonical type field.
3970 QualType Canonical;
3971 if (!T.isCanonical()) {
3973
3974 // Get the new insert position for the node we care about.
3975 BlockPointerType *NewIP =
3976 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3977 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3978 }
3979 auto *New =
3980 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
3981 Types.push_back(New);
3982 BlockPointerTypes.InsertNode(New, InsertPos);
3983 return QualType(New, 0);
3984}
3985
3986/// getLValueReferenceType - Return the uniqued reference to the type for an
3987/// lvalue reference to the specified type.
3989ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3990 assert((!T->isPlaceholderType() ||
3991 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
3992 "Unresolved placeholder type");
3993
3994 // Unique pointers, to guarantee there is only one pointer of a particular
3995 // structure.
3996 llvm::FoldingSetNodeID ID;
3997 ReferenceType::Profile(ID, T, SpelledAsLValue);
3998
3999 void *InsertPos = nullptr;
4000 if (LValueReferenceType *RT =
4001 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4002 return QualType(RT, 0);
4003
4004 const auto *InnerRef = T->getAs<ReferenceType>();
4005
4006 // If the referencee type isn't canonical, this won't be a canonical type
4007 // either, so fill in the canonical type field.
4008 QualType Canonical;
4009 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4010 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4011 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4012
4013 // Get the new insert position for the node we care about.
4014 LValueReferenceType *NewIP =
4015 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4016 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4017 }
4018
4019 auto *New = new (*this, alignof(LValueReferenceType))
4020 LValueReferenceType(T, Canonical, SpelledAsLValue);
4021 Types.push_back(New);
4022 LValueReferenceTypes.InsertNode(New, InsertPos);
4023
4024 return QualType(New, 0);
4025}
4026
4027/// getRValueReferenceType - Return the uniqued reference to the type for an
4028/// rvalue reference to the specified type.
4030 assert((!T->isPlaceholderType() ||
4031 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4032 "Unresolved placeholder type");
4033
4034 // Unique pointers, to guarantee there is only one pointer of a particular
4035 // structure.
4036 llvm::FoldingSetNodeID ID;
4037 ReferenceType::Profile(ID, T, false);
4038
4039 void *InsertPos = nullptr;
4040 if (RValueReferenceType *RT =
4041 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4042 return QualType(RT, 0);
4043
4044 const auto *InnerRef = T->getAs<ReferenceType>();
4045
4046 // If the referencee type isn't canonical, this won't be a canonical type
4047 // either, so fill in the canonical type field.
4048 QualType Canonical;
4049 if (InnerRef || !T.isCanonical()) {
4050 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4051 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4052
4053 // Get the new insert position for the node we care about.
4054 RValueReferenceType *NewIP =
4055 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4056 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4057 }
4058
4059 auto *New = new (*this, alignof(RValueReferenceType))
4060 RValueReferenceType(T, Canonical);
4061 Types.push_back(New);
4062 RValueReferenceTypes.InsertNode(New, InsertPos);
4063 return QualType(New, 0);
4064}
4065
4067 NestedNameSpecifier Qualifier,
4068 const CXXRecordDecl *Cls) const {
4069 if (!Qualifier) {
4070 assert(Cls && "At least one of Qualifier or Cls must be provided");
4071 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4072 } else if (!Cls) {
4073 Cls = Qualifier.getAsRecordDecl();
4074 }
4075 // Unique pointers, to guarantee there is only one pointer of a particular
4076 // structure.
4077 llvm::FoldingSetNodeID ID;
4078 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4079
4080 void *InsertPos = nullptr;
4081 if (MemberPointerType *PT =
4082 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4083 return QualType(PT, 0);
4084
4085 NestedNameSpecifier CanonicalQualifier = [&] {
4086 if (!Cls)
4087 return Qualifier.getCanonical();
4088 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4089 assert(R.isCanonical());
4090 return R;
4091 }();
4092 // If the pointee or class type isn't canonical, this won't be a canonical
4093 // type either, so fill in the canonical type field.
4094 QualType Canonical;
4095 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4096 Canonical =
4097 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4098 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4099 // Get the new insert position for the node we care about.
4100 [[maybe_unused]] MemberPointerType *NewIP =
4101 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4102 assert(!NewIP && "Shouldn't be in the map!");
4103 }
4104 auto *New = new (*this, alignof(MemberPointerType))
4105 MemberPointerType(T, Qualifier, Canonical);
4106 Types.push_back(New);
4107 MemberPointerTypes.InsertNode(New, InsertPos);
4108 return QualType(New, 0);
4109}
4110
4111/// getConstantArrayType - Return the unique reference to the type for an
4112/// array of the specified element type.
4114 const llvm::APInt &ArySizeIn,
4115 const Expr *SizeExpr,
4117 unsigned IndexTypeQuals) const {
4118 assert((EltTy->isDependentType() ||
4119 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4120 "Constant array of VLAs is illegal!");
4121
4122 // We only need the size as part of the type if it's instantiation-dependent.
4123 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4124 SizeExpr = nullptr;
4125
4126 // Convert the array size into a canonical width matching the pointer size for
4127 // the target.
4128 llvm::APInt ArySize(ArySizeIn);
4129 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4130
4131 llvm::FoldingSetNodeID ID;
4132 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4133 ASM, IndexTypeQuals);
4134
4135 void *InsertPos = nullptr;
4136 if (ConstantArrayType *ATP =
4137 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4138 return QualType(ATP, 0);
4139
4140 // If the element type isn't canonical or has qualifiers, or the array bound
4141 // is instantiation-dependent, this won't be a canonical type either, so fill
4142 // in the canonical type field.
4143 QualType Canon;
4144 // FIXME: Check below should look for qualifiers behind sugar.
4145 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4146 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4147 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4148 ASM, IndexTypeQuals);
4149 Canon = getQualifiedType(Canon, canonSplit.Quals);
4150
4151 // Get the new insert position for the node we care about.
4152 ConstantArrayType *NewIP =
4153 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4154 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4155 }
4156
4157 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4158 ASM, IndexTypeQuals);
4159 ConstantArrayTypes.InsertNode(New, InsertPos);
4160 Types.push_back(New);
4161 return QualType(New, 0);
4162}
4163
4164/// getVariableArrayDecayedType - Turns the given type, which may be
4165/// variably-modified, into the corresponding type with all the known
4166/// sizes replaced with [*].
4168 // Vastly most common case.
4169 if (!type->isVariablyModifiedType()) return type;
4170
4171 QualType result;
4172
4173 SplitQualType split = type.getSplitDesugaredType();
4174 const Type *ty = split.Ty;
4175 switch (ty->getTypeClass()) {
4176#define TYPE(Class, Base)
4177#define ABSTRACT_TYPE(Class, Base)
4178#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4179#include "clang/AST/TypeNodes.inc"
4180 llvm_unreachable("didn't desugar past all non-canonical types?");
4181
4182 // These types should never be variably-modified.
4183 case Type::Builtin:
4184 case Type::Complex:
4185 case Type::Vector:
4186 case Type::DependentVector:
4187 case Type::ExtVector:
4188 case Type::DependentSizedExtVector:
4189 case Type::ConstantMatrix:
4190 case Type::DependentSizedMatrix:
4191 case Type::DependentAddressSpace:
4192 case Type::ObjCObject:
4193 case Type::ObjCInterface:
4194 case Type::ObjCObjectPointer:
4195 case Type::Record:
4196 case Type::Enum:
4197 case Type::UnresolvedUsing:
4198 case Type::TypeOfExpr:
4199 case Type::TypeOf:
4200 case Type::Decltype:
4201 case Type::UnaryTransform:
4202 case Type::DependentName:
4203 case Type::InjectedClassName:
4204 case Type::TemplateSpecialization:
4205 case Type::TemplateTypeParm:
4206 case Type::SubstTemplateTypeParmPack:
4207 case Type::SubstBuiltinTemplatePack:
4208 case Type::Auto:
4209 case Type::DeducedTemplateSpecialization:
4210 case Type::PackExpansion:
4211 case Type::PackIndexing:
4212 case Type::BitInt:
4213 case Type::DependentBitInt:
4214 case Type::ArrayParameter:
4215 case Type::HLSLAttributedResource:
4216 case Type::HLSLInlineSpirv:
4217 llvm_unreachable("type should never be variably-modified");
4218
4219 // These types can be variably-modified but should never need to
4220 // further decay.
4221 case Type::FunctionNoProto:
4222 case Type::FunctionProto:
4223 case Type::BlockPointer:
4224 case Type::MemberPointer:
4225 case Type::Pipe:
4226 return type;
4227
4228 // These types can be variably-modified. All these modifications
4229 // preserve structure except as noted by comments.
4230 // TODO: if we ever care about optimizing VLAs, there are no-op
4231 // optimizations available here.
4232 case Type::Pointer:
4235 break;
4236
4237 case Type::LValueReference: {
4238 const auto *lv = cast<LValueReferenceType>(ty);
4239 result = getLValueReferenceType(
4240 getVariableArrayDecayedType(lv->getPointeeType()),
4241 lv->isSpelledAsLValue());
4242 break;
4243 }
4244
4245 case Type::RValueReference: {
4246 const auto *lv = cast<RValueReferenceType>(ty);
4247 result = getRValueReferenceType(
4248 getVariableArrayDecayedType(lv->getPointeeType()));
4249 break;
4250 }
4251
4252 case Type::Atomic: {
4253 const auto *at = cast<AtomicType>(ty);
4254 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4255 break;
4256 }
4257
4258 case Type::ConstantArray: {
4259 const auto *cat = cast<ConstantArrayType>(ty);
4260 result = getConstantArrayType(
4261 getVariableArrayDecayedType(cat->getElementType()),
4262 cat->getSize(),
4263 cat->getSizeExpr(),
4264 cat->getSizeModifier(),
4265 cat->getIndexTypeCVRQualifiers());
4266 break;
4267 }
4268
4269 case Type::DependentSizedArray: {
4270 const auto *dat = cast<DependentSizedArrayType>(ty);
4272 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4273 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4274 break;
4275 }
4276
4277 // Turn incomplete types into [*] types.
4278 case Type::IncompleteArray: {
4279 const auto *iat = cast<IncompleteArrayType>(ty);
4280 result =
4282 /*size*/ nullptr, ArraySizeModifier::Normal,
4283 iat->getIndexTypeCVRQualifiers());
4284 break;
4285 }
4286
4287 // Turn VLA types into [*] types.
4288 case Type::VariableArray: {
4289 const auto *vat = cast<VariableArrayType>(ty);
4290 result =
4292 /*size*/ nullptr, ArraySizeModifier::Star,
4293 vat->getIndexTypeCVRQualifiers());
4294 break;
4295 }
4296 }
4297
4298 // Apply the top-level qualifiers from the original.
4299 return getQualifiedType(result, split.Quals);
4300}
4301
4302/// getVariableArrayType - Returns a non-unique reference to the type for a
4303/// variable array of the specified element type.
4306 unsigned IndexTypeQuals) const {
4307 // Since we don't unique expressions, it isn't possible to unique VLA's
4308 // that have an expression provided for their size.
4309 QualType Canon;
4310
4311 // Be sure to pull qualifiers off the element type.
4312 // FIXME: Check below should look for qualifiers behind sugar.
4313 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4314 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4315 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4316 IndexTypeQuals);
4317 Canon = getQualifiedType(Canon, canonSplit.Quals);
4318 }
4319
4320 auto *New = new (*this, alignof(VariableArrayType))
4321 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4322
4323 VariableArrayTypes.push_back(New);
4324 Types.push_back(New);
4325 return QualType(New, 0);
4326}
4327
4328/// getDependentSizedArrayType - Returns a non-unique reference to
4329/// the type for a dependently-sized array of the specified element
4330/// type.
4334 unsigned elementTypeQuals) const {
4335 assert((!numElements || numElements->isTypeDependent() ||
4336 numElements->isValueDependent()) &&
4337 "Size must be type- or value-dependent!");
4338
4339 SplitQualType canonElementType = getCanonicalType(elementType).split();
4340
4341 void *insertPos = nullptr;
4342 llvm::FoldingSetNodeID ID;
4344 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4345 ASM, elementTypeQuals, numElements);
4346
4347 // Look for an existing type with these properties.
4348 DependentSizedArrayType *canonTy =
4349 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4350
4351 // Dependently-sized array types that do not have a specified number
4352 // of elements will have their sizes deduced from a dependent
4353 // initializer.
4354 if (!numElements) {
4355 if (canonTy)
4356 return QualType(canonTy, 0);
4357
4358 auto *newType = new (*this, alignof(DependentSizedArrayType))
4359 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4360 elementTypeQuals);
4361 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4362 Types.push_back(newType);
4363 return QualType(newType, 0);
4364 }
4365
4366 // If we don't have one, build one.
4367 if (!canonTy) {
4368 canonTy = new (*this, alignof(DependentSizedArrayType))
4369 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4370 numElements, ASM, elementTypeQuals);
4371 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4372 Types.push_back(canonTy);
4373 }
4374
4375 // Apply qualifiers from the element type to the array.
4376 QualType canon = getQualifiedType(QualType(canonTy,0),
4377 canonElementType.Quals);
4378
4379 // If we didn't need extra canonicalization for the element type or the size
4380 // expression, then just use that as our result.
4381 if (QualType(canonElementType.Ty, 0) == elementType &&
4382 canonTy->getSizeExpr() == numElements)
4383 return canon;
4384
4385 // Otherwise, we need to build a type which follows the spelling
4386 // of the element type.
4387 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4388 DependentSizedArrayType(elementType, canon, numElements, ASM,
4389 elementTypeQuals);
4390 Types.push_back(sugaredType);
4391 return QualType(sugaredType, 0);
4392}
4393
4396 unsigned elementTypeQuals) const {
4397 llvm::FoldingSetNodeID ID;
4398 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4399
4400 void *insertPos = nullptr;
4401 if (IncompleteArrayType *iat =
4402 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4403 return QualType(iat, 0);
4404
4405 // If the element type isn't canonical, this won't be a canonical type
4406 // either, so fill in the canonical type field. We also have to pull
4407 // qualifiers off the element type.
4408 QualType canon;
4409
4410 // FIXME: Check below should look for qualifiers behind sugar.
4411 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4412 SplitQualType canonSplit = getCanonicalType(elementType).split();
4413 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4414 ASM, elementTypeQuals);
4415 canon = getQualifiedType(canon, canonSplit.Quals);
4416
4417 // Get the new insert position for the node we care about.
4418 IncompleteArrayType *existing =
4419 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4420 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4421 }
4422
4423 auto *newType = new (*this, alignof(IncompleteArrayType))
4424 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4425
4426 IncompleteArrayTypes.InsertNode(newType, insertPos);
4427 Types.push_back(newType);
4428 return QualType(newType, 0);
4429}
4430
4433#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4434 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4435 NUMVECTORS};
4436
4437#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4438 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4439
4440 switch (Ty->getKind()) {
4441 default:
4442 llvm_unreachable("Unsupported builtin vector type");
4443
4444#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4445 ElBits, NF, IsSigned) \
4446 case BuiltinType::Id: \
4447 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4448 llvm::ElementCount::getScalable(NumEls), NF};
4449#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4450 ElBits, NF) \
4451 case BuiltinType::Id: \
4452 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4453 llvm::ElementCount::getScalable(NumEls), NF};
4454#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4455 ElBits, NF) \
4456 case BuiltinType::Id: \
4457 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4458#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4459 ElBits, NF) \
4460 case BuiltinType::Id: \
4461 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4462#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4463 case BuiltinType::Id: \
4464 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4465#include "clang/Basic/AArch64ACLETypes.def"
4466
4467#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4468 IsSigned) \
4469 case BuiltinType::Id: \
4470 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4471 llvm::ElementCount::getScalable(NumEls), NF};
4472#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4473 case BuiltinType::Id: \
4474 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4475 llvm::ElementCount::getScalable(NumEls), NF};
4476#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4477 case BuiltinType::Id: \
4478 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4479#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4480 case BuiltinType::Id: \
4481 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4482#include "clang/Basic/RISCVVTypes.def"
4483 }
4484}
4485
4486/// getExternrefType - Return a WebAssembly externref type, which represents an
4487/// opaque reference to a host value.
4489 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4490#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4491 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4492 return SingletonId;
4493#include "clang/Basic/WebAssemblyReferenceTypes.def"
4494 }
4495 llvm_unreachable(
4496 "shouldn't try to generate type externref outside WebAssembly target");
4497}
4498
4499/// getScalableVectorType - Return the unique reference to a scalable vector
4500/// type of the specified element type and size. VectorType must be a built-in
4501/// type.
4503 unsigned NumFields) const {
4504 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4505 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4506 return It->second;
4507
4508 if (Target->hasAArch64ACLETypes()) {
4509 uint64_t EltTySize = getTypeSize(EltTy);
4510
4511#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4512 ElBits, NF, IsSigned) \
4513 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4514 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4515 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4516 return ScalableVecTyMap[K] = SingletonId; \
4517 }
4518#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4519 ElBits, NF) \
4520 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4521 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4522 return ScalableVecTyMap[K] = SingletonId; \
4523 }
4524#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4525 ElBits, NF) \
4526 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4527 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4528 return ScalableVecTyMap[K] = SingletonId; \
4529 }
4530#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4531 ElBits, NF) \
4532 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4533 NumElts == (NumEls * NF) && NumFields == 1) { \
4534 return ScalableVecTyMap[K] = SingletonId; \
4535 }
4536#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4537 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4538 return ScalableVecTyMap[K] = SingletonId;
4539#include "clang/Basic/AArch64ACLETypes.def"
4540 } else if (Target->hasRISCVVTypes()) {
4541 uint64_t EltTySize = getTypeSize(EltTy);
4542#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4543 IsFP, IsBF) \
4544 if (!EltTy->isBooleanType() && \
4545 ((EltTy->hasIntegerRepresentation() && \
4546 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4547 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4548 IsFP && !IsBF) || \
4549 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4550 IsBF && !IsFP)) && \
4551 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4552 return ScalableVecTyMap[K] = SingletonId;
4553#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4554 if (EltTy->isBooleanType() && NumElts == NumEls) \
4555 return ScalableVecTyMap[K] = SingletonId;
4556#include "clang/Basic/RISCVVTypes.def"
4557 }
4558 return QualType();
4559}
4560
4561/// getVectorType - Return the unique reference to a vector type of
4562/// the specified element type and size. VectorType must be a built-in type.
4564 VectorKind VecKind) const {
4565 assert(vecType->isBuiltinType() ||
4566 (vecType->isBitIntType() &&
4567 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4568 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4569
4570 // Check if we've already instantiated a vector of this type.
4571 llvm::FoldingSetNodeID ID;
4572 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4573
4574 void *InsertPos = nullptr;
4575 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4576 return QualType(VTP, 0);
4577
4578 // If the element type isn't canonical, this won't be a canonical type either,
4579 // so fill in the canonical type field.
4580 QualType Canonical;
4581 if (!vecType.isCanonical()) {
4582 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4583
4584 // Get the new insert position for the node we care about.
4585 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4586 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4587 }
4588 auto *New = new (*this, alignof(VectorType))
4589 VectorType(vecType, NumElts, Canonical, VecKind);
4590 VectorTypes.InsertNode(New, InsertPos);
4591 Types.push_back(New);
4592 return QualType(New, 0);
4593}
4594
4596 SourceLocation AttrLoc,
4597 VectorKind VecKind) const {
4598 llvm::FoldingSetNodeID ID;
4599 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4600 VecKind);
4601 void *InsertPos = nullptr;
4602 DependentVectorType *Canon =
4603 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4605
4606 if (Canon) {
4607 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4608 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4609 } else {
4610 QualType CanonVecTy = getCanonicalType(VecType);
4611 if (CanonVecTy == VecType) {
4612 New = new (*this, alignof(DependentVectorType))
4613 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4614
4615 DependentVectorType *CanonCheck =
4616 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4617 assert(!CanonCheck &&
4618 "Dependent-sized vector_size canonical type broken");
4619 (void)CanonCheck;
4620 DependentVectorTypes.InsertNode(New, InsertPos);
4621 } else {
4622 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4623 SourceLocation(), VecKind);
4624 New = new (*this, alignof(DependentVectorType))
4625 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4626 }
4627 }
4628
4629 Types.push_back(New);
4630 return QualType(New, 0);
4631}
4632
4633/// getExtVectorType - Return the unique reference to an extended vector type of
4634/// the specified element type and size. VectorType must be a built-in type.
4636 unsigned NumElts) const {
4637 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4638 (vecType->isBitIntType() &&
4639 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4640 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4641
4642 // Check if we've already instantiated a vector of this type.
4643 llvm::FoldingSetNodeID ID;
4644 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4646 void *InsertPos = nullptr;
4647 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4648 return QualType(VTP, 0);
4649
4650 // If the element type isn't canonical, this won't be a canonical type either,
4651 // so fill in the canonical type field.
4652 QualType Canonical;
4653 if (!vecType.isCanonical()) {
4654 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4655
4656 // Get the new insert position for the node we care about.
4657 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4658 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4659 }
4660 auto *New = new (*this, alignof(ExtVectorType))
4661 ExtVectorType(vecType, NumElts, Canonical);
4662 VectorTypes.InsertNode(New, InsertPos);
4663 Types.push_back(New);
4664 return QualType(New, 0);
4665}
4666
4669 Expr *SizeExpr,
4670 SourceLocation AttrLoc) const {
4671 llvm::FoldingSetNodeID ID;
4673 SizeExpr);
4674
4675 void *InsertPos = nullptr;
4677 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4679 if (Canon) {
4680 // We already have a canonical version of this array type; use it as
4681 // the canonical type for a newly-built type.
4682 New = new (*this, alignof(DependentSizedExtVectorType))
4683 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4684 AttrLoc);
4685 } else {
4686 QualType CanonVecTy = getCanonicalType(vecType);
4687 if (CanonVecTy == vecType) {
4688 New = new (*this, alignof(DependentSizedExtVectorType))
4689 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4690
4691 DependentSizedExtVectorType *CanonCheck
4692 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4693 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4694 (void)CanonCheck;
4695 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4696 } else {
4697 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4698 SourceLocation());
4699 New = new (*this, alignof(DependentSizedExtVectorType))
4700 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4701 }
4702 }
4703
4704 Types.push_back(New);
4705 return QualType(New, 0);
4706}
4707
4709 unsigned NumColumns) const {
4710 llvm::FoldingSetNodeID ID;
4711 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4712 Type::ConstantMatrix);
4713
4714 assert(MatrixType::isValidElementType(ElementTy) &&
4715 "need a valid element type");
4716 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4718 "need valid matrix dimensions");
4719 void *InsertPos = nullptr;
4720 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4721 return QualType(MTP, 0);
4722
4723 QualType Canonical;
4724 if (!ElementTy.isCanonical()) {
4725 Canonical =
4726 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4727
4728 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4729 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4730 (void)NewIP;
4731 }
4732
4733 auto *New = new (*this, alignof(ConstantMatrixType))
4734 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4735 MatrixTypes.InsertNode(New, InsertPos);
4736 Types.push_back(New);
4737 return QualType(New, 0);
4738}
4739
4741 Expr *RowExpr,
4742 Expr *ColumnExpr,
4743 SourceLocation AttrLoc) const {
4744 QualType CanonElementTy = getCanonicalType(ElementTy);
4745 llvm::FoldingSetNodeID ID;
4746 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4747 ColumnExpr);
4748
4749 void *InsertPos = nullptr;
4751 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4752
4753 if (!Canon) {
4754 Canon = new (*this, alignof(DependentSizedMatrixType))
4755 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4756 ColumnExpr, AttrLoc);
4757#ifndef NDEBUG
4758 DependentSizedMatrixType *CanonCheck =
4759 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4760 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4761#endif
4762 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4763 Types.push_back(Canon);
4764 }
4765
4766 // Already have a canonical version of the matrix type
4767 //
4768 // If it exactly matches the requested type, use it directly.
4769 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4770 Canon->getRowExpr() == ColumnExpr)
4771 return QualType(Canon, 0);
4772
4773 // Use Canon as the canonical type for newly-built type.
4775 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4776 ColumnExpr, AttrLoc);
4777 Types.push_back(New);
4778 return QualType(New, 0);
4779}
4780
4782 Expr *AddrSpaceExpr,
4783 SourceLocation AttrLoc) const {
4784 assert(AddrSpaceExpr->isInstantiationDependent());
4785
4786 QualType canonPointeeType = getCanonicalType(PointeeType);
4787
4788 void *insertPos = nullptr;
4789 llvm::FoldingSetNodeID ID;
4790 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4791 AddrSpaceExpr);
4792
4793 DependentAddressSpaceType *canonTy =
4794 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4795
4796 if (!canonTy) {
4797 canonTy = new (*this, alignof(DependentAddressSpaceType))
4798 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4799 AttrLoc);
4800 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4801 Types.push_back(canonTy);
4802 }
4803
4804 if (canonPointeeType == PointeeType &&
4805 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4806 return QualType(canonTy, 0);
4807
4808 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4809 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4810 AddrSpaceExpr, AttrLoc);
4811 Types.push_back(sugaredType);
4812 return QualType(sugaredType, 0);
4813}
4814
4815/// Determine whether \p T is canonical as the result type of a function.
4817 return T.isCanonical() &&
4818 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4819 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4820}
4821
4822/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4823QualType
4825 const FunctionType::ExtInfo &Info) const {
4826 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4827 // functionality creates a function without a prototype regardless of
4828 // language mode (so it makes them even in C++). Once the rewriter has been
4829 // fixed, this assertion can be enabled again.
4830 //assert(!LangOpts.requiresStrictPrototypes() &&
4831 // "strict prototypes are disabled");
4832
4833 // Unique functions, to guarantee there is only one function of a particular
4834 // structure.
4835 llvm::FoldingSetNodeID ID;
4836 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4837
4838 void *InsertPos = nullptr;
4839 if (FunctionNoProtoType *FT =
4840 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4841 return QualType(FT, 0);
4842
4843 QualType Canonical;
4844 if (!isCanonicalResultType(ResultTy)) {
4845 Canonical =
4847
4848 // Get the new insert position for the node we care about.
4849 FunctionNoProtoType *NewIP =
4850 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4851 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4852 }
4853
4854 auto *New = new (*this, alignof(FunctionNoProtoType))
4855 FunctionNoProtoType(ResultTy, Canonical, Info);
4856 Types.push_back(New);
4857 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4858 return QualType(New, 0);
4859}
4860
4863 CanQualType CanResultType = getCanonicalType(ResultType);
4864
4865 // Canonical result types do not have ARC lifetime qualifiers.
4866 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4867 Qualifiers Qs = CanResultType.getQualifiers();
4868 Qs.removeObjCLifetime();
4870 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4871 }
4872
4873 return CanResultType;
4874}
4875
4877 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4878 if (ESI.Type == EST_None)
4879 return true;
4880 if (!NoexceptInType)
4881 return false;
4882
4883 // C++17 onwards: exception specification is part of the type, as a simple
4884 // boolean "can this function type throw".
4885 if (ESI.Type == EST_BasicNoexcept)
4886 return true;
4887
4888 // A noexcept(expr) specification is (possibly) canonical if expr is
4889 // value-dependent.
4890 if (ESI.Type == EST_DependentNoexcept)
4891 return true;
4892
4893 // A dynamic exception specification is canonical if it only contains pack
4894 // expansions (so we can't tell whether it's non-throwing) and all its
4895 // contained types are canonical.
4896 if (ESI.Type == EST_Dynamic) {
4897 bool AnyPackExpansions = false;
4898 for (QualType ET : ESI.Exceptions) {
4899 if (!ET.isCanonical())
4900 return false;
4901 if (ET->getAs<PackExpansionType>())
4902 AnyPackExpansions = true;
4903 }
4904 return AnyPackExpansions;
4905 }
4906
4907 return false;
4908}
4909
4910QualType ASTContext::getFunctionTypeInternal(
4911 QualType ResultTy, ArrayRef<QualType> ArgArray,
4912 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4913 size_t NumArgs = ArgArray.size();
4914
4915 // Unique functions, to guarantee there is only one function of a particular
4916 // structure.
4917 llvm::FoldingSetNodeID ID;
4918 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4919 *this, true);
4920
4921 QualType Canonical;
4922 bool Unique = false;
4923
4924 void *InsertPos = nullptr;
4925 if (FunctionProtoType *FPT =
4926 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4927 QualType Existing = QualType(FPT, 0);
4928
4929 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4930 // it so long as our exception specification doesn't contain a dependent
4931 // noexcept expression, or we're just looking for a canonical type.
4932 // Otherwise, we're going to need to create a type
4933 // sugar node to hold the concrete expression.
4934 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4935 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4936 return Existing;
4937
4938 // We need a new type sugar node for this one, to hold the new noexcept
4939 // expression. We do no canonicalization here, but that's OK since we don't
4940 // expect to see the same noexcept expression much more than once.
4941 Canonical = getCanonicalType(Existing);
4942 Unique = true;
4943 }
4944
4945 bool NoexceptInType = getLangOpts().CPlusPlus17;
4946 bool IsCanonicalExceptionSpec =
4948
4949 // Determine whether the type being created is already canonical or not.
4950 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4951 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4952 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4953 if (!ArgArray[i].isCanonicalAsParam())
4954 isCanonical = false;
4955
4956 if (OnlyWantCanonical)
4957 assert(isCanonical &&
4958 "given non-canonical parameters constructing canonical type");
4959
4960 // If this type isn't canonical, get the canonical version of it if we don't
4961 // already have it. The exception spec is only partially part of the
4962 // canonical type, and only in C++17 onwards.
4963 if (!isCanonical && Canonical.isNull()) {
4964 SmallVector<QualType, 16> CanonicalArgs;
4965 CanonicalArgs.reserve(NumArgs);
4966 for (unsigned i = 0; i != NumArgs; ++i)
4967 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4968
4969 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4970 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4971 CanonicalEPI.HasTrailingReturn = false;
4972
4973 if (IsCanonicalExceptionSpec) {
4974 // Exception spec is already OK.
4975 } else if (NoexceptInType) {
4976 switch (EPI.ExceptionSpec.Type) {
4978 // We don't know yet. It shouldn't matter what we pick here; no-one
4979 // should ever look at this.
4980 [[fallthrough]];
4981 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4982 CanonicalEPI.ExceptionSpec.Type = EST_None;
4983 break;
4984
4985 // A dynamic exception specification is almost always "not noexcept",
4986 // with the exception that a pack expansion might expand to no types.
4987 case EST_Dynamic: {
4988 bool AnyPacks = false;
4989 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4990 if (ET->getAs<PackExpansionType>())
4991 AnyPacks = true;
4992 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4993 }
4994 if (!AnyPacks)
4995 CanonicalEPI.ExceptionSpec.Type = EST_None;
4996 else {
4997 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4998 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4999 }
5000 break;
5001 }
5002
5003 case EST_DynamicNone:
5004 case EST_BasicNoexcept:
5005 case EST_NoexceptTrue:
5006 case EST_NoThrow:
5007 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5008 break;
5009
5011 llvm_unreachable("dependent noexcept is already canonical");
5012 }
5013 } else {
5014 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5015 }
5016
5017 // Adjust the canonical function result type.
5018 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5019 Canonical =
5020 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5021
5022 // Get the new insert position for the node we care about.
5023 FunctionProtoType *NewIP =
5024 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5025 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5026 }
5027
5028 // Compute the needed size to hold this FunctionProtoType and the
5029 // various trailing objects.
5030 auto ESH = FunctionProtoType::getExceptionSpecSize(
5031 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5032 size_t Size = FunctionProtoType::totalSizeToAlloc<
5033 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5034 FunctionType::FunctionTypeExtraAttributeInfo,
5035 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5036 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5037 FunctionEffect, EffectConditionExpr>(
5040 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5041 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5042 EPI.ExtParameterInfos ? NumArgs : 0,
5044 EPI.FunctionEffects.conditions().size());
5045
5046 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5047 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5048 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5049 Types.push_back(FTP);
5050 if (!Unique)
5051 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5052 if (!EPI.FunctionEffects.empty())
5053 AnyFunctionEffects = true;
5054 return QualType(FTP, 0);
5055}
5056
5057QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5058 llvm::FoldingSetNodeID ID;
5059 PipeType::Profile(ID, T, ReadOnly);
5060
5061 void *InsertPos = nullptr;
5062 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5063 return QualType(PT, 0);
5064
5065 // If the pipe element type isn't canonical, this won't be a canonical type
5066 // either, so fill in the canonical type field.
5067 QualType Canonical;
5068 if (!T.isCanonical()) {
5069 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5070
5071 // Get the new insert position for the node we care about.
5072 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5073 assert(!NewIP && "Shouldn't be in the map!");
5074 (void)NewIP;
5075 }
5076 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5077 Types.push_back(New);
5078 PipeTypes.InsertNode(New, InsertPos);
5079 return QualType(New, 0);
5080}
5081
5083 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5084 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5085 : Ty;
5086}
5087
5089 return getPipeType(T, true);
5090}
5091
5093 return getPipeType(T, false);
5094}
5095
5096QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5097 llvm::FoldingSetNodeID ID;
5098 BitIntType::Profile(ID, IsUnsigned, NumBits);
5099
5100 void *InsertPos = nullptr;
5101 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5102 return QualType(EIT, 0);
5103
5104 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5105 BitIntTypes.InsertNode(New, InsertPos);
5106 Types.push_back(New);
5107 return QualType(New, 0);
5108}
5109
5111 Expr *NumBitsExpr) const {
5112 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5113 llvm::FoldingSetNodeID ID;
5114 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5115
5116 void *InsertPos = nullptr;
5117 if (DependentBitIntType *Existing =
5118 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5119 return QualType(Existing, 0);
5120
5121 auto *New = new (*this, alignof(DependentBitIntType))
5122 DependentBitIntType(IsUnsigned, NumBitsExpr);
5123 DependentBitIntTypes.InsertNode(New, InsertPos);
5124
5125 Types.push_back(New);
5126 return QualType(New, 0);
5127}
5128
5131 using Kind = PredefinedSugarType::Kind;
5132
5133 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5134 Target != nullptr)
5135 return QualType(Target, 0);
5136
5137 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5138 switch (KDI) {
5139 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5140 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5141 // are part of the core language and are widely used. Using
5142 // PredefinedSugarType makes these types as named sugar types rather than
5143 // standard integer types, enabling better hints and diagnostics.
5144 case Kind::SizeT:
5145 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5146 case Kind::SignedSizeT:
5147 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5148 case Kind::PtrdiffT:
5149 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5150 }
5151 llvm_unreachable("unexpected kind");
5152 };
5153 auto *New = new (*this, alignof(PredefinedSugarType))
5154 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5155 getCanonicalType(*this, static_cast<Kind>(KD)));
5156 Types.push_back(New);
5157 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5158 return QualType(New, 0);
5159}
5160
5162 NestedNameSpecifier Qualifier,
5163 const TypeDecl *Decl) const {
5164 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5165 return getTagType(Keyword, Qualifier, Tag,
5166 /*OwnsTag=*/false);
5167 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5168 return getTypedefType(Keyword, Qualifier, Typedef);
5169 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5170 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5171
5173 assert(!Qualifier);
5174 return QualType(Decl->TypeForDecl, 0);
5175}
5176
5178 if (auto *Tag = dyn_cast<TagDecl>(TD))
5179 return getCanonicalTagType(Tag);
5180 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5181 return getCanonicalType(TN->getUnderlyingType());
5182 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5184 assert(TD->TypeForDecl);
5185 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5186}
5187
5189 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5190 return getCanonicalTagType(TD);
5191 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5192 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5194 /*Qualifier=*/std::nullopt, TD);
5195 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5196 return getCanonicalUnresolvedUsingType(Using);
5197
5198 assert(Decl->TypeForDecl);
5199 return QualType(Decl->TypeForDecl, 0);
5200}
5201
5202/// getTypedefType - Return the unique reference to the type for the
5203/// specified typedef name decl.
5206 NestedNameSpecifier Qualifier,
5207 const TypedefNameDecl *Decl, QualType UnderlyingType,
5208 std::optional<bool> TypeMatchesDeclOrNone) const {
5209 if (!TypeMatchesDeclOrNone) {
5210 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5211 assert(!DeclUnderlyingType.isNull());
5212 if (UnderlyingType.isNull())
5213 UnderlyingType = DeclUnderlyingType;
5214 else
5215 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5216 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5217 } else {
5218 // FIXME: This is a workaround for a serialization cycle: assume the decl
5219 // underlying type is not available; don't touch it.
5220 assert(!UnderlyingType.isNull());
5221 }
5222
5223 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5224 *TypeMatchesDeclOrNone) {
5225 if (Decl->TypeForDecl)
5226 return QualType(Decl->TypeForDecl, 0);
5227
5228 auto *NewType = new (*this, alignof(TypedefType))
5229 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5230 !*TypeMatchesDeclOrNone);
5231
5232 Types.push_back(NewType);
5233 Decl->TypeForDecl = NewType;
5234 return QualType(NewType, 0);
5235 }
5236
5237 llvm::FoldingSetNodeID ID;
5238 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5239 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5240
5241 void *InsertPos = nullptr;
5242 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5243 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5244 return QualType(Placeholder->getType(), 0);
5245
5246 void *Mem =
5247 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5249 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5250 alignof(TypedefType));
5251 auto *NewType =
5252 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5253 UnderlyingType, !*TypeMatchesDeclOrNone);
5254 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5256 TypedefTypes.InsertNode(Placeholder, InsertPos);
5257 Types.push_back(NewType);
5258 return QualType(NewType, 0);
5259}
5260
5262 NestedNameSpecifier Qualifier,
5263 const UsingShadowDecl *D,
5264 QualType UnderlyingType) const {
5265 // FIXME: This is expensive to compute every time!
5266 if (UnderlyingType.isNull()) {
5267 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5268 UnderlyingType =
5271 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5272 }
5273
5274 llvm::FoldingSetNodeID ID;
5275 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5276
5277 void *InsertPos = nullptr;
5278 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5279 return QualType(T, 0);
5280
5281 assert(!UnderlyingType.hasLocalQualifiers());
5282
5283 assert(
5285 UnderlyingType));
5286
5287 void *Mem =
5288 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5289 alignof(UsingType));
5290 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5291 Types.push_back(T);
5292 UsingTypes.InsertNode(T, InsertPos);
5293 return QualType(T, 0);
5294}
5295
5296TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5297 NestedNameSpecifier Qualifier,
5298 const TagDecl *TD, bool OwnsTag,
5299 bool IsInjected,
5300 const Type *CanonicalType,
5301 bool WithFoldingSetNode) const {
5302 auto [TC, Size] = [&] {
5303 switch (TD->getDeclKind()) {
5304 case Decl::Enum:
5305 static_assert(alignof(EnumType) == alignof(TagType));
5306 return std::make_tuple(Type::Enum, sizeof(EnumType));
5307 case Decl::ClassTemplatePartialSpecialization:
5308 case Decl::ClassTemplateSpecialization:
5309 case Decl::CXXRecord:
5310 static_assert(alignof(RecordType) == alignof(TagType));
5311 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5312 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5313 return std::make_tuple(Type::InjectedClassName,
5314 sizeof(InjectedClassNameType));
5315 [[fallthrough]];
5316 case Decl::Record:
5317 return std::make_tuple(Type::Record, sizeof(RecordType));
5318 default:
5319 llvm_unreachable("unexpected decl kind");
5320 }
5321 }();
5322
5323 if (Qualifier) {
5324 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5325 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5326 sizeof(NestedNameSpecifier);
5327 }
5328 void *Mem;
5329 if (WithFoldingSetNode) {
5330 // FIXME: It would be more profitable to tail allocate the folding set node
5331 // from the type, instead of the other way around, due to the greater
5332 // alignment requirements of the type. But this makes it harder to deal with
5333 // the different type node sizes. This would require either uniquing from
5334 // different folding sets, or having the folding setaccept a
5335 // contextual parameter which is not fixed at construction.
5336 Mem = Allocate(
5337 sizeof(TagTypeFoldingSetPlaceholder) +
5338 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5339 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5340 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5341 Mem = T->getTagType();
5342 } else {
5343 Mem = Allocate(Size, alignof(TagType));
5344 }
5345
5346 auto *T = [&, TC = TC]() -> TagType * {
5347 switch (TC) {
5348 case Type::Enum: {
5349 assert(isa<EnumDecl>(TD));
5350 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5351 IsInjected, CanonicalType);
5352 assert(reinterpret_cast<void *>(T) ==
5353 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5354 "TagType must be the first base of EnumType");
5355 return T;
5356 }
5357 case Type::Record: {
5358 assert(isa<RecordDecl>(TD));
5359 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5360 IsInjected, CanonicalType);
5361 assert(reinterpret_cast<void *>(T) ==
5362 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5363 "TagType must be the first base of RecordType");
5364 return T;
5365 }
5366 case Type::InjectedClassName: {
5367 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5368 IsInjected, CanonicalType);
5369 assert(reinterpret_cast<void *>(T) ==
5370 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5371 "TagType must be the first base of InjectedClassNameType");
5372 return T;
5373 }
5374 default:
5375 llvm_unreachable("unexpected type class");
5376 }
5377 }();
5378 assert(T->getKeyword() == Keyword);
5379 assert(T->getQualifier() == Qualifier);
5380 assert(T->getOriginalDecl() == TD);
5381 assert(T->isInjected() == IsInjected);
5382 assert(T->isTagOwned() == OwnsTag);
5383 assert((T->isCanonicalUnqualified()
5384 ? QualType()
5385 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5386 Types.push_back(T);
5387 return T;
5388}
5389
5390static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5391 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5392 RD && RD->isInjectedClassName())
5393 return cast<TagDecl>(RD->getDeclContext());
5394 return TD;
5395}
5396
5399 if (TD->TypeForDecl)
5400 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5401
5402 const Type *CanonicalType = getTagTypeInternal(
5404 /*Qualifier=*/std::nullopt, TD,
5405 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5406 /*WithFoldingSetNode=*/false);
5407 TD->TypeForDecl = CanonicalType;
5408 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5409}
5410
5412 NestedNameSpecifier Qualifier,
5413 const TagDecl *TD, bool OwnsTag) const {
5414
5415 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5416 bool IsInjected = TD != NonInjectedTD;
5417
5418 ElaboratedTypeKeyword PreferredKeyword =
5421 NonInjectedTD->getTagKind());
5422
5423 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5424 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5425 return QualType(T, 0);
5426
5427 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5428 const Type *T =
5429 getTagTypeInternal(Keyword,
5430 /*Qualifier=*/std::nullopt, NonInjectedTD,
5431 /*OwnsTag=*/false, IsInjected, CanonicalType,
5432 /*WithFoldingSetNode=*/false);
5433 TD->TypeForDecl = T;
5434 return QualType(T, 0);
5435 }
5436
5437 llvm::FoldingSetNodeID ID;
5438 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5439 OwnsTag, IsInjected);
5440
5441 void *InsertPos = nullptr;
5442 if (TagTypeFoldingSetPlaceholder *T =
5443 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5444 return QualType(T->getTagType(), 0);
5445
5446 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5447 TagType *T =
5448 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5449 CanonicalType, /*WithFoldingSetNode=*/true);
5450 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5451 return QualType(T, 0);
5452}
5453
5454bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5455 unsigned NumPositiveBits,
5456 QualType &BestType,
5457 QualType &BestPromotionType) {
5458 unsigned IntWidth = Target->getIntWidth();
5459 unsigned CharWidth = Target->getCharWidth();
5460 unsigned ShortWidth = Target->getShortWidth();
5461 bool EnumTooLarge = false;
5462 unsigned BestWidth;
5463 if (NumNegativeBits) {
5464 // If there is a negative value, figure out the smallest integer type (of
5465 // int/long/longlong) that fits.
5466 // If it's packed, check also if it fits a char or a short.
5467 if (IsPacked && NumNegativeBits <= CharWidth &&
5468 NumPositiveBits < CharWidth) {
5469 BestType = SignedCharTy;
5470 BestWidth = CharWidth;
5471 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5472 NumPositiveBits < ShortWidth) {
5473 BestType = ShortTy;
5474 BestWidth = ShortWidth;
5475 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5476 BestType = IntTy;
5477 BestWidth = IntWidth;
5478 } else {
5479 BestWidth = Target->getLongWidth();
5480
5481 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5482 BestType = LongTy;
5483 } else {
5484 BestWidth = Target->getLongLongWidth();
5485
5486 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5487 EnumTooLarge = true;
5488 BestType = LongLongTy;
5489 }
5490 }
5491 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5492 } else {
5493 // If there is no negative value, figure out the smallest type that fits
5494 // all of the enumerator values.
5495 // If it's packed, check also if it fits a char or a short.
5496 if (IsPacked && NumPositiveBits <= CharWidth) {
5497 BestType = UnsignedCharTy;
5498 BestPromotionType = IntTy;
5499 BestWidth = CharWidth;
5500 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5501 BestType = UnsignedShortTy;
5502 BestPromotionType = IntTy;
5503 BestWidth = ShortWidth;
5504 } else if (NumPositiveBits <= IntWidth) {
5505 BestType = UnsignedIntTy;
5506 BestWidth = IntWidth;
5507 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5509 : IntTy;
5510 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5511 BestType = UnsignedLongTy;
5512 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5514 : LongTy;
5515 } else {
5516 BestWidth = Target->getLongLongWidth();
5517 if (NumPositiveBits > BestWidth) {
5518 // This can happen with bit-precise integer types, but those are not
5519 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5520 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5521 // a 128-bit integer, we should consider doing the same.
5522 EnumTooLarge = true;
5523 }
5524 BestType = UnsignedLongLongTy;
5525 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5527 : LongLongTy;
5528 }
5529 }
5530 return EnumTooLarge;
5531}
5532
5534 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5535 "Integral type required!");
5536 unsigned BitWidth = getIntWidth(T);
5537
5538 if (Value.isUnsigned() || Value.isNonNegative()) {
5539 if (T->isSignedIntegerOrEnumerationType())
5540 --BitWidth;
5541 return Value.getActiveBits() <= BitWidth;
5542 }
5543 return Value.getSignificantBits() <= BitWidth;
5544}
5545
5546UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5548 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5549 const Type *CanonicalType) const {
5550 void *Mem = Allocate(
5551 UnresolvedUsingType::totalSizeToAlloc<
5553 !!InsertPos, !!Qualifier),
5554 alignof(UnresolvedUsingType));
5555 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5556 if (InsertPos) {
5557 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5559 TypedefTypes.InsertNode(Placeholder, InsertPos);
5560 }
5561 Types.push_back(T);
5562 return T;
5563}
5564
5566 const UnresolvedUsingTypenameDecl *D) const {
5567 D = D->getCanonicalDecl();
5568 if (D->TypeForDecl)
5569 return D->TypeForDecl->getCanonicalTypeUnqualified();
5570
5571 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5573 /*Qualifier=*/std::nullopt, D,
5574 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5575 D->TypeForDecl = CanonicalType;
5576 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5577}
5578
5581 NestedNameSpecifier Qualifier,
5582 const UnresolvedUsingTypenameDecl *D) const {
5583 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5584 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5585 return QualType(T, 0);
5586
5587 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5588 const Type *T =
5589 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5590 /*Qualifier=*/std::nullopt, D,
5591 /*InsertPos=*/nullptr, CanonicalType);
5592 D->TypeForDecl = T;
5593 return QualType(T, 0);
5594 }
5595
5596 llvm::FoldingSetNodeID ID;
5597 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5598
5599 void *InsertPos = nullptr;
5601 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5602 return QualType(Placeholder->getType(), 0);
5603 assert(InsertPos);
5604
5605 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5606 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5607 InsertPos, CanonicalType);
5608 return QualType(T, 0);
5609}
5610
5612 QualType modifiedType,
5613 QualType equivalentType,
5614 const Attr *attr) const {
5615 llvm::FoldingSetNodeID id;
5616 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5617
5618 void *insertPos = nullptr;
5619 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5620 if (type) return QualType(type, 0);
5621
5622 assert(!attr || attr->getKind() == attrKind);
5623
5624 QualType canon = getCanonicalType(equivalentType);
5625 type = new (*this, alignof(AttributedType))
5626 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5627
5628 Types.push_back(type);
5629 AttributedTypes.InsertNode(type, insertPos);
5630
5631 return QualType(type, 0);
5632}
5633
5635 QualType equivalentType) const {
5636 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5637}
5638
5640 QualType modifiedType,
5641 QualType equivalentType) {
5642 switch (nullability) {
5644 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5645
5647 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5648
5650 return getAttributedType(attr::TypeNullableResult, modifiedType,
5651 equivalentType);
5652
5654 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5655 equivalentType);
5656 }
5657
5658 llvm_unreachable("Unknown nullability kind");
5659}
5660
5661QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5662 QualType Wrapped) const {
5663 llvm::FoldingSetNodeID ID;
5664 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5665
5666 void *InsertPos = nullptr;
5667 BTFTagAttributedType *Ty =
5668 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5669 if (Ty)
5670 return QualType(Ty, 0);
5671
5672 QualType Canon = getCanonicalType(Wrapped);
5673 Ty = new (*this, alignof(BTFTagAttributedType))
5674 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5675
5676 Types.push_back(Ty);
5677 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5678
5679 return QualType(Ty, 0);
5680}
5681
5683 QualType Wrapped, QualType Contained,
5684 const HLSLAttributedResourceType::Attributes &Attrs) {
5685
5686 llvm::FoldingSetNodeID ID;
5687 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5688
5689 void *InsertPos = nullptr;
5690 HLSLAttributedResourceType *Ty =
5691 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5692 if (Ty)
5693 return QualType(Ty, 0);
5694
5695 Ty = new (*this, alignof(HLSLAttributedResourceType))
5696 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5697
5698 Types.push_back(Ty);
5699 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5700
5701 return QualType(Ty, 0);
5702}
5703
5704QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5705 uint32_t Alignment,
5706 ArrayRef<SpirvOperand> Operands) {
5707 llvm::FoldingSetNodeID ID;
5708 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5709
5710 void *InsertPos = nullptr;
5711 HLSLInlineSpirvType *Ty =
5712 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5713 if (Ty)
5714 return QualType(Ty, 0);
5715
5716 void *Mem = Allocate(
5717 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5718 alignof(HLSLInlineSpirvType));
5719
5720 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5721
5722 Types.push_back(Ty);
5723 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5724
5725 return QualType(Ty, 0);
5726}
5727
5728/// Retrieve a substitution-result type.
5730 Decl *AssociatedDecl,
5731 unsigned Index,
5732 UnsignedOrNone PackIndex,
5733 bool Final) const {
5734 llvm::FoldingSetNodeID ID;
5735 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5736 PackIndex, Final);
5737 void *InsertPos = nullptr;
5738 SubstTemplateTypeParmType *SubstParm =
5739 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5740
5741 if (!SubstParm) {
5742 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5743 !Replacement.isCanonical()),
5744 alignof(SubstTemplateTypeParmType));
5745 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5746 Index, PackIndex, Final);
5747 Types.push_back(SubstParm);
5748 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5749 }
5750
5751 return QualType(SubstParm, 0);
5752}
5753
5756 unsigned Index, bool Final,
5757 const TemplateArgument &ArgPack) {
5758#ifndef NDEBUG
5759 for (const auto &P : ArgPack.pack_elements())
5760 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5761#endif
5762
5763 llvm::FoldingSetNodeID ID;
5764 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5765 ArgPack);
5766 void *InsertPos = nullptr;
5767 if (SubstTemplateTypeParmPackType *SubstParm =
5768 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5769 return QualType(SubstParm, 0);
5770
5771 QualType Canon;
5772 {
5773 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5774 if (!AssociatedDecl->isCanonicalDecl() ||
5775 !CanonArgPack.structurallyEquals(ArgPack)) {
5777 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5778 [[maybe_unused]] const auto *Nothing =
5779 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5780 assert(!Nothing);
5781 }
5782 }
5783
5784 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5785 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5786 ArgPack);
5787 Types.push_back(SubstParm);
5788 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5789 return QualType(SubstParm, 0);
5790}
5791
5794 assert(llvm::all_of(ArgPack.pack_elements(),
5795 [](const auto &P) {
5796 return P.getKind() == TemplateArgument::Type;
5797 }) &&
5798 "Pack contains a non-type");
5799
5800 llvm::FoldingSetNodeID ID;
5801 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5802
5803 void *InsertPos = nullptr;
5804 if (auto *T =
5805 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5806 return QualType(T, 0);
5807
5808 QualType Canon;
5809 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5810 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5811 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5812 // Refresh InsertPos, in case the recursive call above caused rehashing,
5813 // which would invalidate the bucket pointer.
5814 [[maybe_unused]] const auto *Nothing =
5815 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5816 assert(!Nothing);
5817 }
5818
5819 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5820 SubstBuiltinTemplatePackType(Canon, ArgPack);
5821 Types.push_back(PackType);
5822 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5823 return QualType(PackType, 0);
5824}
5825
5826/// Retrieve the template type parameter type for a template
5827/// parameter or parameter pack with the given depth, index, and (optionally)
5828/// name.
5829QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5830 bool ParameterPack,
5831 TemplateTypeParmDecl *TTPDecl) const {
5832 llvm::FoldingSetNodeID ID;
5833 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5834 void *InsertPos = nullptr;
5835 TemplateTypeParmType *TypeParm
5836 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5837
5838 if (TypeParm)
5839 return QualType(TypeParm, 0);
5840
5841 if (TTPDecl) {
5842 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5843 TypeParm = new (*this, alignof(TemplateTypeParmType))
5844 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5845
5846 TemplateTypeParmType *TypeCheck
5847 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5848 assert(!TypeCheck && "Template type parameter canonical type broken");
5849 (void)TypeCheck;
5850 } else
5851 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5852 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5853
5854 Types.push_back(TypeParm);
5855 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5856
5857 return QualType(TypeParm, 0);
5858}
5859
5862 switch (Keyword) {
5863 // These are just themselves.
5869 return Keyword;
5870
5871 // These are equivalent.
5874
5875 // These are functionally equivalent, so relying on their equivalence is
5876 // IFNDR. By making them equivalent, we disallow overloading, which at least
5877 // can produce a diagnostic.
5880 }
5881 llvm_unreachable("unexpected keyword kind");
5882}
5883
5885 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5886 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5887 TemplateName Name, SourceLocation NameLoc,
5888 const TemplateArgumentListInfo &SpecifiedArgs,
5889 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5891 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5892
5895 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5896 SpecifiedArgs);
5897 return DI;
5898}
5899
5902 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5903 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5904 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5905 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5906 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5907 SpecifiedArgVec.push_back(Arg.getArgument());
5908
5909 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5910 CanonicalArgs, Underlying);
5911}
5912
5913[[maybe_unused]] static bool
5915 for (const TemplateArgument &Arg : Args)
5916 if (Arg.isPackExpansion())
5917 return true;
5918 return false;
5919}
5920
5923 ArrayRef<TemplateArgument> Args) const {
5924 assert(Template ==
5925 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5927 Template.getAsDependentTemplateName()));
5928#ifndef NDEBUG
5929 for (const auto &Arg : Args)
5930 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5931#endif
5932
5933 llvm::FoldingSetNodeID ID;
5934 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
5935 *this);
5936 void *InsertPos = nullptr;
5937 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5938 return QualType(T, 0);
5939
5940 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5941 sizeof(TemplateArgument) * Args.size(),
5942 alignof(TemplateSpecializationType));
5943 auto *Spec =
5944 new (Mem) TemplateSpecializationType(Keyword, Template,
5945 /*IsAlias=*/false, Args, QualType());
5946 assert(Spec->isDependentType() &&
5947 "canonical template specialization must be dependent");
5948 Types.push_back(Spec);
5949 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
5950 return QualType(Spec, 0);
5951}
5952
5955 ArrayRef<TemplateArgument> SpecifiedArgs,
5956 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5957 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
5958 bool IsTypeAlias = TD && TD->isTypeAlias();
5959 if (Underlying.isNull()) {
5960 TemplateName CanonTemplate =
5961 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
5962 ElaboratedTypeKeyword CanonKeyword =
5963 CanonTemplate.getAsDependentTemplateName()
5966 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
5968 if (CanonicalArgs.empty()) {
5969 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
5970 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
5971 CanonicalArgs = CanonArgsVec;
5972 } else {
5973 NonCanonical |= !llvm::equal(
5974 SpecifiedArgs, CanonicalArgs,
5975 [](const TemplateArgument &A, const TemplateArgument &B) {
5976 return A.structurallyEquals(B);
5977 });
5978 }
5979
5980 // We can get here with an alias template when the specialization
5981 // contains a pack expansion that does not match up with a parameter
5982 // pack, or a builtin template which cannot be resolved due to dependency.
5983 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
5984 hasAnyPackExpansions(CanonicalArgs)) &&
5985 "Caller must compute aliased type");
5986 IsTypeAlias = false;
5987
5989 CanonKeyword, CanonTemplate, CanonicalArgs);
5990 if (!NonCanonical)
5991 return Underlying;
5992 }
5993 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5994 sizeof(TemplateArgument) * SpecifiedArgs.size() +
5995 (IsTypeAlias ? sizeof(QualType) : 0),
5996 alignof(TemplateSpecializationType));
5997 auto *Spec = new (Mem) TemplateSpecializationType(
5998 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
5999 Types.push_back(Spec);
6000 return QualType(Spec, 0);
6001}
6002
6005 llvm::FoldingSetNodeID ID;
6006 ParenType::Profile(ID, InnerType);
6007
6008 void *InsertPos = nullptr;
6009 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6010 if (T)
6011 return QualType(T, 0);
6012
6013 QualType Canon = InnerType;
6014 if (!Canon.isCanonical()) {
6015 Canon = getCanonicalType(InnerType);
6016 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6017 assert(!CheckT && "Paren canonical type broken");
6018 (void)CheckT;
6019 }
6020
6021 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6022 Types.push_back(T);
6023 ParenTypes.InsertNode(T, InsertPos);
6024 return QualType(T, 0);
6025}
6026
6029 const IdentifierInfo *MacroII) const {
6030 QualType Canon = UnderlyingTy;
6031 if (!Canon.isCanonical())
6032 Canon = getCanonicalType(UnderlyingTy);
6033
6034 auto *newType = new (*this, alignof(MacroQualifiedType))
6035 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6036 Types.push_back(newType);
6037 return QualType(newType, 0);
6038}
6039
6042 const IdentifierInfo *Name) const {
6043 llvm::FoldingSetNodeID ID;
6044 DependentNameType::Profile(ID, Keyword, NNS, Name);
6045
6046 void *InsertPos = nullptr;
6047 if (DependentNameType *T =
6048 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6049 return QualType(T, 0);
6050
6051 ElaboratedTypeKeyword CanonKeyword =
6053 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6054
6055 QualType Canon;
6056 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6057 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6058 [[maybe_unused]] DependentNameType *T =
6059 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6060 assert(!T && "broken canonicalization");
6061 assert(Canon.isCanonical());
6062 }
6063
6064 DependentNameType *T = new (*this, alignof(DependentNameType))
6065 DependentNameType(Keyword, NNS, Name, Canon);
6066 Types.push_back(T);
6067 DependentNameTypes.InsertNode(T, InsertPos);
6068 return QualType(T, 0);
6069}
6070
6072 TemplateArgument Arg;
6073 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6075 if (TTP->isParameterPack())
6076 ArgType = getPackExpansionType(ArgType, std::nullopt);
6077
6079 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6080 QualType T =
6081 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6082 // For class NTTPs, ensure we include the 'const' so the type matches that
6083 // of a real template argument.
6084 // FIXME: It would be more faithful to model this as something like an
6085 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6087 if (T->isRecordType()) {
6088 // C++ [temp.param]p8: An id-expression naming a non-type
6089 // template-parameter of class type T denotes a static storage duration
6090 // object of type const T.
6091 T.addConst();
6092 VK = VK_LValue;
6093 } else {
6094 VK = Expr::getValueKindForType(NTTP->getType());
6095 }
6096 Expr *E = new (*this)
6097 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6098 T, VK, NTTP->getLocation());
6099
6100 if (NTTP->isParameterPack())
6101 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6102 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6103 } else {
6104 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6106 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6107 TemplateName(TTP));
6108 if (TTP->isParameterPack())
6109 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6110 else
6111 Arg = TemplateArgument(Name);
6112 }
6113
6114 if (Param->isTemplateParameterPack())
6115 Arg =
6116 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6117
6118 return Arg;
6119}
6120
6122 UnsignedOrNone NumExpansions,
6123 bool ExpectPackInType) const {
6124 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6125 "Pack expansions must expand one or more parameter packs");
6126
6127 llvm::FoldingSetNodeID ID;
6128 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6129
6130 void *InsertPos = nullptr;
6131 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6132 if (T)
6133 return QualType(T, 0);
6134
6135 QualType Canon;
6136 if (!Pattern.isCanonical()) {
6137 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6138 /*ExpectPackInType=*/false);
6139
6140 // Find the insert position again, in case we inserted an element into
6141 // PackExpansionTypes and invalidated our insert position.
6142 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6143 }
6144
6145 T = new (*this, alignof(PackExpansionType))
6146 PackExpansionType(Pattern, Canon, NumExpansions);
6147 Types.push_back(T);
6148 PackExpansionTypes.InsertNode(T, InsertPos);
6149 return QualType(T, 0);
6150}
6151
6152/// CmpProtocolNames - Comparison predicate for sorting protocols
6153/// alphabetically.
6154static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6155 ObjCProtocolDecl *const *RHS) {
6156 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6157}
6158
6160 if (Protocols.empty()) return true;
6161
6162 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6163 return false;
6164
6165 for (unsigned i = 1; i != Protocols.size(); ++i)
6166 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6167 Protocols[i]->getCanonicalDecl() != Protocols[i])
6168 return false;
6169 return true;
6170}
6171
6172static void
6174 // Sort protocols, keyed by name.
6175 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6176
6177 // Canonicalize.
6178 for (ObjCProtocolDecl *&P : Protocols)
6179 P = P->getCanonicalDecl();
6180
6181 // Remove duplicates.
6182 auto ProtocolsEnd = llvm::unique(Protocols);
6183 Protocols.erase(ProtocolsEnd, Protocols.end());
6184}
6185
6187 ObjCProtocolDecl * const *Protocols,
6188 unsigned NumProtocols) const {
6189 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6190 /*isKindOf=*/false);
6191}
6192
6194 QualType baseType,
6195 ArrayRef<QualType> typeArgs,
6197 bool isKindOf) const {
6198 // If the base type is an interface and there aren't any protocols or
6199 // type arguments to add, then the interface type will do just fine.
6200 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6201 isa<ObjCInterfaceType>(baseType))
6202 return baseType;
6203
6204 // Look in the folding set for an existing type.
6205 llvm::FoldingSetNodeID ID;
6206 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6207 void *InsertPos = nullptr;
6208 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6209 return QualType(QT, 0);
6210
6211 // Determine the type arguments to be used for canonicalization,
6212 // which may be explicitly specified here or written on the base
6213 // type.
6214 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6215 if (effectiveTypeArgs.empty()) {
6216 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6217 effectiveTypeArgs = baseObject->getTypeArgs();
6218 }
6219
6220 // Build the canonical type, which has the canonical base type and a
6221 // sorted-and-uniqued list of protocols and the type arguments
6222 // canonicalized.
6223 QualType canonical;
6224 bool typeArgsAreCanonical = llvm::all_of(
6225 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6226 bool protocolsSorted = areSortedAndUniqued(protocols);
6227 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6228 // Determine the canonical type arguments.
6229 ArrayRef<QualType> canonTypeArgs;
6230 SmallVector<QualType, 4> canonTypeArgsVec;
6231 if (!typeArgsAreCanonical) {
6232 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6233 for (auto typeArg : effectiveTypeArgs)
6234 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6235 canonTypeArgs = canonTypeArgsVec;
6236 } else {
6237 canonTypeArgs = effectiveTypeArgs;
6238 }
6239
6240 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6241 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6242 if (!protocolsSorted) {
6243 canonProtocolsVec.append(protocols.begin(), protocols.end());
6244 SortAndUniqueProtocols(canonProtocolsVec);
6245 canonProtocols = canonProtocolsVec;
6246 } else {
6247 canonProtocols = protocols;
6248 }
6249
6250 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6251 canonProtocols, isKindOf);
6252
6253 // Regenerate InsertPos.
6254 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6255 }
6256
6257 unsigned size = sizeof(ObjCObjectTypeImpl);
6258 size += typeArgs.size() * sizeof(QualType);
6259 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6260 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6261 auto *T =
6262 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6263 isKindOf);
6264
6265 Types.push_back(T);
6266 ObjCObjectTypes.InsertNode(T, InsertPos);
6267 return QualType(T, 0);
6268}
6269
6270/// Apply Objective-C protocol qualifiers to the given type.
6271/// If this is for the canonical type of a type parameter, we can apply
6272/// protocol qualifiers on the ObjCObjectPointerType.
6275 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6276 bool allowOnPointerType) const {
6277 hasError = false;
6278
6279 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6280 return getObjCTypeParamType(objT->getDecl(), protocols);
6281 }
6282
6283 // Apply protocol qualifiers to ObjCObjectPointerType.
6284 if (allowOnPointerType) {
6285 if (const auto *objPtr =
6286 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6287 const ObjCObjectType *objT = objPtr->getObjectType();
6288 // Merge protocol lists and construct ObjCObjectType.
6290 protocolsVec.append(objT->qual_begin(),
6291 objT->qual_end());
6292 protocolsVec.append(protocols.begin(), protocols.end());
6293 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6295 objT->getBaseType(),
6296 objT->getTypeArgsAsWritten(),
6297 protocols,
6298 objT->isKindOfTypeAsWritten());
6300 }
6301 }
6302
6303 // Apply protocol qualifiers to ObjCObjectType.
6304 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6305 // FIXME: Check for protocols to which the class type is already
6306 // known to conform.
6307
6308 return getObjCObjectType(objT->getBaseType(),
6309 objT->getTypeArgsAsWritten(),
6310 protocols,
6311 objT->isKindOfTypeAsWritten());
6312 }
6313
6314 // If the canonical type is ObjCObjectType, ...
6315 if (type->isObjCObjectType()) {
6316 // Silently overwrite any existing protocol qualifiers.
6317 // TODO: determine whether that's the right thing to do.
6318
6319 // FIXME: Check for protocols to which the class type is already
6320 // known to conform.
6321 return getObjCObjectType(type, {}, protocols, false);
6322 }
6323
6324 // id<protocol-list>
6325 if (type->isObjCIdType()) {
6326 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6327 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6328 objPtr->isKindOfType());
6330 }
6331
6332 // Class<protocol-list>
6333 if (type->isObjCClassType()) {
6334 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6335 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6336 objPtr->isKindOfType());
6338 }
6339
6340 hasError = true;
6341 return type;
6342}
6343
6346 ArrayRef<ObjCProtocolDecl *> protocols) const {
6347 // Look in the folding set for an existing type.
6348 llvm::FoldingSetNodeID ID;
6349 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6350 void *InsertPos = nullptr;
6351 if (ObjCTypeParamType *TypeParam =
6352 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6353 return QualType(TypeParam, 0);
6354
6355 // We canonicalize to the underlying type.
6356 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6357 if (!protocols.empty()) {
6358 // Apply the protocol qualifers.
6359 bool hasError;
6361 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6362 assert(!hasError && "Error when apply protocol qualifier to bound type");
6363 }
6364
6365 unsigned size = sizeof(ObjCTypeParamType);
6366 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6367 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6368 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6369
6370 Types.push_back(newType);
6371 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6372 return QualType(newType, 0);
6373}
6374
6376 ObjCTypeParamDecl *New) const {
6377 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6378 // Update TypeForDecl after updating TypeSourceInfo.
6379 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6381 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6382 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6383 New->TypeForDecl = UpdatedTy.getTypePtr();
6384}
6385
6386/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6387/// protocol list adopt all protocols in QT's qualified-id protocol
6388/// list.
6390 ObjCInterfaceDecl *IC) {
6391 if (!QT->isObjCQualifiedIdType())
6392 return false;
6393
6394 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6395 // If both the right and left sides have qualifiers.
6396 for (auto *Proto : OPT->quals()) {
6397 if (!IC->ClassImplementsProtocol(Proto, false))
6398 return false;
6399 }
6400 return true;
6401 }
6402 return false;
6403}
6404
6405/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6406/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6407/// of protocols.
6409 ObjCInterfaceDecl *IDecl) {
6410 if (!QT->isObjCQualifiedIdType())
6411 return false;
6412 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6413 if (!OPT)
6414 return false;
6415 if (!IDecl->hasDefinition())
6416 return false;
6418 CollectInheritedProtocols(IDecl, InheritedProtocols);
6419 if (InheritedProtocols.empty())
6420 return false;
6421 // Check that if every protocol in list of id<plist> conforms to a protocol
6422 // of IDecl's, then bridge casting is ok.
6423 bool Conforms = false;
6424 for (auto *Proto : OPT->quals()) {
6425 Conforms = false;
6426 for (auto *PI : InheritedProtocols) {
6427 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6428 Conforms = true;
6429 break;
6430 }
6431 }
6432 if (!Conforms)
6433 break;
6434 }
6435 if (Conforms)
6436 return true;
6437
6438 for (auto *PI : InheritedProtocols) {
6439 // If both the right and left sides have qualifiers.
6440 bool Adopts = false;
6441 for (auto *Proto : OPT->quals()) {
6442 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6443 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6444 break;
6445 }
6446 if (!Adopts)
6447 return false;
6448 }
6449 return true;
6450}
6451
6452/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6453/// the given object type.
6455 llvm::FoldingSetNodeID ID;
6456 ObjCObjectPointerType::Profile(ID, ObjectT);
6457
6458 void *InsertPos = nullptr;
6459 if (ObjCObjectPointerType *QT =
6460 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6461 return QualType(QT, 0);
6462
6463 // Find the canonical object type.
6464 QualType Canonical;
6465 if (!ObjectT.isCanonical()) {
6466 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6467
6468 // Regenerate InsertPos.
6469 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6470 }
6471
6472 // No match.
6473 void *Mem =
6475 auto *QType =
6476 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6477
6478 Types.push_back(QType);
6479 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6480 return QualType(QType, 0);
6481}
6482
6483/// getObjCInterfaceType - Return the unique reference to the type for the
6484/// specified ObjC interface decl. The list of protocols is optional.
6486 ObjCInterfaceDecl *PrevDecl) const {
6487 if (Decl->TypeForDecl)
6488 return QualType(Decl->TypeForDecl, 0);
6489
6490 if (PrevDecl) {
6491 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6492 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6493 return QualType(PrevDecl->TypeForDecl, 0);
6494 }
6495
6496 // Prefer the definition, if there is one.
6497 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6498 Decl = Def;
6499
6500 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6501 auto *T = new (Mem) ObjCInterfaceType(Decl);
6502 Decl->TypeForDecl = T;
6503 Types.push_back(T);
6504 return QualType(T, 0);
6505}
6506
6507/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6508/// TypeOfExprType AST's (since expression's are never shared). For example,
6509/// multiple declarations that refer to "typeof(x)" all contain different
6510/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6511/// on canonical type's (which are always unique).
6513 TypeOfExprType *toe;
6514 if (tofExpr->isTypeDependent()) {
6515 llvm::FoldingSetNodeID ID;
6516 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6517 Kind == TypeOfKind::Unqualified);
6518
6519 void *InsertPos = nullptr;
6521 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6522 if (Canon) {
6523 // We already have a "canonical" version of an identical, dependent
6524 // typeof(expr) type. Use that as our canonical type.
6525 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6526 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6527 } else {
6528 // Build a new, canonical typeof(expr) type.
6529 Canon = new (*this, alignof(DependentTypeOfExprType))
6530 DependentTypeOfExprType(*this, tofExpr, Kind);
6531 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6532 toe = Canon;
6533 }
6534 } else {
6535 QualType Canonical = getCanonicalType(tofExpr->getType());
6536 toe = new (*this, alignof(TypeOfExprType))
6537 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6538 }
6539 Types.push_back(toe);
6540 return QualType(toe, 0);
6541}
6542
6543/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6544/// TypeOfType nodes. The only motivation to unique these nodes would be
6545/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6546/// an issue. This doesn't affect the type checker, since it operates
6547/// on canonical types (which are always unique).
6549 QualType Canonical = getCanonicalType(tofType);
6550 auto *tot = new (*this, alignof(TypeOfType))
6551 TypeOfType(*this, tofType, Canonical, Kind);
6552 Types.push_back(tot);
6553 return QualType(tot, 0);
6554}
6555
6556/// getReferenceQualifiedType - Given an expr, will return the type for
6557/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6558/// and class member access into account.
6560 // C++11 [dcl.type.simple]p4:
6561 // [...]
6562 QualType T = E->getType();
6563 switch (E->getValueKind()) {
6564 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6565 // type of e;
6566 case VK_XValue:
6567 return getRValueReferenceType(T);
6568 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6569 // type of e;
6570 case VK_LValue:
6571 return getLValueReferenceType(T);
6572 // - otherwise, decltype(e) is the type of e.
6573 case VK_PRValue:
6574 return T;
6575 }
6576 llvm_unreachable("Unknown value kind");
6577}
6578
6579/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6580/// nodes. This would never be helpful, since each such type has its own
6581/// expression, and would not give a significant memory saving, since there
6582/// is an Expr tree under each such type.
6584 // C++11 [temp.type]p2:
6585 // If an expression e involves a template parameter, decltype(e) denotes a
6586 // unique dependent type. Two such decltype-specifiers refer to the same
6587 // type only if their expressions are equivalent (14.5.6.1).
6588 QualType CanonType;
6589 if (!E->isInstantiationDependent()) {
6590 CanonType = getCanonicalType(UnderlyingType);
6591 } else if (!UnderlyingType.isNull()) {
6592 CanonType = getDecltypeType(E, QualType());
6593 } else {
6594 llvm::FoldingSetNodeID ID;
6595 DependentDecltypeType::Profile(ID, *this, E);
6596
6597 void *InsertPos = nullptr;
6598 if (DependentDecltypeType *Canon =
6599 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6600 return QualType(Canon, 0);
6601
6602 // Build a new, canonical decltype(expr) type.
6603 auto *DT =
6604 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6605 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6606 Types.push_back(DT);
6607 return QualType(DT, 0);
6608 }
6609 auto *DT = new (*this, alignof(DecltypeType))
6610 DecltypeType(E, UnderlyingType, CanonType);
6611 Types.push_back(DT);
6612 return QualType(DT, 0);
6613}
6614
6616 bool FullySubstituted,
6617 ArrayRef<QualType> Expansions,
6618 UnsignedOrNone Index) const {
6619 QualType Canonical;
6620 if (FullySubstituted && Index) {
6621 Canonical = getCanonicalType(Expansions[*Index]);
6622 } else {
6623 llvm::FoldingSetNodeID ID;
6624 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6625 FullySubstituted, Expansions);
6626 void *InsertPos = nullptr;
6627 PackIndexingType *Canon =
6628 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6629 if (!Canon) {
6630 void *Mem = Allocate(
6631 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6633 Canon =
6634 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6635 IndexExpr, FullySubstituted, Expansions);
6636 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6637 }
6638 Canonical = QualType(Canon, 0);
6639 }
6640
6641 void *Mem =
6642 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6644 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6645 FullySubstituted, Expansions);
6646 Types.push_back(T);
6647 return QualType(T, 0);
6648}
6649
6650/// getUnaryTransformationType - We don't unique these, since the memory
6651/// savings are minimal and these are rare.
6654 UnaryTransformType::UTTKind Kind) const {
6655
6656 llvm::FoldingSetNodeID ID;
6657 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6658
6659 void *InsertPos = nullptr;
6660 if (UnaryTransformType *UT =
6661 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6662 return QualType(UT, 0);
6663
6664 QualType CanonType;
6665 if (!BaseType->isDependentType()) {
6666 CanonType = UnderlyingType.getCanonicalType();
6667 } else {
6668 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6669 UnderlyingType = QualType();
6670 if (QualType CanonBase = BaseType.getCanonicalType();
6671 BaseType != CanonBase) {
6672 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6673 assert(CanonType.isCanonical());
6674
6675 // Find the insertion position again.
6676 [[maybe_unused]] UnaryTransformType *UT =
6677 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6678 assert(!UT && "broken canonicalization");
6679 }
6680 }
6681
6682 auto *UT = new (*this, alignof(UnaryTransformType))
6683 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6684 UnaryTransformTypes.InsertNode(UT, InsertPos);
6685 Types.push_back(UT);
6686 return QualType(UT, 0);
6687}
6688
6689QualType ASTContext::getAutoTypeInternal(
6690 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6691 bool IsPack, TemplateDecl *TypeConstraintConcept,
6692 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6693 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6694 !TypeConstraintConcept && !IsDependent)
6695 return getAutoDeductType();
6696
6697 // Look in the folding set for an existing type.
6698 llvm::FoldingSetNodeID ID;
6699 bool IsDeducedDependent =
6700 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6701 (!DeducedType.isNull() && DeducedType->isDependentType());
6702 AutoType::Profile(ID, *this, DeducedType, Keyword,
6703 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6704 TypeConstraintArgs);
6705 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6706 return QualType(AT_iter->getSecond(), 0);
6707
6708 QualType Canon;
6709 if (!IsCanon) {
6710 if (!DeducedType.isNull()) {
6711 Canon = DeducedType.getCanonicalType();
6712 } else if (TypeConstraintConcept) {
6713 bool AnyNonCanonArgs = false;
6714 auto *CanonicalConcept =
6715 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6716 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6717 *this, TypeConstraintArgs, AnyNonCanonArgs);
6718 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6719 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6720 CanonicalConcept, CanonicalConceptArgs,
6721 /*IsCanon=*/true);
6722 }
6723 }
6724 }
6725
6726 void *Mem = Allocate(sizeof(AutoType) +
6727 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6728 alignof(AutoType));
6729 auto *AT = new (Mem) AutoType(
6730 DeducedType, Keyword,
6731 (IsDependent ? TypeDependence::DependentInstantiation
6732 : TypeDependence::None) |
6733 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6734 Canon, TypeConstraintConcept, TypeConstraintArgs);
6735#ifndef NDEBUG
6736 llvm::FoldingSetNodeID InsertedID;
6737 AT->Profile(InsertedID, *this);
6738 assert(InsertedID == ID && "ID does not match");
6739#endif
6740 Types.push_back(AT);
6741 AutoTypes.try_emplace(ID, AT);
6742 return QualType(AT, 0);
6743}
6744
6745/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6746/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6747/// canonical deduced-but-dependent 'auto' type.
6748QualType
6750 bool IsDependent, bool IsPack,
6751 TemplateDecl *TypeConstraintConcept,
6752 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6753 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6754 assert((!IsDependent || DeducedType.isNull()) &&
6755 "A dependent auto should be undeduced");
6756 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6757 TypeConstraintConcept, TypeConstraintArgs);
6758}
6759
6761 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6762
6763 // Remove a type-constraint from a top-level auto or decltype(auto).
6764 if (auto *AT = CanonT->getAs<AutoType>()) {
6765 if (!AT->isConstrained())
6766 return T;
6767 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6768 AT->isDependentType(),
6769 AT->containsUnexpandedParameterPack()),
6770 T.getQualifiers());
6771 }
6772
6773 // FIXME: We only support constrained auto at the top level in the type of a
6774 // non-type template parameter at the moment. Once we lift that restriction,
6775 // we'll need to recursively build types containing auto here.
6776 assert(!CanonT->getContainedAutoType() ||
6777 !CanonT->getContainedAutoType()->isConstrained());
6778 return T;
6779}
6780
6781QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6783 bool IsDependent, QualType Canon) const {
6784 // Look in the folding set for an existing type.
6785 void *InsertPos = nullptr;
6786 llvm::FoldingSetNodeID ID;
6787 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6788 IsDependent);
6789 if (DeducedTemplateSpecializationType *DTST =
6790 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6791 return QualType(DTST, 0);
6792
6793 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6794 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6795 IsDependent, Canon);
6796
6797#ifndef NDEBUG
6798 llvm::FoldingSetNodeID TempID;
6799 DTST->Profile(TempID);
6800 assert(ID == TempID && "ID does not match");
6801#endif
6802 Types.push_back(DTST);
6803 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6804 return QualType(DTST, 0);
6805}
6806
6807/// Return the uniqued reference to the deduced template specialization type
6808/// which has been deduced to the given type, or to the canonical undeduced
6809/// such type, or the canonical deduced-but-dependent such type.
6812 bool IsDependent) const {
6813 // FIXME: This could save an extra hash table lookup if it handled all the
6814 // parameters already being canonical.
6815 // FIXME: Can this be formed from a DependentTemplateName, such that the
6816 // keyword should be part of the canonical type?
6817 QualType Canon =
6818 DeducedType.isNull()
6819 ? getDeducedTemplateSpecializationTypeInternal(
6821 QualType(), IsDependent, QualType())
6822 : DeducedType.getCanonicalType();
6823 return getDeducedTemplateSpecializationTypeInternal(
6824 Keyword, Template, DeducedType, IsDependent, Canon);
6825}
6826
6827/// getAtomicType - Return the uniqued reference to the atomic type for
6828/// the given value type.
6830 // Unique pointers, to guarantee there is only one pointer of a particular
6831 // structure.
6832 llvm::FoldingSetNodeID ID;
6834
6835 void *InsertPos = nullptr;
6836 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6837 return QualType(AT, 0);
6838
6839 // If the atomic value type isn't canonical, this won't be a canonical type
6840 // either, so fill in the canonical type field.
6841 QualType Canonical;
6842 if (!T.isCanonical()) {
6843 Canonical = getAtomicType(getCanonicalType(T));
6844
6845 // Get the new insert position for the node we care about.
6846 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6847 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6848 }
6849 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6850 Types.push_back(New);
6851 AtomicTypes.InsertNode(New, InsertPos);
6852 return QualType(New, 0);
6853}
6854
6855/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6857 if (AutoDeductTy.isNull())
6858 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6859 AutoType(QualType(), AutoTypeKeyword::Auto,
6860 TypeDependence::None, QualType(),
6861 /*concept*/ nullptr, /*args*/ {}),
6862 0);
6863 return AutoDeductTy;
6864}
6865
6866/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6868 if (AutoRRefDeductTy.isNull())
6870 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6871 return AutoRRefDeductTy;
6872}
6873
6874/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6875/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6876/// needs to agree with the definition in <stddef.h>.
6880
6882 return getFromTargetType(Target->getSizeType());
6883}
6884
6885/// Return the unique signed counterpart of the integer type
6886/// corresponding to size_t.
6890
6891/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6892/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6896
6897/// Return the unique unsigned counterpart of "ptrdiff_t"
6898/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6899/// in the definition of %tu format specifier.
6901 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6902}
6903
6904/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6906 return getFromTargetType(Target->getIntMaxType());
6907}
6908
6909/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6911 return getFromTargetType(Target->getUIntMaxType());
6912}
6913
6914/// getSignedWCharType - Return the type of "signed wchar_t".
6915/// Used when in C++, as a GCC extension.
6917 // FIXME: derive from "Target" ?
6918 return WCharTy;
6919}
6920
6921/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6922/// Used when in C++, as a GCC extension.
6924 // FIXME: derive from "Target" ?
6925 return UnsignedIntTy;
6926}
6927
6929 return getFromTargetType(Target->getIntPtrType());
6930}
6931
6935
6936/// Return the unique type for "pid_t" defined in
6937/// <sys/types.h>. We need this to compute the correct type for vfork().
6939 return getFromTargetType(Target->getProcessIDType());
6940}
6941
6942//===----------------------------------------------------------------------===//
6943// Type Operators
6944//===----------------------------------------------------------------------===//
6945
6947 // Push qualifiers into arrays, and then discard any remaining
6948 // qualifiers.
6949 T = getCanonicalType(T);
6951 const Type *Ty = T.getTypePtr();
6955 } else if (isa<ArrayType>(Ty)) {
6957 } else if (isa<FunctionType>(Ty)) {
6958 Result = getPointerType(QualType(Ty, 0));
6959 } else {
6960 Result = QualType(Ty, 0);
6961 }
6962
6964}
6965
6967 Qualifiers &quals) const {
6968 SplitQualType splitType = type.getSplitUnqualifiedType();
6969
6970 // FIXME: getSplitUnqualifiedType() actually walks all the way to
6971 // the unqualified desugared type and then drops it on the floor.
6972 // We then have to strip that sugar back off with
6973 // getUnqualifiedDesugaredType(), which is silly.
6974 const auto *AT =
6975 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
6976
6977 // If we don't have an array, just use the results in splitType.
6978 if (!AT) {
6979 quals = splitType.Quals;
6980 return QualType(splitType.Ty, 0);
6981 }
6982
6983 // Otherwise, recurse on the array's element type.
6984 QualType elementType = AT->getElementType();
6985 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
6986
6987 // If that didn't change the element type, AT has no qualifiers, so we
6988 // can just use the results in splitType.
6989 if (elementType == unqualElementType) {
6990 assert(quals.empty()); // from the recursive call
6991 quals = splitType.Quals;
6992 return QualType(splitType.Ty, 0);
6993 }
6994
6995 // Otherwise, add in the qualifiers from the outermost type, then
6996 // build the type back up.
6997 quals.addConsistentQualifiers(splitType.Quals);
6998
6999 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7000 return getConstantArrayType(unqualElementType, CAT->getSize(),
7001 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7002 }
7003
7004 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7005 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7006 }
7007
7008 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7009 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7010 VAT->getSizeModifier(),
7011 VAT->getIndexTypeCVRQualifiers());
7012 }
7013
7014 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7015 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7016 DSAT->getSizeModifier(), 0);
7017}
7018
7019/// Attempt to unwrap two types that may both be array types with the same bound
7020/// (or both be array types of unknown bound) for the purpose of comparing the
7021/// cv-decomposition of two types per C++ [conv.qual].
7022///
7023/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7024/// C++20 [conv.qual], if permitted by the current language mode.
7026 bool AllowPiMismatch) const {
7027 while (true) {
7028 auto *AT1 = getAsArrayType(T1);
7029 if (!AT1)
7030 return;
7031
7032 auto *AT2 = getAsArrayType(T2);
7033 if (!AT2)
7034 return;
7035
7036 // If we don't have two array types with the same constant bound nor two
7037 // incomplete array types, we've unwrapped everything we can.
7038 // C++20 also permits one type to be a constant array type and the other
7039 // to be an incomplete array type.
7040 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7041 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7042 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7043 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7044 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7046 return;
7047 } else if (isa<IncompleteArrayType>(AT1)) {
7048 if (!(isa<IncompleteArrayType>(AT2) ||
7049 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7051 return;
7052 } else {
7053 return;
7054 }
7055
7056 T1 = AT1->getElementType();
7057 T2 = AT2->getElementType();
7058 }
7059}
7060
7061/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7062///
7063/// If T1 and T2 are both pointer types of the same kind, or both array types
7064/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7065/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7066///
7067/// This function will typically be called in a loop that successively
7068/// "unwraps" pointer and pointer-to-member types to compare them at each
7069/// level.
7070///
7071/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7072/// C++20 [conv.qual], if permitted by the current language mode.
7073///
7074/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7075/// pair of types that can't be unwrapped further.
7077 bool AllowPiMismatch) const {
7078 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7079
7080 const auto *T1PtrType = T1->getAs<PointerType>();
7081 const auto *T2PtrType = T2->getAs<PointerType>();
7082 if (T1PtrType && T2PtrType) {
7083 T1 = T1PtrType->getPointeeType();
7084 T2 = T2PtrType->getPointeeType();
7085 return true;
7086 }
7087
7088 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7089 *T2MPType = T2->getAs<MemberPointerType>();
7090 T1MPType && T2MPType) {
7091 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7092 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7093 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7094 return false;
7095 if (T1MPType->getQualifier().getCanonical() !=
7096 T2MPType->getQualifier().getCanonical())
7097 return false;
7098 T1 = T1MPType->getPointeeType();
7099 T2 = T2MPType->getPointeeType();
7100 return true;
7101 }
7102
7103 if (getLangOpts().ObjC) {
7104 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7105 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7106 if (T1OPType && T2OPType) {
7107 T1 = T1OPType->getPointeeType();
7108 T2 = T2OPType->getPointeeType();
7109 return true;
7110 }
7111 }
7112
7113 // FIXME: Block pointers, too?
7114
7115 return false;
7116}
7117
7119 while (true) {
7120 Qualifiers Quals;
7121 T1 = getUnqualifiedArrayType(T1, Quals);
7122 T2 = getUnqualifiedArrayType(T2, Quals);
7123 if (hasSameType(T1, T2))
7124 return true;
7125 if (!UnwrapSimilarTypes(T1, T2))
7126 return false;
7127 }
7128}
7129
7131 while (true) {
7132 Qualifiers Quals1, Quals2;
7133 T1 = getUnqualifiedArrayType(T1, Quals1);
7134 T2 = getUnqualifiedArrayType(T2, Quals2);
7135
7136 Quals1.removeCVRQualifiers();
7137 Quals2.removeCVRQualifiers();
7138 if (Quals1 != Quals2)
7139 return false;
7140
7141 if (hasSameType(T1, T2))
7142 return true;
7143
7144 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7145 return false;
7146 }
7147}
7148
7151 SourceLocation NameLoc) const {
7152 switch (Name.getKind()) {
7155 // DNInfo work in progress: CHECKME: what about DNLoc?
7157 NameLoc);
7158
7161 // DNInfo work in progress: CHECKME: what about DNLoc?
7162 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7163 }
7164
7167 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7168 }
7169
7173 DeclarationName DName;
7174 if (const IdentifierInfo *II = TN.getIdentifier()) {
7175 DName = DeclarationNames.getIdentifier(II);
7176 return DeclarationNameInfo(DName, NameLoc);
7177 } else {
7178 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7179 // DNInfo work in progress: FIXME: source locations?
7180 DeclarationNameLoc DNLoc =
7182 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7183 }
7184 }
7185
7189 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7190 NameLoc);
7191 }
7192
7197 NameLoc);
7198 }
7201 NameLoc);
7204 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7205 }
7206 }
7207
7208 llvm_unreachable("bad template name kind!");
7209}
7210
7211static const TemplateArgument *
7213 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7214 if (!TP->hasDefaultArgument())
7215 return nullptr;
7216 return &TP->getDefaultArgument().getArgument();
7217 };
7218 switch (P->getKind()) {
7219 case NamedDecl::TemplateTypeParm:
7220 return handleParam(cast<TemplateTypeParmDecl>(P));
7221 case NamedDecl::NonTypeTemplateParm:
7222 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7223 case NamedDecl::TemplateTemplateParm:
7224 return handleParam(cast<TemplateTemplateParmDecl>(P));
7225 default:
7226 llvm_unreachable("Unexpected template parameter kind");
7227 }
7228}
7229
7231 bool IgnoreDeduced) const {
7232 while (std::optional<TemplateName> UnderlyingOrNone =
7233 Name.desugar(IgnoreDeduced))
7234 Name = *UnderlyingOrNone;
7235
7236 switch (Name.getKind()) {
7239 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7241
7242 // The canonical template name is the canonical template declaration.
7243 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7244 }
7245
7248 llvm_unreachable("cannot canonicalize unresolved template");
7249
7252 assert(DTN && "Non-dependent template names must refer to template decls.");
7253 NestedNameSpecifier Qualifier = DTN->getQualifier();
7254 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7255 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7256 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7257 /*HasTemplateKeyword=*/true});
7258 return Name;
7259 }
7260
7264 TemplateArgument canonArgPack =
7267 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7268 subst->getIndex(), subst->getFinal());
7269 }
7271 assert(IgnoreDeduced == false);
7273 DefaultArguments DefArgs = DTS->getDefaultArguments();
7274 TemplateName Underlying = DTS->getUnderlying();
7275
7276 TemplateName CanonUnderlying =
7277 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7278 bool NonCanonical = CanonUnderlying != Underlying;
7279 auto CanonArgs =
7280 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7281
7282 ArrayRef<NamedDecl *> Params =
7283 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7284 assert(CanonArgs.size() <= Params.size());
7285 // A deduced template name which deduces the same default arguments already
7286 // declared in the underlying template is the same template as the
7287 // underlying template. We need need to note any arguments which differ from
7288 // the corresponding declaration. If any argument differs, we must build a
7289 // deduced template name.
7290 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7292 if (!A)
7293 break;
7294 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7295 TemplateArgument &CanonDefArg = CanonArgs[I];
7296 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7297 continue;
7298 // Keep popping from the back any deault arguments which are the same.
7299 if (I == int(CanonArgs.size() - 1))
7300 CanonArgs.pop_back();
7301 NonCanonical = true;
7302 }
7303 return NonCanonical ? getDeducedTemplateName(
7304 CanonUnderlying,
7305 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7306 : Name;
7307 }
7311 llvm_unreachable("always sugar node");
7312 }
7313
7314 llvm_unreachable("bad template name!");
7315}
7316
7318 const TemplateName &Y,
7319 bool IgnoreDeduced) const {
7320 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7321 getCanonicalTemplateName(Y, IgnoreDeduced);
7322}
7323
7325 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7326 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7327 return false;
7329 return false;
7330 return true;
7331}
7332
7333bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7334 if (!XCE != !YCE)
7335 return false;
7336
7337 if (!XCE)
7338 return true;
7339
7340 llvm::FoldingSetNodeID XCEID, YCEID;
7341 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7342 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7343 return XCEID == YCEID;
7344}
7345
7347 const TypeConstraint *YTC) const {
7348 if (!XTC != !YTC)
7349 return false;
7350
7351 if (!XTC)
7352 return true;
7353
7354 auto *NCX = XTC->getNamedConcept();
7355 auto *NCY = YTC->getNamedConcept();
7356 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7357 return false;
7360 return false;
7362 if (XTC->getConceptReference()
7364 ->NumTemplateArgs !=
7366 return false;
7367
7368 // Compare slowly by profiling.
7369 //
7370 // We couldn't compare the profiling result for the template
7371 // args here. Consider the following example in different modules:
7372 //
7373 // template <__integer_like _Tp, C<_Tp> Sentinel>
7374 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7375 // return __t;
7376 // }
7377 //
7378 // When we compare the profiling result for `C<_Tp>` in different
7379 // modules, it will compare the type of `_Tp` in different modules.
7380 // However, the type of `_Tp` in different modules refer to different
7381 // types here naturally. So we couldn't compare the profiling result
7382 // for the template args directly.
7385}
7386
7388 const NamedDecl *Y) const {
7389 if (X->getKind() != Y->getKind())
7390 return false;
7391
7392 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7393 auto *TY = cast<TemplateTypeParmDecl>(Y);
7394 if (TX->isParameterPack() != TY->isParameterPack())
7395 return false;
7396 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7397 return false;
7398 return isSameTypeConstraint(TX->getTypeConstraint(),
7399 TY->getTypeConstraint());
7400 }
7401
7402 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7403 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7404 return TX->isParameterPack() == TY->isParameterPack() &&
7405 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7406 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7407 TY->getPlaceholderTypeConstraint());
7408 }
7409
7411 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7412 return TX->isParameterPack() == TY->isParameterPack() &&
7413 isSameTemplateParameterList(TX->getTemplateParameters(),
7414 TY->getTemplateParameters());
7415}
7416
7418 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7419 if (X->size() != Y->size())
7420 return false;
7421
7422 for (unsigned I = 0, N = X->size(); I != N; ++I)
7423 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7424 return false;
7425
7426 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7427}
7428
7430 const NamedDecl *Y) const {
7431 // If the type parameter isn't the same already, we don't need to check the
7432 // default argument further.
7433 if (!isSameTemplateParameter(X, Y))
7434 return false;
7435
7436 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7437 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7438 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7439 return false;
7440
7441 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7442 TTPY->getDefaultArgument().getArgument().getAsType());
7443 }
7444
7445 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7446 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7447 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7448 return false;
7449
7450 Expr *DefaultArgumentX =
7451 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7452 Expr *DefaultArgumentY =
7453 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7454 llvm::FoldingSetNodeID XID, YID;
7455 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7456 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7457 return XID == YID;
7458 }
7459
7460 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7461 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7462
7463 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7464 return false;
7465
7466 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7467 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7468 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7469}
7470
7472 const NestedNameSpecifier Y) {
7473 if (X == Y)
7474 return true;
7475 if (!X || !Y)
7476 return false;
7477
7478 auto Kind = X.getKind();
7479 if (Kind != Y.getKind())
7480 return false;
7481
7482 // FIXME: For namespaces and types, we're permitted to check that the entity
7483 // is named via the same tokens. We should probably do so.
7484 switch (Kind) {
7486 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7487 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7488 if (!declaresSameEntity(NamespaceX->getNamespace(),
7489 NamespaceY->getNamespace()))
7490 return false;
7491 return isSameQualifier(PrefixX, PrefixY);
7492 }
7494 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7495 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7496 return false;
7497 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7498 }
7502 return true;
7503 }
7504 llvm_unreachable("unhandled qualifier kind");
7505}
7506
7507static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7508 if (!A->getASTContext().getLangOpts().CUDA)
7509 return true; // Target attributes are overloadable in CUDA compilation only.
7510 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7511 return false;
7512 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7513 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7514 return true; // unattributed and __host__ functions are the same.
7515}
7516
7517/// Determine whether the attributes we can overload on are identical for A and
7518/// B. Will ignore any overloadable attrs represented in the type of A and B.
7520 const FunctionDecl *B) {
7521 // Note that pass_object_size attributes are represented in the function's
7522 // ExtParameterInfo, so we don't need to check them here.
7523
7524 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7525 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7526 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7527
7528 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7529 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7530 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7531
7532 // Return false if the number of enable_if attributes is different.
7533 if (!Cand1A || !Cand2A)
7534 return false;
7535
7536 Cand1ID.clear();
7537 Cand2ID.clear();
7538
7539 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7540 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7541
7542 // Return false if any of the enable_if expressions of A and B are
7543 // different.
7544 if (Cand1ID != Cand2ID)
7545 return false;
7546 }
7547 return hasSameCudaAttrs(A, B);
7548}
7549
7550bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7551 // Caution: this function is called by the AST reader during deserialization,
7552 // so it cannot rely on AST invariants being met. Non-trivial accessors
7553 // should be avoided, along with any traversal of redeclaration chains.
7554
7555 if (X == Y)
7556 return true;
7557
7558 if (X->getDeclName() != Y->getDeclName())
7559 return false;
7560
7561 // Must be in the same context.
7562 //
7563 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7564 // could be two different declarations of the same function. (We will fix the
7565 // semantic DC to refer to the primary definition after merging.)
7566 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7568 return false;
7569
7570 // If either X or Y are local to the owning module, they are only possible to
7571 // be the same entity if they are in the same module.
7572 if (X->isModuleLocal() || Y->isModuleLocal())
7573 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7574 return false;
7575
7576 // Two typedefs refer to the same entity if they have the same underlying
7577 // type.
7578 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7579 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7580 return hasSameType(TypedefX->getUnderlyingType(),
7581 TypedefY->getUnderlyingType());
7582
7583 // Must have the same kind.
7584 if (X->getKind() != Y->getKind())
7585 return false;
7586
7587 // Objective-C classes and protocols with the same name always match.
7589 return true;
7590
7592 // No need to handle these here: we merge them when adding them to the
7593 // template.
7594 return false;
7595 }
7596
7597 // Compatible tags match.
7598 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7599 const auto *TagY = cast<TagDecl>(Y);
7600 return (TagX->getTagKind() == TagY->getTagKind()) ||
7601 ((TagX->getTagKind() == TagTypeKind::Struct ||
7602 TagX->getTagKind() == TagTypeKind::Class ||
7603 TagX->getTagKind() == TagTypeKind::Interface) &&
7604 (TagY->getTagKind() == TagTypeKind::Struct ||
7605 TagY->getTagKind() == TagTypeKind::Class ||
7606 TagY->getTagKind() == TagTypeKind::Interface));
7607 }
7608
7609 // Functions with the same type and linkage match.
7610 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7611 // functions, etc.
7612 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7613 const auto *FuncY = cast<FunctionDecl>(Y);
7614 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7615 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7616 if (CtorX->getInheritedConstructor() &&
7617 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7618 CtorY->getInheritedConstructor().getConstructor()))
7619 return false;
7620 }
7621
7622 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7623 return false;
7624
7625 // Multiversioned functions with different feature strings are represented
7626 // as separate declarations.
7627 if (FuncX->isMultiVersion()) {
7628 const auto *TAX = FuncX->getAttr<TargetAttr>();
7629 const auto *TAY = FuncY->getAttr<TargetAttr>();
7630 assert(TAX && TAY && "Multiversion Function without target attribute");
7631
7632 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7633 return false;
7634 }
7635
7636 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7637 // not the same entity if they are constrained.
7638 if ((FuncX->isMemberLikeConstrainedFriend() ||
7639 FuncY->isMemberLikeConstrainedFriend()) &&
7640 !FuncX->getLexicalDeclContext()->Equals(
7641 FuncY->getLexicalDeclContext())) {
7642 return false;
7643 }
7644
7645 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7646 FuncY->getTrailingRequiresClause()))
7647 return false;
7648
7649 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7650 // Map to the first declaration that we've already merged into this one.
7651 // The TSI of redeclarations might not match (due to calling conventions
7652 // being inherited onto the type but not the TSI), but the TSI type of
7653 // the first declaration of the function should match across modules.
7654 FD = FD->getCanonicalDecl();
7655 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7656 : FD->getType();
7657 };
7658 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7659 if (!hasSameType(XT, YT)) {
7660 // We can get functions with different types on the redecl chain in C++17
7661 // if they have differing exception specifications and at least one of
7662 // the excpetion specs is unresolved.
7663 auto *XFPT = XT->getAs<FunctionProtoType>();
7664 auto *YFPT = YT->getAs<FunctionProtoType>();
7665 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7666 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7669 return true;
7670 return false;
7671 }
7672
7673 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7674 hasSameOverloadableAttrs(FuncX, FuncY);
7675 }
7676
7677 // Variables with the same type and linkage match.
7678 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7679 const auto *VarY = cast<VarDecl>(Y);
7680 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7681 // During deserialization, we might compare variables before we load
7682 // their types. Assume the types will end up being the same.
7683 if (VarX->getType().isNull() || VarY->getType().isNull())
7684 return true;
7685
7686 if (hasSameType(VarX->getType(), VarY->getType()))
7687 return true;
7688
7689 // We can get decls with different types on the redecl chain. Eg.
7690 // template <typename T> struct S { static T Var[]; }; // #1
7691 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7692 // Only? happens when completing an incomplete array type. In this case
7693 // when comparing #1 and #2 we should go through their element type.
7694 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7695 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7696 if (!VarXTy || !VarYTy)
7697 return false;
7698 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7699 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7700 }
7701 return false;
7702 }
7703
7704 // Namespaces with the same name and inlinedness match.
7705 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7706 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7707 return NamespaceX->isInline() == NamespaceY->isInline();
7708 }
7709
7710 // Identical template names and kinds match if their template parameter lists
7711 // and patterns match.
7712 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7713 const auto *TemplateY = cast<TemplateDecl>(Y);
7714
7715 // ConceptDecl wouldn't be the same if their constraint expression differs.
7716 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7717 const auto *ConceptY = cast<ConceptDecl>(Y);
7718 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7719 ConceptY->getConstraintExpr()))
7720 return false;
7721 }
7722
7723 return isSameEntity(TemplateX->getTemplatedDecl(),
7724 TemplateY->getTemplatedDecl()) &&
7725 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7726 TemplateY->getTemplateParameters());
7727 }
7728
7729 // Fields with the same name and the same type match.
7730 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7731 const auto *FDY = cast<FieldDecl>(Y);
7732 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7733 return hasSameType(FDX->getType(), FDY->getType());
7734 }
7735
7736 // Indirect fields with the same target field match.
7737 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7738 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7739 return IFDX->getAnonField()->getCanonicalDecl() ==
7740 IFDY->getAnonField()->getCanonicalDecl();
7741 }
7742
7743 // Enumerators with the same name match.
7745 // FIXME: Also check the value is odr-equivalent.
7746 return true;
7747
7748 // Using shadow declarations with the same target match.
7749 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7750 const auto *USY = cast<UsingShadowDecl>(Y);
7751 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7752 }
7753
7754 // Using declarations with the same qualifier match. (We already know that
7755 // the name matches.)
7756 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7757 const auto *UY = cast<UsingDecl>(Y);
7758 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7759 UX->hasTypename() == UY->hasTypename() &&
7760 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7761 }
7762 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7763 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7764 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7765 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7766 }
7767 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7768 return isSameQualifier(
7769 UX->getQualifier(),
7770 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7771 }
7772
7773 // Using-pack declarations are only created by instantiation, and match if
7774 // they're instantiated from matching UnresolvedUsing...Decls.
7775 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7776 return declaresSameEntity(
7777 UX->getInstantiatedFromUsingDecl(),
7778 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7779 }
7780
7781 // Namespace alias definitions with the same target match.
7782 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7783 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7784 return NAX->getNamespace()->Equals(NAY->getNamespace());
7785 }
7786
7787 return false;
7788}
7789
7792 switch (Arg.getKind()) {
7794 return Arg;
7795
7797 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7798 Arg.getIsDefaulted());
7799
7801 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7803 Arg.getIsDefaulted());
7804 }
7805
7808 /*isNullPtr*/ true, Arg.getIsDefaulted());
7809
7812 Arg.getIsDefaulted());
7813
7815 return TemplateArgument(
7818
7821
7823 return TemplateArgument(*this,
7826
7829 /*isNullPtr*/ false, Arg.getIsDefaulted());
7830
7832 bool AnyNonCanonArgs = false;
7833 auto CanonArgs = ::getCanonicalTemplateArguments(
7834 *this, Arg.pack_elements(), AnyNonCanonArgs);
7835 if (!AnyNonCanonArgs)
7836 return Arg;
7838 const_cast<ASTContext &>(*this), CanonArgs);
7839 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7840 return NewArg;
7841 }
7842 }
7843
7844 // Silence GCC warning
7845 llvm_unreachable("Unhandled template argument kind");
7846}
7847
7849 const TemplateArgument &Arg2) const {
7850 if (Arg1.getKind() != Arg2.getKind())
7851 return false;
7852
7853 switch (Arg1.getKind()) {
7855 llvm_unreachable("Comparing NULL template argument");
7856
7858 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7859
7861 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7863
7865 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7866
7871
7873 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7874 Arg2.getAsIntegral());
7875
7877 return Arg1.structurallyEquals(Arg2);
7878
7880 llvm::FoldingSetNodeID ID1, ID2;
7881 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7882 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7883 return ID1 == ID2;
7884 }
7885
7887 return llvm::equal(
7888 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7889 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7890 return isSameTemplateArgument(Arg1, Arg2);
7891 });
7892 }
7893
7894 llvm_unreachable("Unhandled template argument kind");
7895}
7896
7898 // Handle the non-qualified case efficiently.
7899 if (!T.hasLocalQualifiers()) {
7900 // Handle the common positive case fast.
7901 if (const auto *AT = dyn_cast<ArrayType>(T))
7902 return AT;
7903 }
7904
7905 // Handle the common negative case fast.
7906 if (!isa<ArrayType>(T.getCanonicalType()))
7907 return nullptr;
7908
7909 // Apply any qualifiers from the array type to the element type. This
7910 // implements C99 6.7.3p8: "If the specification of an array type includes
7911 // any type qualifiers, the element type is so qualified, not the array type."
7912
7913 // If we get here, we either have type qualifiers on the type, or we have
7914 // sugar such as a typedef in the way. If we have type qualifiers on the type
7915 // we must propagate them down into the element type.
7916
7917 SplitQualType split = T.getSplitDesugaredType();
7918 Qualifiers qs = split.Quals;
7919
7920 // If we have a simple case, just return now.
7921 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7922 if (!ATy || qs.empty())
7923 return ATy;
7924
7925 // Otherwise, we have an array and we have qualifiers on it. Push the
7926 // qualifiers into the array element type and return a new array type.
7927 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7928
7929 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7930 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7931 CAT->getSizeExpr(),
7932 CAT->getSizeModifier(),
7933 CAT->getIndexTypeCVRQualifiers()));
7934 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7936 IAT->getSizeModifier(),
7937 IAT->getIndexTypeCVRQualifiers()));
7938
7939 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7941 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
7942 DSAT->getIndexTypeCVRQualifiers()));
7943
7944 const auto *VAT = cast<VariableArrayType>(ATy);
7945 return cast<ArrayType>(
7946 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
7947 VAT->getIndexTypeCVRQualifiers()));
7948}
7949
7951 if (getLangOpts().HLSL && T->isConstantArrayType())
7952 return getArrayParameterType(T);
7953 if (T->isArrayType() || T->isFunctionType())
7954 return getDecayedType(T);
7955 return T;
7956}
7957
7961 return T.getUnqualifiedType();
7962}
7963
7965 // C++ [except.throw]p3:
7966 // A throw-expression initializes a temporary object, called the exception
7967 // object, the type of which is determined by removing any top-level
7968 // cv-qualifiers from the static type of the operand of throw and adjusting
7969 // the type from "array of T" or "function returning T" to "pointer to T"
7970 // or "pointer to function returning T", [...]
7972 if (T->isArrayType() || T->isFunctionType())
7973 T = getDecayedType(T);
7974 return T.getUnqualifiedType();
7975}
7976
7977/// getArrayDecayedType - Return the properly qualified result of decaying the
7978/// specified array type to a pointer. This operation is non-trivial when
7979/// handling typedefs etc. The canonical type of "T" must be an array type,
7980/// this returns a pointer to a properly qualified element of the array.
7981///
7982/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
7984 // Get the element type with 'getAsArrayType' so that we don't lose any
7985 // typedefs in the element type of the array. This also handles propagation
7986 // of type qualifiers from the array type into the element type if present
7987 // (C99 6.7.3p8).
7988 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
7989 assert(PrettyArrayType && "Not an array type!");
7990
7991 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
7992
7993 // int x[restrict 4] -> int *restrict
7995 PrettyArrayType->getIndexTypeQualifiers());
7996
7997 // int x[_Nullable] -> int * _Nullable
7998 if (auto Nullability = Ty->getNullability()) {
7999 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8000 Result, Result);
8001 }
8002 return Result;
8003}
8004
8006 return getBaseElementType(array->getElementType());
8007}
8008
8010 Qualifiers qs;
8011 while (true) {
8012 SplitQualType split = type.getSplitDesugaredType();
8013 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8014 if (!array) break;
8015
8016 type = array->getElementType();
8018 }
8019
8020 return getQualifiedType(type, qs);
8021}
8022
8023/// getConstantArrayElementCount - Returns number of constant array elements.
8024uint64_t
8026 uint64_t ElementCount = 1;
8027 do {
8028 ElementCount *= CA->getZExtSize();
8029 CA = dyn_cast_or_null<ConstantArrayType>(
8031 } while (CA);
8032 return ElementCount;
8033}
8034
8036 const ArrayInitLoopExpr *AILE) const {
8037 if (!AILE)
8038 return 0;
8039
8040 uint64_t ElementCount = 1;
8041
8042 do {
8043 ElementCount *= AILE->getArraySize().getZExtValue();
8044 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8045 } while (AILE);
8046
8047 return ElementCount;
8048}
8049
8050/// getFloatingRank - Return a relative rank for floating point types.
8051/// This routine will assert if passed a built-in type that isn't a float.
8053 if (const auto *CT = T->getAs<ComplexType>())
8054 return getFloatingRank(CT->getElementType());
8055
8056 switch (T->castAs<BuiltinType>()->getKind()) {
8057 default: llvm_unreachable("getFloatingRank(): not a floating type");
8058 case BuiltinType::Float16: return Float16Rank;
8059 case BuiltinType::Half: return HalfRank;
8060 case BuiltinType::Float: return FloatRank;
8061 case BuiltinType::Double: return DoubleRank;
8062 case BuiltinType::LongDouble: return LongDoubleRank;
8063 case BuiltinType::Float128: return Float128Rank;
8064 case BuiltinType::BFloat16: return BFloat16Rank;
8065 case BuiltinType::Ibm128: return Ibm128Rank;
8066 }
8067}
8068
8069/// getFloatingTypeOrder - Compare the rank of the two specified floating
8070/// point types, ignoring the domain of the type (i.e. 'double' ==
8071/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8072/// LHS < RHS, return -1.
8074 FloatingRank LHSR = getFloatingRank(LHS);
8075 FloatingRank RHSR = getFloatingRank(RHS);
8076
8077 if (LHSR == RHSR)
8078 return 0;
8079 if (LHSR > RHSR)
8080 return 1;
8081 return -1;
8082}
8083
8086 return 0;
8087 return getFloatingTypeOrder(LHS, RHS);
8088}
8089
8090/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8091/// routine will assert if passed a built-in type that isn't an integer or enum,
8092/// or if it is not canonicalized.
8093unsigned ASTContext::getIntegerRank(const Type *T) const {
8094 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8095
8096 // Results in this 'losing' to any type of the same size, but winning if
8097 // larger.
8098 if (const auto *EIT = dyn_cast<BitIntType>(T))
8099 return 0 + (EIT->getNumBits() << 3);
8100
8101 switch (cast<BuiltinType>(T)->getKind()) {
8102 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8103 case BuiltinType::Bool:
8104 return 1 + (getIntWidth(BoolTy) << 3);
8105 case BuiltinType::Char_S:
8106 case BuiltinType::Char_U:
8107 case BuiltinType::SChar:
8108 case BuiltinType::UChar:
8109 return 2 + (getIntWidth(CharTy) << 3);
8110 case BuiltinType::Short:
8111 case BuiltinType::UShort:
8112 return 3 + (getIntWidth(ShortTy) << 3);
8113 case BuiltinType::Int:
8114 case BuiltinType::UInt:
8115 return 4 + (getIntWidth(IntTy) << 3);
8116 case BuiltinType::Long:
8117 case BuiltinType::ULong:
8118 return 5 + (getIntWidth(LongTy) << 3);
8119 case BuiltinType::LongLong:
8120 case BuiltinType::ULongLong:
8121 return 6 + (getIntWidth(LongLongTy) << 3);
8122 case BuiltinType::Int128:
8123 case BuiltinType::UInt128:
8124 return 7 + (getIntWidth(Int128Ty) << 3);
8125
8126 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8127 // their underlying types" [c++20 conv.rank]
8128 case BuiltinType::Char8:
8129 return getIntegerRank(UnsignedCharTy.getTypePtr());
8130 case BuiltinType::Char16:
8131 return getIntegerRank(
8132 getFromTargetType(Target->getChar16Type()).getTypePtr());
8133 case BuiltinType::Char32:
8134 return getIntegerRank(
8135 getFromTargetType(Target->getChar32Type()).getTypePtr());
8136 case BuiltinType::WChar_S:
8137 case BuiltinType::WChar_U:
8138 return getIntegerRank(
8139 getFromTargetType(Target->getWCharType()).getTypePtr());
8140 }
8141}
8142
8143/// Whether this is a promotable bitfield reference according
8144/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8145///
8146/// \returns the type this bit-field will promote to, or NULL if no
8147/// promotion occurs.
8149 if (E->isTypeDependent() || E->isValueDependent())
8150 return {};
8151
8152 // C++ [conv.prom]p5:
8153 // If the bit-field has an enumerated type, it is treated as any other
8154 // value of that type for promotion purposes.
8156 return {};
8157
8158 // FIXME: We should not do this unless E->refersToBitField() is true. This
8159 // matters in C where getSourceBitField() will find bit-fields for various
8160 // cases where the source expression is not a bit-field designator.
8161
8162 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8163 if (!Field)
8164 return {};
8165
8166 QualType FT = Field->getType();
8167
8168 uint64_t BitWidth = Field->getBitWidthValue();
8169 uint64_t IntSize = getTypeSize(IntTy);
8170 // C++ [conv.prom]p5:
8171 // A prvalue for an integral bit-field can be converted to a prvalue of type
8172 // int if int can represent all the values of the bit-field; otherwise, it
8173 // can be converted to unsigned int if unsigned int can represent all the
8174 // values of the bit-field. If the bit-field is larger yet, no integral
8175 // promotion applies to it.
8176 // C11 6.3.1.1/2:
8177 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8178 // If an int can represent all values of the original type (as restricted by
8179 // the width, for a bit-field), the value is converted to an int; otherwise,
8180 // it is converted to an unsigned int.
8181 //
8182 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8183 // We perform that promotion here to match GCC and C++.
8184 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8185 // greater than that of 'int'. We perform that promotion to match GCC.
8186 //
8187 // C23 6.3.1.1p2:
8188 // The value from a bit-field of a bit-precise integer type is converted to
8189 // the corresponding bit-precise integer type. (The rest is the same as in
8190 // C11.)
8191 if (QualType QT = Field->getType(); QT->isBitIntType())
8192 return QT;
8193
8194 if (BitWidth < IntSize)
8195 return IntTy;
8196
8197 if (BitWidth == IntSize)
8198 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8199
8200 // Bit-fields wider than int are not subject to promotions, and therefore act
8201 // like the base type. GCC has some weird bugs in this area that we
8202 // deliberately do not follow (GCC follows a pre-standard resolution to
8203 // C's DR315 which treats bit-width as being part of the type, and this leaks
8204 // into their semantics in some cases).
8205 return {};
8206}
8207
8208/// getPromotedIntegerType - Returns the type that Promotable will
8209/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8210/// integer type.
8212 assert(!Promotable.isNull());
8213 assert(isPromotableIntegerType(Promotable));
8214 if (const auto *ED = Promotable->getAsEnumDecl())
8215 return ED->getPromotionType();
8216
8217 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8218 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8219 // (3.9.1) can be converted to a prvalue of the first of the following
8220 // types that can represent all the values of its underlying type:
8221 // int, unsigned int, long int, unsigned long int, long long int, or
8222 // unsigned long long int [...]
8223 // FIXME: Is there some better way to compute this?
8224 if (BT->getKind() == BuiltinType::WChar_S ||
8225 BT->getKind() == BuiltinType::WChar_U ||
8226 BT->getKind() == BuiltinType::Char8 ||
8227 BT->getKind() == BuiltinType::Char16 ||
8228 BT->getKind() == BuiltinType::Char32) {
8229 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8230 uint64_t FromSize = getTypeSize(BT);
8231 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8233 for (const auto &PT : PromoteTypes) {
8234 uint64_t ToSize = getTypeSize(PT);
8235 if (FromSize < ToSize ||
8236 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8237 return PT;
8238 }
8239 llvm_unreachable("char type should fit into long long");
8240 }
8241 }
8242
8243 // At this point, we should have a signed or unsigned integer type.
8244 if (Promotable->isSignedIntegerType())
8245 return IntTy;
8246 uint64_t PromotableSize = getIntWidth(Promotable);
8247 uint64_t IntSize = getIntWidth(IntTy);
8248 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8249 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8250}
8251
8252/// Recurses in pointer/array types until it finds an objc retainable
8253/// type and returns its ownership.
8255 while (!T.isNull()) {
8256 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8257 return T.getObjCLifetime();
8258 if (T->isArrayType())
8260 else if (const auto *PT = T->getAs<PointerType>())
8261 T = PT->getPointeeType();
8262 else if (const auto *RT = T->getAs<ReferenceType>())
8263 T = RT->getPointeeType();
8264 else
8265 break;
8266 }
8267
8268 return Qualifiers::OCL_None;
8269}
8270
8271static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8272 // Incomplete enum types are not treated as integer types.
8273 // FIXME: In C++, enum types are never integer types.
8274 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8275 if (ED->isComplete() && !ED->isScoped())
8276 return ED->getIntegerType().getTypePtr();
8277 return nullptr;
8278}
8279
8280/// getIntegerTypeOrder - Returns the highest ranked integer type:
8281/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8282/// LHS < RHS, return -1.
8284 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8285 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8286
8287 // Unwrap enums to their underlying type.
8288 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8289 LHSC = getIntegerTypeForEnum(ET);
8290 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8291 RHSC = getIntegerTypeForEnum(ET);
8292
8293 if (LHSC == RHSC) return 0;
8294
8295 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8296 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8297
8298 unsigned LHSRank = getIntegerRank(LHSC);
8299 unsigned RHSRank = getIntegerRank(RHSC);
8300
8301 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8302 if (LHSRank == RHSRank) return 0;
8303 return LHSRank > RHSRank ? 1 : -1;
8304 }
8305
8306 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8307 if (LHSUnsigned) {
8308 // If the unsigned [LHS] type is larger, return it.
8309 if (LHSRank >= RHSRank)
8310 return 1;
8311
8312 // If the signed type can represent all values of the unsigned type, it
8313 // wins. Because we are dealing with 2's complement and types that are
8314 // powers of two larger than each other, this is always safe.
8315 return -1;
8316 }
8317
8318 // If the unsigned [RHS] type is larger, return it.
8319 if (RHSRank >= LHSRank)
8320 return -1;
8321
8322 // If the signed type can represent all values of the unsigned type, it
8323 // wins. Because we are dealing with 2's complement and types that are
8324 // powers of two larger than each other, this is always safe.
8325 return 1;
8326}
8327
8329 if (CFConstantStringTypeDecl)
8330 return CFConstantStringTypeDecl;
8331
8332 assert(!CFConstantStringTagDecl &&
8333 "tag and typedef should be initialized together");
8334 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8335 CFConstantStringTagDecl->startDefinition();
8336
8337 struct {
8338 QualType Type;
8339 const char *Name;
8340 } Fields[5];
8341 unsigned Count = 0;
8342
8343 /// Objective-C ABI
8344 ///
8345 /// typedef struct __NSConstantString_tag {
8346 /// const int *isa;
8347 /// int flags;
8348 /// const char *str;
8349 /// long length;
8350 /// } __NSConstantString;
8351 ///
8352 /// Swift ABI (4.1, 4.2)
8353 ///
8354 /// typedef struct __NSConstantString_tag {
8355 /// uintptr_t _cfisa;
8356 /// uintptr_t _swift_rc;
8357 /// _Atomic(uint64_t) _cfinfoa;
8358 /// const char *_ptr;
8359 /// uint32_t _length;
8360 /// } __NSConstantString;
8361 ///
8362 /// Swift ABI (5.0)
8363 ///
8364 /// typedef struct __NSConstantString_tag {
8365 /// uintptr_t _cfisa;
8366 /// uintptr_t _swift_rc;
8367 /// _Atomic(uint64_t) _cfinfoa;
8368 /// const char *_ptr;
8369 /// uintptr_t _length;
8370 /// } __NSConstantString;
8371
8372 const auto CFRuntime = getLangOpts().CFRuntime;
8373 if (static_cast<unsigned>(CFRuntime) <
8374 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8375 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8376 Fields[Count++] = { IntTy, "flags" };
8377 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8378 Fields[Count++] = { LongTy, "length" };
8379 } else {
8380 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8381 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8382 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8383 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8386 Fields[Count++] = { IntTy, "_ptr" };
8387 else
8388 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8389 }
8390
8391 // Create fields
8392 for (unsigned i = 0; i < Count; ++i) {
8393 FieldDecl *Field =
8394 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8395 SourceLocation(), &Idents.get(Fields[i].Name),
8396 Fields[i].Type, /*TInfo=*/nullptr,
8397 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8398 Field->setAccess(AS_public);
8399 CFConstantStringTagDecl->addDecl(Field);
8400 }
8401
8402 CFConstantStringTagDecl->completeDefinition();
8403 // This type is designed to be compatible with NSConstantString, but cannot
8404 // use the same name, since NSConstantString is an interface.
8405 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8406 CFConstantStringTypeDecl =
8407 buildImplicitTypedef(tagType, "__NSConstantString");
8408
8409 return CFConstantStringTypeDecl;
8410}
8411
8413 if (!CFConstantStringTagDecl)
8414 getCFConstantStringDecl(); // Build the tag and the typedef.
8415 return CFConstantStringTagDecl;
8416}
8417
8418// getCFConstantStringType - Return the type used for constant CFStrings.
8423
8425 if (ObjCSuperType.isNull()) {
8426 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8427 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8428 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8429 }
8430 return ObjCSuperType;
8431}
8432
8434 const auto *TT = T->castAs<TypedefType>();
8435 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8436 CFConstantStringTagDecl = TT->castAsRecordDecl();
8437}
8438
8440 if (BlockDescriptorType)
8441 return getCanonicalTagType(BlockDescriptorType);
8442
8443 RecordDecl *RD;
8444 // FIXME: Needs the FlagAppleBlock bit.
8445 RD = buildImplicitRecord("__block_descriptor");
8446 RD->startDefinition();
8447
8448 QualType FieldTypes[] = {
8451 };
8452
8453 static const char *const FieldNames[] = {
8454 "reserved",
8455 "Size"
8456 };
8457
8458 for (size_t i = 0; i < 2; ++i) {
8460 *this, RD, SourceLocation(), SourceLocation(),
8461 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8462 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8463 Field->setAccess(AS_public);
8464 RD->addDecl(Field);
8465 }
8466
8467 RD->completeDefinition();
8468
8469 BlockDescriptorType = RD;
8470
8471 return getCanonicalTagType(BlockDescriptorType);
8472}
8473
8475 if (BlockDescriptorExtendedType)
8476 return getCanonicalTagType(BlockDescriptorExtendedType);
8477
8478 RecordDecl *RD;
8479 // FIXME: Needs the FlagAppleBlock bit.
8480 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8481 RD->startDefinition();
8482
8483 QualType FieldTypes[] = {
8488 };
8489
8490 static const char *const FieldNames[] = {
8491 "reserved",
8492 "Size",
8493 "CopyFuncPtr",
8494 "DestroyFuncPtr"
8495 };
8496
8497 for (size_t i = 0; i < 4; ++i) {
8499 *this, RD, SourceLocation(), SourceLocation(),
8500 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8501 /*BitWidth=*/nullptr,
8502 /*Mutable=*/false, ICIS_NoInit);
8503 Field->setAccess(AS_public);
8504 RD->addDecl(Field);
8505 }
8506
8507 RD->completeDefinition();
8508
8509 BlockDescriptorExtendedType = RD;
8510 return getCanonicalTagType(BlockDescriptorExtendedType);
8511}
8512
8514 const auto *BT = dyn_cast<BuiltinType>(T);
8515
8516 if (!BT) {
8517 if (isa<PipeType>(T))
8518 return OCLTK_Pipe;
8519
8520 return OCLTK_Default;
8521 }
8522
8523 switch (BT->getKind()) {
8524#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8525 case BuiltinType::Id: \
8526 return OCLTK_Image;
8527#include "clang/Basic/OpenCLImageTypes.def"
8528
8529 case BuiltinType::OCLClkEvent:
8530 return OCLTK_ClkEvent;
8531
8532 case BuiltinType::OCLEvent:
8533 return OCLTK_Event;
8534
8535 case BuiltinType::OCLQueue:
8536 return OCLTK_Queue;
8537
8538 case BuiltinType::OCLReserveID:
8539 return OCLTK_ReserveID;
8540
8541 case BuiltinType::OCLSampler:
8542 return OCLTK_Sampler;
8543
8544 default:
8545 return OCLTK_Default;
8546 }
8547}
8548
8550 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8551}
8552
8553/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8554/// requires copy/dispose. Note that this must match the logic
8555/// in buildByrefHelpers.
8557 const VarDecl *D) {
8558 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8559 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8560 if (!copyExpr && record->hasTrivialDestructor()) return false;
8561
8562 return true;
8563 }
8564
8566 return true;
8567
8568 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8569 // move or destroy.
8571 return true;
8572
8573 if (!Ty->isObjCRetainableType()) return false;
8574
8575 Qualifiers qs = Ty.getQualifiers();
8576
8577 // If we have lifetime, that dominates.
8578 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8579 switch (lifetime) {
8580 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8581
8582 // These are just bits as far as the runtime is concerned.
8585 return false;
8586
8587 // These cases should have been taken care of when checking the type's
8588 // non-triviality.
8591 llvm_unreachable("impossible");
8592 }
8593 llvm_unreachable("fell out of lifetime switch!");
8594 }
8595 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8597}
8598
8600 Qualifiers::ObjCLifetime &LifeTime,
8601 bool &HasByrefExtendedLayout) const {
8602 if (!getLangOpts().ObjC ||
8603 getLangOpts().getGC() != LangOptions::NonGC)
8604 return false;
8605
8606 HasByrefExtendedLayout = false;
8607 if (Ty->isRecordType()) {
8608 HasByrefExtendedLayout = true;
8609 LifeTime = Qualifiers::OCL_None;
8610 } else if ((LifeTime = Ty.getObjCLifetime())) {
8611 // Honor the ARC qualifiers.
8612 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8613 // The MRR rule.
8615 } else {
8616 LifeTime = Qualifiers::OCL_None;
8617 }
8618 return true;
8619}
8620
8622 assert(Target && "Expected target to be initialized");
8623 const llvm::Triple &T = Target->getTriple();
8624 // Windows is LLP64 rather than LP64
8625 if (T.isOSWindows() && T.isArch64Bit())
8626 return UnsignedLongLongTy;
8627 return UnsignedLongTy;
8628}
8629
8631 assert(Target && "Expected target to be initialized");
8632 const llvm::Triple &T = Target->getTriple();
8633 // Windows is LLP64 rather than LP64
8634 if (T.isOSWindows() && T.isArch64Bit())
8635 return LongLongTy;
8636 return LongTy;
8637}
8638
8640 if (!ObjCInstanceTypeDecl)
8641 ObjCInstanceTypeDecl =
8642 buildImplicitTypedef(getObjCIdType(), "instancetype");
8643 return ObjCInstanceTypeDecl;
8644}
8645
8646// This returns true if a type has been typedefed to BOOL:
8647// typedef <type> BOOL;
8649 if (const auto *TT = dyn_cast<TypedefType>(T))
8650 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8651 return II->isStr("BOOL");
8652
8653 return false;
8654}
8655
8656/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8657/// purpose.
8659 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8660 return CharUnits::Zero();
8661
8663
8664 // Make all integer and enum types at least as large as an int
8665 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8666 sz = std::max(sz, getTypeSizeInChars(IntTy));
8667 // Treat arrays as pointers, since that's how they're passed in.
8668 else if (type->isArrayType())
8670 return sz;
8671}
8672
8679
8682 if (!VD->isInline())
8684
8685 // In almost all cases, it's a weak definition.
8686 auto *First = VD->getFirstDecl();
8687 if (First->isInlineSpecified() || !First->isStaticDataMember())
8689
8690 // If there's a file-context declaration in this translation unit, it's a
8691 // non-discardable definition.
8692 for (auto *D : VD->redecls())
8694 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8696
8697 // If we've not seen one yet, we don't know.
8699}
8700
8701static std::string charUnitsToString(const CharUnits &CU) {
8702 return llvm::itostr(CU.getQuantity());
8703}
8704
8705/// getObjCEncodingForBlock - Return the encoded type for this block
8706/// declaration.
8708 std::string S;
8709
8710 const BlockDecl *Decl = Expr->getBlockDecl();
8711 QualType BlockTy =
8713 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8714 // Encode result type.
8715 if (getLangOpts().EncodeExtendedBlockSig)
8717 true /*Extended*/);
8718 else
8719 getObjCEncodingForType(BlockReturnTy, S);
8720 // Compute size of all parameters.
8721 // Start with computing size of a pointer in number of bytes.
8722 // FIXME: There might(should) be a better way of doing this computation!
8724 CharUnits ParmOffset = PtrSize;
8725 for (auto *PI : Decl->parameters()) {
8726 QualType PType = PI->getType();
8728 if (sz.isZero())
8729 continue;
8730 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8731 ParmOffset += sz;
8732 }
8733 // Size of the argument frame
8734 S += charUnitsToString(ParmOffset);
8735 // Block pointer and offset.
8736 S += "@?0";
8737
8738 // Argument types.
8739 ParmOffset = PtrSize;
8740 for (auto *PVDecl : Decl->parameters()) {
8741 QualType PType = PVDecl->getOriginalType();
8742 if (const auto *AT =
8743 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8744 // Use array's original type only if it has known number of
8745 // elements.
8746 if (!isa<ConstantArrayType>(AT))
8747 PType = PVDecl->getType();
8748 } else if (PType->isFunctionType())
8749 PType = PVDecl->getType();
8750 if (getLangOpts().EncodeExtendedBlockSig)
8752 S, true /*Extended*/);
8753 else
8754 getObjCEncodingForType(PType, S);
8755 S += charUnitsToString(ParmOffset);
8756 ParmOffset += getObjCEncodingTypeSize(PType);
8757 }
8758
8759 return S;
8760}
8761
8762std::string
8764 std::string S;
8765 // Encode result type.
8766 getObjCEncodingForType(Decl->getReturnType(), S);
8767 CharUnits ParmOffset;
8768 // Compute size of all parameters.
8769 for (auto *PI : Decl->parameters()) {
8770 QualType PType = PI->getType();
8772 if (sz.isZero())
8773 continue;
8774
8775 assert(sz.isPositive() &&
8776 "getObjCEncodingForFunctionDecl - Incomplete param type");
8777 ParmOffset += sz;
8778 }
8779 S += charUnitsToString(ParmOffset);
8780 ParmOffset = CharUnits::Zero();
8781
8782 // Argument types.
8783 for (auto *PVDecl : Decl->parameters()) {
8784 QualType PType = PVDecl->getOriginalType();
8785 if (const auto *AT =
8786 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8787 // Use array's original type only if it has known number of
8788 // elements.
8789 if (!isa<ConstantArrayType>(AT))
8790 PType = PVDecl->getType();
8791 } else if (PType->isFunctionType())
8792 PType = PVDecl->getType();
8793 getObjCEncodingForType(PType, S);
8794 S += charUnitsToString(ParmOffset);
8795 ParmOffset += getObjCEncodingTypeSize(PType);
8796 }
8797
8798 return S;
8799}
8800
8801/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8802/// method parameter or return type. If Extended, include class names and
8803/// block object types.
8805 QualType T, std::string& S,
8806 bool Extended) const {
8807 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8809 // Encode parameter type.
8810 ObjCEncOptions Options = ObjCEncOptions()
8811 .setExpandPointedToStructures()
8812 .setExpandStructures()
8813 .setIsOutermostType();
8814 if (Extended)
8815 Options.setEncodeBlockParameters().setEncodeClassNames();
8816 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8817}
8818
8819/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8820/// declaration.
8822 bool Extended) const {
8823 // FIXME: This is not very efficient.
8824 // Encode return type.
8825 std::string S;
8826 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8827 Decl->getReturnType(), S, Extended);
8828 // Compute size of all parameters.
8829 // Start with computing size of a pointer in number of bytes.
8830 // FIXME: There might(should) be a better way of doing this computation!
8832 // The first two arguments (self and _cmd) are pointers; account for
8833 // their size.
8834 CharUnits ParmOffset = 2 * PtrSize;
8835 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8836 E = Decl->sel_param_end(); PI != E; ++PI) {
8837 QualType PType = (*PI)->getType();
8839 if (sz.isZero())
8840 continue;
8841
8842 assert(sz.isPositive() &&
8843 "getObjCEncodingForMethodDecl - Incomplete param type");
8844 ParmOffset += sz;
8845 }
8846 S += charUnitsToString(ParmOffset);
8847 S += "@0:";
8848 S += charUnitsToString(PtrSize);
8849
8850 // Argument types.
8851 ParmOffset = 2 * PtrSize;
8852 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8853 E = Decl->sel_param_end(); PI != E; ++PI) {
8854 const ParmVarDecl *PVDecl = *PI;
8855 QualType PType = PVDecl->getOriginalType();
8856 if (const auto *AT =
8857 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8858 // Use array's original type only if it has known number of
8859 // elements.
8860 if (!isa<ConstantArrayType>(AT))
8861 PType = PVDecl->getType();
8862 } else if (PType->isFunctionType())
8863 PType = PVDecl->getType();
8865 PType, S, Extended);
8866 S += charUnitsToString(ParmOffset);
8867 ParmOffset += getObjCEncodingTypeSize(PType);
8868 }
8869
8870 return S;
8871}
8872
8875 const ObjCPropertyDecl *PD,
8876 const Decl *Container) const {
8877 if (!Container)
8878 return nullptr;
8879 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8880 for (auto *PID : CID->property_impls())
8881 if (PID->getPropertyDecl() == PD)
8882 return PID;
8883 } else {
8884 const auto *OID = cast<ObjCImplementationDecl>(Container);
8885 for (auto *PID : OID->property_impls())
8886 if (PID->getPropertyDecl() == PD)
8887 return PID;
8888 }
8889 return nullptr;
8890}
8891
8892/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8893/// property declaration. If non-NULL, Container must be either an
8894/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8895/// NULL when getting encodings for protocol properties.
8896/// Property attributes are stored as a comma-delimited C string. The simple
8897/// attributes readonly and bycopy are encoded as single characters. The
8898/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8899/// encoded as single characters, followed by an identifier. Property types
8900/// are also encoded as a parametrized attribute. The characters used to encode
8901/// these attributes are defined by the following enumeration:
8902/// @code
8903/// enum PropertyAttributes {
8904/// kPropertyReadOnly = 'R', // property is read-only.
8905/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8906/// kPropertyByref = '&', // property is a reference to the value last assigned
8907/// kPropertyDynamic = 'D', // property is dynamic
8908/// kPropertyGetter = 'G', // followed by getter selector name
8909/// kPropertySetter = 'S', // followed by setter selector name
8910/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8911/// kPropertyType = 'T' // followed by old-style type encoding.
8912/// kPropertyWeak = 'W' // 'weak' property
8913/// kPropertyStrong = 'P' // property GC'able
8914/// kPropertyNonAtomic = 'N' // property non-atomic
8915/// kPropertyOptional = '?' // property optional
8916/// };
8917/// @endcode
8918std::string
8920 const Decl *Container) const {
8921 // Collect information from the property implementation decl(s).
8922 bool Dynamic = false;
8923 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8924
8925 if (ObjCPropertyImplDecl *PropertyImpDecl =
8927 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8928 Dynamic = true;
8929 else
8930 SynthesizePID = PropertyImpDecl;
8931 }
8932
8933 // FIXME: This is not very efficient.
8934 std::string S = "T";
8935
8936 // Encode result type.
8937 // GCC has some special rules regarding encoding of properties which
8938 // closely resembles encoding of ivars.
8940
8941 if (PD->isOptional())
8942 S += ",?";
8943
8944 if (PD->isReadOnly()) {
8945 S += ",R";
8947 S += ",C";
8949 S += ",&";
8951 S += ",W";
8952 } else {
8953 switch (PD->getSetterKind()) {
8954 case ObjCPropertyDecl::Assign: break;
8955 case ObjCPropertyDecl::Copy: S += ",C"; break;
8956 case ObjCPropertyDecl::Retain: S += ",&"; break;
8957 case ObjCPropertyDecl::Weak: S += ",W"; break;
8958 }
8959 }
8960
8961 // It really isn't clear at all what this means, since properties
8962 // are "dynamic by default".
8963 if (Dynamic)
8964 S += ",D";
8965
8967 S += ",N";
8968
8970 S += ",G";
8971 S += PD->getGetterName().getAsString();
8972 }
8973
8975 S += ",S";
8976 S += PD->getSetterName().getAsString();
8977 }
8978
8979 if (SynthesizePID) {
8980 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
8981 S += ",V";
8982 S += OID->getNameAsString();
8983 }
8984
8985 // FIXME: OBJCGC: weak & strong
8986 return S;
8987}
8988
8989/// getLegacyIntegralTypeEncoding -
8990/// Another legacy compatibility encoding: 32-bit longs are encoded as
8991/// 'l' or 'L' , but not always. For typedefs, we need to use
8992/// 'i' or 'I' instead if encoding a struct field, or a pointer!
8994 if (PointeeTy->getAs<TypedefType>()) {
8995 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
8996 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
8997 PointeeTy = UnsignedIntTy;
8998 else
8999 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9000 PointeeTy = IntTy;
9001 }
9002 }
9003}
9004
9006 const FieldDecl *Field,
9007 QualType *NotEncodedT) const {
9008 // We follow the behavior of gcc, expanding structures which are
9009 // directly pointed to, and expanding embedded structures. Note that
9010 // these rules are sufficient to prevent recursive encoding of the
9011 // same type.
9012 getObjCEncodingForTypeImpl(T, S,
9013 ObjCEncOptions()
9014 .setExpandPointedToStructures()
9015 .setExpandStructures()
9016 .setIsOutermostType(),
9017 Field, NotEncodedT);
9018}
9019
9021 std::string& S) const {
9022 // Encode result type.
9023 // GCC has some special rules regarding encoding of properties which
9024 // closely resembles encoding of ivars.
9025 getObjCEncodingForTypeImpl(T, S,
9026 ObjCEncOptions()
9027 .setExpandPointedToStructures()
9028 .setExpandStructures()
9029 .setIsOutermostType()
9030 .setEncodingProperty(),
9031 /*Field=*/nullptr);
9032}
9033
9035 const BuiltinType *BT) {
9036 BuiltinType::Kind kind = BT->getKind();
9037 switch (kind) {
9038 case BuiltinType::Void: return 'v';
9039 case BuiltinType::Bool: return 'B';
9040 case BuiltinType::Char8:
9041 case BuiltinType::Char_U:
9042 case BuiltinType::UChar: return 'C';
9043 case BuiltinType::Char16:
9044 case BuiltinType::UShort: return 'S';
9045 case BuiltinType::Char32:
9046 case BuiltinType::UInt: return 'I';
9047 case BuiltinType::ULong:
9048 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9049 case BuiltinType::UInt128: return 'T';
9050 case BuiltinType::ULongLong: return 'Q';
9051 case BuiltinType::Char_S:
9052 case BuiltinType::SChar: return 'c';
9053 case BuiltinType::Short: return 's';
9054 case BuiltinType::WChar_S:
9055 case BuiltinType::WChar_U:
9056 case BuiltinType::Int: return 'i';
9057 case BuiltinType::Long:
9058 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9059 case BuiltinType::LongLong: return 'q';
9060 case BuiltinType::Int128: return 't';
9061 case BuiltinType::Float: return 'f';
9062 case BuiltinType::Double: return 'd';
9063 case BuiltinType::LongDouble: return 'D';
9064 case BuiltinType::NullPtr: return '*'; // like char*
9065
9066 case BuiltinType::BFloat16:
9067 case BuiltinType::Float16:
9068 case BuiltinType::Float128:
9069 case BuiltinType::Ibm128:
9070 case BuiltinType::Half:
9071 case BuiltinType::ShortAccum:
9072 case BuiltinType::Accum:
9073 case BuiltinType::LongAccum:
9074 case BuiltinType::UShortAccum:
9075 case BuiltinType::UAccum:
9076 case BuiltinType::ULongAccum:
9077 case BuiltinType::ShortFract:
9078 case BuiltinType::Fract:
9079 case BuiltinType::LongFract:
9080 case BuiltinType::UShortFract:
9081 case BuiltinType::UFract:
9082 case BuiltinType::ULongFract:
9083 case BuiltinType::SatShortAccum:
9084 case BuiltinType::SatAccum:
9085 case BuiltinType::SatLongAccum:
9086 case BuiltinType::SatUShortAccum:
9087 case BuiltinType::SatUAccum:
9088 case BuiltinType::SatULongAccum:
9089 case BuiltinType::SatShortFract:
9090 case BuiltinType::SatFract:
9091 case BuiltinType::SatLongFract:
9092 case BuiltinType::SatUShortFract:
9093 case BuiltinType::SatUFract:
9094 case BuiltinType::SatULongFract:
9095 // FIXME: potentially need @encodes for these!
9096 return ' ';
9097
9098#define SVE_TYPE(Name, Id, SingletonId) \
9099 case BuiltinType::Id:
9100#include "clang/Basic/AArch64ACLETypes.def"
9101#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9102#include "clang/Basic/RISCVVTypes.def"
9103#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9104#include "clang/Basic/WebAssemblyReferenceTypes.def"
9105#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9106#include "clang/Basic/AMDGPUTypes.def"
9107 {
9108 DiagnosticsEngine &Diags = C->getDiagnostics();
9109 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9110 "cannot yet @encode type %0");
9111 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9112 return ' ';
9113 }
9114
9115 case BuiltinType::ObjCId:
9116 case BuiltinType::ObjCClass:
9117 case BuiltinType::ObjCSel:
9118 llvm_unreachable("@encoding ObjC primitive type");
9119
9120 // OpenCL and placeholder types don't need @encodings.
9121#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9122 case BuiltinType::Id:
9123#include "clang/Basic/OpenCLImageTypes.def"
9124#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9125 case BuiltinType::Id:
9126#include "clang/Basic/OpenCLExtensionTypes.def"
9127 case BuiltinType::OCLEvent:
9128 case BuiltinType::OCLClkEvent:
9129 case BuiltinType::OCLQueue:
9130 case BuiltinType::OCLReserveID:
9131 case BuiltinType::OCLSampler:
9132 case BuiltinType::Dependent:
9133#define PPC_VECTOR_TYPE(Name, Id, Size) \
9134 case BuiltinType::Id:
9135#include "clang/Basic/PPCTypes.def"
9136#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9137#include "clang/Basic/HLSLIntangibleTypes.def"
9138#define BUILTIN_TYPE(KIND, ID)
9139#define PLACEHOLDER_TYPE(KIND, ID) \
9140 case BuiltinType::KIND:
9141#include "clang/AST/BuiltinTypes.def"
9142 llvm_unreachable("invalid builtin type for @encode");
9143 }
9144 llvm_unreachable("invalid BuiltinType::Kind value");
9145}
9146
9147static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9149
9150 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9151 if (!Enum->isFixed())
9152 return 'i';
9153
9154 // The encoding of a fixed enum type matches its fixed underlying type.
9155 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9157}
9158
9159static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9160 QualType T, const FieldDecl *FD) {
9161 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9162 S += 'b';
9163 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9164 // The GNU runtime requires more information; bitfields are encoded as b,
9165 // then the offset (in bits) of the first element, then the type of the
9166 // bitfield, then the size in bits. For example, in this structure:
9167 //
9168 // struct
9169 // {
9170 // int integer;
9171 // int flags:2;
9172 // };
9173 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9174 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9175 // information is not especially sensible, but we're stuck with it for
9176 // compatibility with GCC, although providing it breaks anything that
9177 // actually uses runtime introspection and wants to work on both runtimes...
9178 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9179 uint64_t Offset;
9180
9181 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9182 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9183 } else {
9184 const RecordDecl *RD = FD->getParent();
9185 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9186 Offset = RL.getFieldOffset(FD->getFieldIndex());
9187 }
9188
9189 S += llvm::utostr(Offset);
9190
9191 if (const auto *ET = T->getAsCanonical<EnumType>())
9192 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9193 else {
9194 const auto *BT = T->castAs<BuiltinType>();
9195 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9196 }
9197 }
9198 S += llvm::utostr(FD->getBitWidthValue());
9199}
9200
9201// Helper function for determining whether the encoded type string would include
9202// a template specialization type.
9204 bool VisitBasesAndFields) {
9205 T = T->getBaseElementTypeUnsafe();
9206
9207 if (auto *PT = T->getAs<PointerType>())
9209 PT->getPointeeType().getTypePtr(), false);
9210
9211 auto *CXXRD = T->getAsCXXRecordDecl();
9212
9213 if (!CXXRD)
9214 return false;
9215
9217 return true;
9218
9219 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9220 return false;
9221
9222 for (const auto &B : CXXRD->bases())
9223 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9224 true))
9225 return true;
9226
9227 for (auto *FD : CXXRD->fields())
9228 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9229 true))
9230 return true;
9231
9232 return false;
9233}
9234
9235// FIXME: Use SmallString for accumulating string.
9236void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9237 const ObjCEncOptions Options,
9238 const FieldDecl *FD,
9239 QualType *NotEncodedT) const {
9241 switch (CT->getTypeClass()) {
9242 case Type::Builtin:
9243 case Type::Enum:
9244 if (FD && FD->isBitField())
9245 return EncodeBitField(this, S, T, FD);
9246 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9247 S += getObjCEncodingForPrimitiveType(this, BT);
9248 else
9249 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9250 return;
9251
9252 case Type::Complex:
9253 S += 'j';
9254 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9255 ObjCEncOptions(),
9256 /*Field=*/nullptr);
9257 return;
9258
9259 case Type::Atomic:
9260 S += 'A';
9261 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9262 ObjCEncOptions(),
9263 /*Field=*/nullptr);
9264 return;
9265
9266 // encoding for pointer or reference types.
9267 case Type::Pointer:
9268 case Type::LValueReference:
9269 case Type::RValueReference: {
9270 QualType PointeeTy;
9271 if (isa<PointerType>(CT)) {
9272 const auto *PT = T->castAs<PointerType>();
9273 if (PT->isObjCSelType()) {
9274 S += ':';
9275 return;
9276 }
9277 PointeeTy = PT->getPointeeType();
9278 } else {
9279 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9280 }
9281
9282 bool isReadOnly = false;
9283 // For historical/compatibility reasons, the read-only qualifier of the
9284 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9285 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9286 // Also, do not emit the 'r' for anything but the outermost type!
9287 if (T->getAs<TypedefType>()) {
9288 if (Options.IsOutermostType() && T.isConstQualified()) {
9289 isReadOnly = true;
9290 S += 'r';
9291 }
9292 } else if (Options.IsOutermostType()) {
9293 QualType P = PointeeTy;
9294 while (auto PT = P->getAs<PointerType>())
9295 P = PT->getPointeeType();
9296 if (P.isConstQualified()) {
9297 isReadOnly = true;
9298 S += 'r';
9299 }
9300 }
9301 if (isReadOnly) {
9302 // Another legacy compatibility encoding. Some ObjC qualifier and type
9303 // combinations need to be rearranged.
9304 // Rewrite "in const" from "nr" to "rn"
9305 if (StringRef(S).ends_with("nr"))
9306 S.replace(S.end()-2, S.end(), "rn");
9307 }
9308
9309 if (PointeeTy->isCharType()) {
9310 // char pointer types should be encoded as '*' unless it is a
9311 // type that has been typedef'd to 'BOOL'.
9312 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9313 S += '*';
9314 return;
9315 }
9316 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9317 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9318 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9319 if (II == &Idents.get("objc_class")) {
9320 S += '#';
9321 return;
9322 }
9323 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9324 if (II == &Idents.get("objc_object")) {
9325 S += '@';
9326 return;
9327 }
9328 // If the encoded string for the class includes template names, just emit
9329 // "^v" for pointers to the class.
9330 if (getLangOpts().CPlusPlus &&
9331 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9333 RTy, Options.ExpandPointedToStructures()))) {
9334 S += "^v";
9335 return;
9336 }
9337 // fall through...
9338 }
9339 S += '^';
9341
9342 ObjCEncOptions NewOptions;
9343 if (Options.ExpandPointedToStructures())
9344 NewOptions.setExpandStructures();
9345 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9346 /*Field=*/nullptr, NotEncodedT);
9347 return;
9348 }
9349
9350 case Type::ConstantArray:
9351 case Type::IncompleteArray:
9352 case Type::VariableArray: {
9353 const auto *AT = cast<ArrayType>(CT);
9354
9355 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9356 // Incomplete arrays are encoded as a pointer to the array element.
9357 S += '^';
9358
9359 getObjCEncodingForTypeImpl(
9360 AT->getElementType(), S,
9361 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9362 } else {
9363 S += '[';
9364
9365 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9366 S += llvm::utostr(CAT->getZExtSize());
9367 else {
9368 //Variable length arrays are encoded as a regular array with 0 elements.
9370 "Unknown array type!");
9371 S += '0';
9372 }
9373
9374 getObjCEncodingForTypeImpl(
9375 AT->getElementType(), S,
9376 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9377 NotEncodedT);
9378 S += ']';
9379 }
9380 return;
9381 }
9382
9383 case Type::FunctionNoProto:
9384 case Type::FunctionProto:
9385 S += '?';
9386 return;
9387
9388 case Type::Record: {
9389 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9390 S += RDecl->isUnion() ? '(' : '{';
9391 // Anonymous structures print as '?'
9392 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9393 S += II->getName();
9394 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9395 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9396 llvm::raw_string_ostream OS(S);
9397 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9399 }
9400 } else {
9401 S += '?';
9402 }
9403 if (Options.ExpandStructures()) {
9404 S += '=';
9405 if (!RDecl->isUnion()) {
9406 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9407 } else {
9408 for (const auto *Field : RDecl->fields()) {
9409 if (FD) {
9410 S += '"';
9411 S += Field->getNameAsString();
9412 S += '"';
9413 }
9414
9415 // Special case bit-fields.
9416 if (Field->isBitField()) {
9417 getObjCEncodingForTypeImpl(Field->getType(), S,
9418 ObjCEncOptions().setExpandStructures(),
9419 Field);
9420 } else {
9421 QualType qt = Field->getType();
9423 getObjCEncodingForTypeImpl(
9424 qt, S,
9425 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9426 NotEncodedT);
9427 }
9428 }
9429 }
9430 }
9431 S += RDecl->isUnion() ? ')' : '}';
9432 return;
9433 }
9434
9435 case Type::BlockPointer: {
9436 const auto *BT = T->castAs<BlockPointerType>();
9437 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9438 if (Options.EncodeBlockParameters()) {
9439 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9440
9441 S += '<';
9442 // Block return type
9443 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9444 Options.forComponentType(), FD, NotEncodedT);
9445 // Block self
9446 S += "@?";
9447 // Block parameters
9448 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9449 for (const auto &I : FPT->param_types())
9450 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9451 NotEncodedT);
9452 }
9453 S += '>';
9454 }
9455 return;
9456 }
9457
9458 case Type::ObjCObject: {
9459 // hack to match legacy encoding of *id and *Class
9460 QualType Ty = getObjCObjectPointerType(CT);
9461 if (Ty->isObjCIdType()) {
9462 S += "{objc_object=}";
9463 return;
9464 }
9465 else if (Ty->isObjCClassType()) {
9466 S += "{objc_class=}";
9467 return;
9468 }
9469 // TODO: Double check to make sure this intentionally falls through.
9470 [[fallthrough]];
9471 }
9472
9473 case Type::ObjCInterface: {
9474 // Ignore protocol qualifiers when mangling at this level.
9475 // @encode(class_name)
9476 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9477 S += '{';
9478 S += OI->getObjCRuntimeNameAsString();
9479 if (Options.ExpandStructures()) {
9480 S += '=';
9481 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9482 DeepCollectObjCIvars(OI, true, Ivars);
9483 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9484 const FieldDecl *Field = Ivars[i];
9485 if (Field->isBitField())
9486 getObjCEncodingForTypeImpl(Field->getType(), S,
9487 ObjCEncOptions().setExpandStructures(),
9488 Field);
9489 else
9490 getObjCEncodingForTypeImpl(Field->getType(), S,
9491 ObjCEncOptions().setExpandStructures(), FD,
9492 NotEncodedT);
9493 }
9494 }
9495 S += '}';
9496 return;
9497 }
9498
9499 case Type::ObjCObjectPointer: {
9500 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9501 if (OPT->isObjCIdType()) {
9502 S += '@';
9503 return;
9504 }
9505
9506 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9507 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9508 // Since this is a binary compatibility issue, need to consult with
9509 // runtime folks. Fortunately, this is a *very* obscure construct.
9510 S += '#';
9511 return;
9512 }
9513
9514 if (OPT->isObjCQualifiedIdType()) {
9515 getObjCEncodingForTypeImpl(
9516 getObjCIdType(), S,
9517 Options.keepingOnly(ObjCEncOptions()
9518 .setExpandPointedToStructures()
9519 .setExpandStructures()),
9520 FD);
9521 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9522 // Note that we do extended encoding of protocol qualifier list
9523 // Only when doing ivar or property encoding.
9524 S += '"';
9525 for (const auto *I : OPT->quals()) {
9526 S += '<';
9527 S += I->getObjCRuntimeNameAsString();
9528 S += '>';
9529 }
9530 S += '"';
9531 }
9532 return;
9533 }
9534
9535 S += '@';
9536 if (OPT->getInterfaceDecl() &&
9537 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9538 S += '"';
9539 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9540 for (const auto *I : OPT->quals()) {
9541 S += '<';
9542 S += I->getObjCRuntimeNameAsString();
9543 S += '>';
9544 }
9545 S += '"';
9546 }
9547 return;
9548 }
9549
9550 // gcc just blithely ignores member pointers.
9551 // FIXME: we should do better than that. 'M' is available.
9552 case Type::MemberPointer:
9553 // This matches gcc's encoding, even though technically it is insufficient.
9554 //FIXME. We should do a better job than gcc.
9555 case Type::Vector:
9556 case Type::ExtVector:
9557 // Until we have a coherent encoding of these three types, issue warning.
9558 if (NotEncodedT)
9559 *NotEncodedT = T;
9560 return;
9561
9562 case Type::ConstantMatrix:
9563 if (NotEncodedT)
9564 *NotEncodedT = T;
9565 return;
9566
9567 case Type::BitInt:
9568 if (NotEncodedT)
9569 *NotEncodedT = T;
9570 return;
9571
9572 // We could see an undeduced auto type here during error recovery.
9573 // Just ignore it.
9574 case Type::Auto:
9575 case Type::DeducedTemplateSpecialization:
9576 return;
9577
9578 case Type::HLSLAttributedResource:
9579 case Type::HLSLInlineSpirv:
9580 llvm_unreachable("unexpected type");
9581
9582 case Type::ArrayParameter:
9583 case Type::Pipe:
9584#define ABSTRACT_TYPE(KIND, BASE)
9585#define TYPE(KIND, BASE)
9586#define DEPENDENT_TYPE(KIND, BASE) \
9587 case Type::KIND:
9588#define NON_CANONICAL_TYPE(KIND, BASE) \
9589 case Type::KIND:
9590#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9591 case Type::KIND:
9592#include "clang/AST/TypeNodes.inc"
9593 llvm_unreachable("@encode for dependent type!");
9594 }
9595 llvm_unreachable("bad type kind!");
9596}
9597
9598void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9599 std::string &S,
9600 const FieldDecl *FD,
9601 bool includeVBases,
9602 QualType *NotEncodedT) const {
9603 assert(RDecl && "Expected non-null RecordDecl");
9604 assert(!RDecl->isUnion() && "Should not be called for unions");
9605 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9606 return;
9607
9608 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9609 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9610 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9611
9612 if (CXXRec) {
9613 for (const auto &BI : CXXRec->bases()) {
9614 if (!BI.isVirtual()) {
9615 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9616 if (base->isEmpty())
9617 continue;
9618 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9619 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9620 std::make_pair(offs, base));
9621 }
9622 }
9623 }
9624
9625 for (FieldDecl *Field : RDecl->fields()) {
9626 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9627 continue;
9628 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9629 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9630 std::make_pair(offs, Field));
9631 }
9632
9633 if (CXXRec && includeVBases) {
9634 for (const auto &BI : CXXRec->vbases()) {
9635 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9636 if (base->isEmpty())
9637 continue;
9638 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9639 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9640 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9641 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9642 std::make_pair(offs, base));
9643 }
9644 }
9645
9646 CharUnits size;
9647 if (CXXRec) {
9648 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9649 } else {
9650 size = layout.getSize();
9651 }
9652
9653#ifndef NDEBUG
9654 uint64_t CurOffs = 0;
9655#endif
9656 std::multimap<uint64_t, NamedDecl *>::iterator
9657 CurLayObj = FieldOrBaseOffsets.begin();
9658
9659 if (CXXRec && CXXRec->isDynamicClass() &&
9660 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9661 if (FD) {
9662 S += "\"_vptr$";
9663 std::string recname = CXXRec->getNameAsString();
9664 if (recname.empty()) recname = "?";
9665 S += recname;
9666 S += '"';
9667 }
9668 S += "^^?";
9669#ifndef NDEBUG
9670 CurOffs += getTypeSize(VoidPtrTy);
9671#endif
9672 }
9673
9674 if (!RDecl->hasFlexibleArrayMember()) {
9675 // Mark the end of the structure.
9676 uint64_t offs = toBits(size);
9677 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9678 std::make_pair(offs, nullptr));
9679 }
9680
9681 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9682#ifndef NDEBUG
9683 assert(CurOffs <= CurLayObj->first);
9684 if (CurOffs < CurLayObj->first) {
9685 uint64_t padding = CurLayObj->first - CurOffs;
9686 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9687 // packing/alignment of members is different that normal, in which case
9688 // the encoding will be out-of-sync with the real layout.
9689 // If the runtime switches to just consider the size of types without
9690 // taking into account alignment, we could make padding explicit in the
9691 // encoding (e.g. using arrays of chars). The encoding strings would be
9692 // longer then though.
9693 CurOffs += padding;
9694 }
9695#endif
9696
9697 NamedDecl *dcl = CurLayObj->second;
9698 if (!dcl)
9699 break; // reached end of structure.
9700
9701 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9702 // We expand the bases without their virtual bases since those are going
9703 // in the initial structure. Note that this differs from gcc which
9704 // expands virtual bases each time one is encountered in the hierarchy,
9705 // making the encoding type bigger than it really is.
9706 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9707 NotEncodedT);
9708 assert(!base->isEmpty());
9709#ifndef NDEBUG
9710 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9711#endif
9712 } else {
9713 const auto *field = cast<FieldDecl>(dcl);
9714 if (FD) {
9715 S += '"';
9716 S += field->getNameAsString();
9717 S += '"';
9718 }
9719
9720 if (field->isBitField()) {
9721 EncodeBitField(this, S, field->getType(), field);
9722#ifndef NDEBUG
9723 CurOffs += field->getBitWidthValue();
9724#endif
9725 } else {
9726 QualType qt = field->getType();
9728 getObjCEncodingForTypeImpl(
9729 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9730 FD, NotEncodedT);
9731#ifndef NDEBUG
9732 CurOffs += getTypeSize(field->getType());
9733#endif
9734 }
9735 }
9736 }
9737}
9738
9740 std::string& S) const {
9741 if (QT & Decl::OBJC_TQ_In)
9742 S += 'n';
9743 if (QT & Decl::OBJC_TQ_Inout)
9744 S += 'N';
9745 if (QT & Decl::OBJC_TQ_Out)
9746 S += 'o';
9747 if (QT & Decl::OBJC_TQ_Bycopy)
9748 S += 'O';
9749 if (QT & Decl::OBJC_TQ_Byref)
9750 S += 'R';
9751 if (QT & Decl::OBJC_TQ_Oneway)
9752 S += 'V';
9753}
9754
9756 if (!ObjCIdDecl) {
9759 ObjCIdDecl = buildImplicitTypedef(T, "id");
9760 }
9761 return ObjCIdDecl;
9762}
9763
9765 if (!ObjCSelDecl) {
9767 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9768 }
9769 return ObjCSelDecl;
9770}
9771
9773 if (!ObjCClassDecl) {
9776 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9777 }
9778 return ObjCClassDecl;
9779}
9780
9782 if (!ObjCProtocolClassDecl) {
9783 ObjCProtocolClassDecl
9786 &Idents.get("Protocol"),
9787 /*typeParamList=*/nullptr,
9788 /*PrevDecl=*/nullptr,
9789 SourceLocation(), true);
9790 }
9791
9792 return ObjCProtocolClassDecl;
9793}
9794
9796 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9797 return PointerAuthQualifier();
9799 getLangOpts().PointerAuthObjcInterfaceSelKey,
9800 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9802 /*isIsaPointer=*/false,
9803 /*authenticatesNullValues=*/false);
9804}
9805
9806//===----------------------------------------------------------------------===//
9807// __builtin_va_list Construction Functions
9808//===----------------------------------------------------------------------===//
9809
9811 StringRef Name) {
9812 // typedef char* __builtin[_ms]_va_list;
9813 QualType T = Context->getPointerType(Context->CharTy);
9814 return Context->buildImplicitTypedef(T, Name);
9815}
9816
9818 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9819}
9820
9822 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9823}
9824
9826 // typedef void* __builtin_va_list;
9827 QualType T = Context->getPointerType(Context->VoidTy);
9828 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9829}
9830
9831static TypedefDecl *
9833 // struct __va_list
9834 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9835 if (Context->getLangOpts().CPlusPlus) {
9836 // namespace std { struct __va_list {
9837 auto *NS = NamespaceDecl::Create(
9838 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9839 /*Inline=*/false, SourceLocation(), SourceLocation(),
9840 &Context->Idents.get("std"),
9841 /*PrevDecl=*/nullptr, /*Nested=*/false);
9842 NS->setImplicit();
9844 }
9845
9846 VaListTagDecl->startDefinition();
9847
9848 const size_t NumFields = 5;
9849 QualType FieldTypes[NumFields];
9850 const char *FieldNames[NumFields];
9851
9852 // void *__stack;
9853 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9854 FieldNames[0] = "__stack";
9855
9856 // void *__gr_top;
9857 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9858 FieldNames[1] = "__gr_top";
9859
9860 // void *__vr_top;
9861 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9862 FieldNames[2] = "__vr_top";
9863
9864 // int __gr_offs;
9865 FieldTypes[3] = Context->IntTy;
9866 FieldNames[3] = "__gr_offs";
9867
9868 // int __vr_offs;
9869 FieldTypes[4] = Context->IntTy;
9870 FieldNames[4] = "__vr_offs";
9871
9872 // Create fields
9873 for (unsigned i = 0; i < NumFields; ++i) {
9874 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9878 &Context->Idents.get(FieldNames[i]),
9879 FieldTypes[i], /*TInfo=*/nullptr,
9880 /*BitWidth=*/nullptr,
9881 /*Mutable=*/false,
9882 ICIS_NoInit);
9883 Field->setAccess(AS_public);
9884 VaListTagDecl->addDecl(Field);
9885 }
9886 VaListTagDecl->completeDefinition();
9887 Context->VaListTagDecl = VaListTagDecl;
9888 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9889
9890 // } __builtin_va_list;
9891 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9892}
9893
9895 // typedef struct __va_list_tag {
9897
9898 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9899 VaListTagDecl->startDefinition();
9900
9901 const size_t NumFields = 5;
9902 QualType FieldTypes[NumFields];
9903 const char *FieldNames[NumFields];
9904
9905 // unsigned char gpr;
9906 FieldTypes[0] = Context->UnsignedCharTy;
9907 FieldNames[0] = "gpr";
9908
9909 // unsigned char fpr;
9910 FieldTypes[1] = Context->UnsignedCharTy;
9911 FieldNames[1] = "fpr";
9912
9913 // unsigned short reserved;
9914 FieldTypes[2] = Context->UnsignedShortTy;
9915 FieldNames[2] = "reserved";
9916
9917 // void* overflow_arg_area;
9918 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9919 FieldNames[3] = "overflow_arg_area";
9920
9921 // void* reg_save_area;
9922 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9923 FieldNames[4] = "reg_save_area";
9924
9925 // Create fields
9926 for (unsigned i = 0; i < NumFields; ++i) {
9927 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9930 &Context->Idents.get(FieldNames[i]),
9931 FieldTypes[i], /*TInfo=*/nullptr,
9932 /*BitWidth=*/nullptr,
9933 /*Mutable=*/false,
9934 ICIS_NoInit);
9935 Field->setAccess(AS_public);
9936 VaListTagDecl->addDecl(Field);
9937 }
9938 VaListTagDecl->completeDefinition();
9939 Context->VaListTagDecl = VaListTagDecl;
9940 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9941
9942 // } __va_list_tag;
9943 TypedefDecl *VaListTagTypedefDecl =
9944 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
9945
9946 QualType VaListTagTypedefType =
9947 Context->getTypedefType(ElaboratedTypeKeyword::None,
9948 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
9949
9950 // typedef __va_list_tag __builtin_va_list[1];
9951 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
9952 QualType VaListTagArrayType = Context->getConstantArrayType(
9953 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
9954 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
9955}
9956
9957static TypedefDecl *
9959 // struct __va_list_tag {
9961 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9962 VaListTagDecl->startDefinition();
9963
9964 const size_t NumFields = 4;
9965 QualType FieldTypes[NumFields];
9966 const char *FieldNames[NumFields];
9967
9968 // unsigned gp_offset;
9969 FieldTypes[0] = Context->UnsignedIntTy;
9970 FieldNames[0] = "gp_offset";
9971
9972 // unsigned fp_offset;
9973 FieldTypes[1] = Context->UnsignedIntTy;
9974 FieldNames[1] = "fp_offset";
9975
9976 // void* overflow_arg_area;
9977 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9978 FieldNames[2] = "overflow_arg_area";
9979
9980 // void* reg_save_area;
9981 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9982 FieldNames[3] = "reg_save_area";
9983
9984 // Create fields
9985 for (unsigned i = 0; i < NumFields; ++i) {
9986 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9990 &Context->Idents.get(FieldNames[i]),
9991 FieldTypes[i], /*TInfo=*/nullptr,
9992 /*BitWidth=*/nullptr,
9993 /*Mutable=*/false,
9994 ICIS_NoInit);
9995 Field->setAccess(AS_public);
9996 VaListTagDecl->addDecl(Field);
9997 }
9998 VaListTagDecl->completeDefinition();
9999 Context->VaListTagDecl = VaListTagDecl;
10000 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10001
10002 // };
10003
10004 // typedef struct __va_list_tag __builtin_va_list[1];
10005 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10006 QualType VaListTagArrayType = Context->getConstantArrayType(
10007 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10008 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10009}
10010
10011static TypedefDecl *
10013 // struct __va_list
10014 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10015 if (Context->getLangOpts().CPlusPlus) {
10016 // namespace std { struct __va_list {
10017 NamespaceDecl *NS;
10018 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10019 Context->getTranslationUnitDecl(),
10020 /*Inline=*/false, SourceLocation(),
10021 SourceLocation(), &Context->Idents.get("std"),
10022 /*PrevDecl=*/nullptr, /*Nested=*/false);
10023 NS->setImplicit();
10024 VaListDecl->setDeclContext(NS);
10025 }
10026
10027 VaListDecl->startDefinition();
10028
10029 // void * __ap;
10030 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10031 VaListDecl,
10034 &Context->Idents.get("__ap"),
10035 Context->getPointerType(Context->VoidTy),
10036 /*TInfo=*/nullptr,
10037 /*BitWidth=*/nullptr,
10038 /*Mutable=*/false,
10039 ICIS_NoInit);
10040 Field->setAccess(AS_public);
10041 VaListDecl->addDecl(Field);
10042
10043 // };
10044 VaListDecl->completeDefinition();
10045 Context->VaListTagDecl = VaListDecl;
10046
10047 // typedef struct __va_list __builtin_va_list;
10048 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10049 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10050}
10051
10052static TypedefDecl *
10054 // struct __va_list_tag {
10056 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10057 VaListTagDecl->startDefinition();
10058
10059 const size_t NumFields = 4;
10060 QualType FieldTypes[NumFields];
10061 const char *FieldNames[NumFields];
10062
10063 // long __gpr;
10064 FieldTypes[0] = Context->LongTy;
10065 FieldNames[0] = "__gpr";
10066
10067 // long __fpr;
10068 FieldTypes[1] = Context->LongTy;
10069 FieldNames[1] = "__fpr";
10070
10071 // void *__overflow_arg_area;
10072 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10073 FieldNames[2] = "__overflow_arg_area";
10074
10075 // void *__reg_save_area;
10076 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10077 FieldNames[3] = "__reg_save_area";
10078
10079 // Create fields
10080 for (unsigned i = 0; i < NumFields; ++i) {
10081 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10085 &Context->Idents.get(FieldNames[i]),
10086 FieldTypes[i], /*TInfo=*/nullptr,
10087 /*BitWidth=*/nullptr,
10088 /*Mutable=*/false,
10089 ICIS_NoInit);
10090 Field->setAccess(AS_public);
10091 VaListTagDecl->addDecl(Field);
10092 }
10093 VaListTagDecl->completeDefinition();
10094 Context->VaListTagDecl = VaListTagDecl;
10095 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10096
10097 // };
10098
10099 // typedef __va_list_tag __builtin_va_list[1];
10100 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10101 QualType VaListTagArrayType = Context->getConstantArrayType(
10102 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10103
10104 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10105}
10106
10108 // typedef struct __va_list_tag {
10110 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10111 VaListTagDecl->startDefinition();
10112
10113 const size_t NumFields = 3;
10114 QualType FieldTypes[NumFields];
10115 const char *FieldNames[NumFields];
10116
10117 // void *CurrentSavedRegisterArea;
10118 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10119 FieldNames[0] = "__current_saved_reg_area_pointer";
10120
10121 // void *SavedRegAreaEnd;
10122 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10123 FieldNames[1] = "__saved_reg_area_end_pointer";
10124
10125 // void *OverflowArea;
10126 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10127 FieldNames[2] = "__overflow_area_pointer";
10128
10129 // Create fields
10130 for (unsigned i = 0; i < NumFields; ++i) {
10132 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10133 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10134 /*TInfo=*/nullptr,
10135 /*BitWidth=*/nullptr,
10136 /*Mutable=*/false, ICIS_NoInit);
10137 Field->setAccess(AS_public);
10138 VaListTagDecl->addDecl(Field);
10139 }
10140 VaListTagDecl->completeDefinition();
10141 Context->VaListTagDecl = VaListTagDecl;
10142 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10143
10144 // } __va_list_tag;
10145 TypedefDecl *VaListTagTypedefDecl =
10146 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10147
10148 QualType VaListTagTypedefType =
10149 Context->getTypedefType(ElaboratedTypeKeyword::None,
10150 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10151
10152 // typedef __va_list_tag __builtin_va_list[1];
10153 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10154 QualType VaListTagArrayType = Context->getConstantArrayType(
10155 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10156
10157 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10158}
10159
10160static TypedefDecl *
10162 // typedef struct __va_list_tag {
10163 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10164
10165 VaListTagDecl->startDefinition();
10166
10167 // int* __va_stk;
10168 // int* __va_reg;
10169 // int __va_ndx;
10170 constexpr size_t NumFields = 3;
10171 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10172 Context->getPointerType(Context->IntTy),
10173 Context->IntTy};
10174 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10175
10176 // Create fields
10177 for (unsigned i = 0; i < NumFields; ++i) {
10180 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10181 /*BitWidth=*/nullptr,
10182 /*Mutable=*/false, ICIS_NoInit);
10183 Field->setAccess(AS_public);
10184 VaListTagDecl->addDecl(Field);
10185 }
10186 VaListTagDecl->completeDefinition();
10187 Context->VaListTagDecl = VaListTagDecl;
10188 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10189
10190 // } __va_list_tag;
10191 TypedefDecl *VaListTagTypedefDecl =
10192 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10193
10194 return VaListTagTypedefDecl;
10195}
10196
10199 switch (Kind) {
10201 return CreateCharPtrBuiltinVaListDecl(Context);
10203 return CreateVoidPtrBuiltinVaListDecl(Context);
10205 return CreateAArch64ABIBuiltinVaListDecl(Context);
10207 return CreatePowerABIBuiltinVaListDecl(Context);
10209 return CreateX86_64ABIBuiltinVaListDecl(Context);
10211 return CreateAAPCSABIBuiltinVaListDecl(Context);
10213 return CreateSystemZBuiltinVaListDecl(Context);
10215 return CreateHexagonBuiltinVaListDecl(Context);
10217 return CreateXtensaABIBuiltinVaListDecl(Context);
10218 }
10219
10220 llvm_unreachable("Unhandled __builtin_va_list type kind");
10221}
10222
10224 if (!BuiltinVaListDecl) {
10225 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10226 assert(BuiltinVaListDecl->isImplicit());
10227 }
10228
10229 return BuiltinVaListDecl;
10230}
10231
10233 // Force the creation of VaListTagDecl by building the __builtin_va_list
10234 // declaration.
10235 if (!VaListTagDecl)
10236 (void)getBuiltinVaListDecl();
10237
10238 return VaListTagDecl;
10239}
10240
10242 if (!BuiltinMSVaListDecl)
10243 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10244
10245 return BuiltinMSVaListDecl;
10246}
10247
10249 // Allow redecl custom type checking builtin for HLSL.
10250 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10251 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10252 return true;
10253 // Allow redecl custom type checking builtin for SPIR-V.
10254 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10255 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10256 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10257 return true;
10258 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10259}
10260
10262 assert(ObjCConstantStringType.isNull() &&
10263 "'NSConstantString' type already set!");
10264
10265 ObjCConstantStringType = getObjCInterfaceType(Decl);
10266}
10267
10268/// Retrieve the template name that corresponds to a non-empty
10269/// lookup.
10272 UnresolvedSetIterator End) const {
10273 unsigned size = End - Begin;
10274 assert(size > 1 && "set is not overloaded!");
10275
10276 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10277 size * sizeof(FunctionTemplateDecl*));
10278 auto *OT = new (memory) OverloadedTemplateStorage(size);
10279
10280 NamedDecl **Storage = OT->getStorage();
10281 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10282 NamedDecl *D = *I;
10283 assert(isa<FunctionTemplateDecl>(D) ||
10287 *Storage++ = D;
10288 }
10289
10290 return TemplateName(OT);
10291}
10292
10293/// Retrieve a template name representing an unqualified-id that has been
10294/// assumed to name a template for ADL purposes.
10296 auto *OT = new (*this) AssumedTemplateStorage(Name);
10297 return TemplateName(OT);
10298}
10299
10300/// Retrieve the template name that represents a qualified
10301/// template name such as \c std::vector.
10303 bool TemplateKeyword,
10304 TemplateName Template) const {
10305 assert(Template.getKind() == TemplateName::Template ||
10307
10308 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10309 assert(!Qualifier && "unexpected qualified template template parameter");
10310 assert(TemplateKeyword == false);
10311 return Template;
10312 }
10313
10314 // FIXME: Canonicalization?
10315 llvm::FoldingSetNodeID ID;
10316 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10317
10318 void *InsertPos = nullptr;
10320 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10321 if (!QTN) {
10322 QTN = new (*this, alignof(QualifiedTemplateName))
10323 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10324 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10325 }
10326
10327 return TemplateName(QTN);
10328}
10329
10330/// Retrieve the template name that represents a dependent
10331/// template name such as \c MetaFun::template operator+.
10334 llvm::FoldingSetNodeID ID;
10335 S.Profile(ID);
10336
10337 void *InsertPos = nullptr;
10338 if (DependentTemplateName *QTN =
10339 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10340 return TemplateName(QTN);
10341
10343 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10344 DependentTemplateNames.InsertNode(QTN, InsertPos);
10345 return TemplateName(QTN);
10346}
10347
10349 Decl *AssociatedDecl,
10350 unsigned Index,
10351 UnsignedOrNone PackIndex,
10352 bool Final) const {
10353 llvm::FoldingSetNodeID ID;
10354 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10355 Index, PackIndex, Final);
10356
10357 void *insertPos = nullptr;
10359 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10360
10361 if (!subst) {
10362 subst = new (*this) SubstTemplateTemplateParmStorage(
10363 Replacement, AssociatedDecl, Index, PackIndex, Final);
10364 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10365 }
10366
10367 return TemplateName(subst);
10368}
10369
10372 Decl *AssociatedDecl,
10373 unsigned Index, bool Final) const {
10374 auto &Self = const_cast<ASTContext &>(*this);
10375 llvm::FoldingSetNodeID ID;
10377 AssociatedDecl, Index, Final);
10378
10379 void *InsertPos = nullptr;
10381 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10382
10383 if (!Subst) {
10384 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10385 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10386 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10387 }
10388
10389 return TemplateName(Subst);
10390}
10391
10392/// Retrieve the template name that represents a template name
10393/// deduced from a specialization.
10396 DefaultArguments DefaultArgs) const {
10397 if (!DefaultArgs)
10398 return Underlying;
10399
10400 llvm::FoldingSetNodeID ID;
10401 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10402
10403 void *InsertPos = nullptr;
10405 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10406 if (!DTS) {
10407 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10408 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10409 alignof(DeducedTemplateStorage));
10410 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10411 DeducedTemplates.InsertNode(DTS, InsertPos);
10412 }
10413 return TemplateName(DTS);
10414}
10415
10416/// getFromTargetType - Given one of the integer types provided by
10417/// TargetInfo, produce the corresponding type. The unsigned @p Type
10418/// is actually a value of type @c TargetInfo::IntType.
10419CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10420 switch (Type) {
10421 case TargetInfo::NoInt: return {};
10424 case TargetInfo::SignedShort: return ShortTy;
10426 case TargetInfo::SignedInt: return IntTy;
10428 case TargetInfo::SignedLong: return LongTy;
10432 }
10433
10434 llvm_unreachable("Unhandled TargetInfo::IntType value");
10435}
10436
10437//===----------------------------------------------------------------------===//
10438// Type Predicates.
10439//===----------------------------------------------------------------------===//
10440
10441/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10442/// garbage collection attribute.
10443///
10445 if (getLangOpts().getGC() == LangOptions::NonGC)
10446 return Qualifiers::GCNone;
10447
10448 assert(getLangOpts().ObjC);
10449 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10450
10451 // Default behaviour under objective-C's gc is for ObjC pointers
10452 // (or pointers to them) be treated as though they were declared
10453 // as __strong.
10454 if (GCAttrs == Qualifiers::GCNone) {
10456 return Qualifiers::Strong;
10457 else if (Ty->isPointerType())
10459 } else {
10460 // It's not valid to set GC attributes on anything that isn't a
10461 // pointer.
10462#ifndef NDEBUG
10464 while (const auto *AT = dyn_cast<ArrayType>(CT))
10465 CT = AT->getElementType();
10466 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10467#endif
10468 }
10469 return GCAttrs;
10470}
10471
10472//===----------------------------------------------------------------------===//
10473// Type Compatibility Testing
10474//===----------------------------------------------------------------------===//
10475
10476/// areCompatVectorTypes - Return true if the two specified vector types are
10477/// compatible.
10478static bool areCompatVectorTypes(const VectorType *LHS,
10479 const VectorType *RHS) {
10480 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10481 return LHS->getElementType() == RHS->getElementType() &&
10482 LHS->getNumElements() == RHS->getNumElements();
10483}
10484
10485/// areCompatMatrixTypes - Return true if the two specified matrix types are
10486/// compatible.
10488 const ConstantMatrixType *RHS) {
10489 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10490 return LHS->getElementType() == RHS->getElementType() &&
10491 LHS->getNumRows() == RHS->getNumRows() &&
10492 LHS->getNumColumns() == RHS->getNumColumns();
10493}
10494
10496 QualType SecondVec) {
10497 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10498 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10499
10500 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10501 return true;
10502
10503 // Treat Neon vector types and most AltiVec vector types as if they are the
10504 // equivalent GCC vector types.
10505 const auto *First = FirstVec->castAs<VectorType>();
10506 const auto *Second = SecondVec->castAs<VectorType>();
10507 if (First->getNumElements() == Second->getNumElements() &&
10508 hasSameType(First->getElementType(), Second->getElementType()) &&
10509 First->getVectorKind() != VectorKind::AltiVecPixel &&
10510 First->getVectorKind() != VectorKind::AltiVecBool &&
10513 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10514 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10517 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10519 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10521 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10523 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10525 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10527 return true;
10528
10529 return false;
10530}
10531
10532/// getRVVTypeSize - Return RVV vector register size.
10533static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10534 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10535 auto VScale = Context.getTargetInfo().getVScaleRange(
10536 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10537 if (!VScale)
10538 return 0;
10539
10540 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10541
10542 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10543 if (Info.ElementType == Context.BoolTy)
10544 EltSize = 1;
10545
10546 uint64_t MinElts = Info.EC.getKnownMinValue();
10547 return VScale->first * MinElts * EltSize;
10548}
10549
10551 QualType SecondType) {
10552 assert(
10553 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10554 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10555 "Expected RVV builtin type and vector type!");
10556
10557 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10558 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10559 if (const auto *VT = SecondType->getAs<VectorType>()) {
10560 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10562 return FirstType->isRVVVLSBuiltinType() &&
10563 Info.ElementType == BoolTy &&
10564 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10565 }
10566 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10568 return FirstType->isRVVVLSBuiltinType() &&
10569 Info.ElementType == BoolTy &&
10570 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10571 }
10572 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10574 return FirstType->isRVVVLSBuiltinType() &&
10575 Info.ElementType == BoolTy &&
10576 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10577 }
10578 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10580 return FirstType->isRVVVLSBuiltinType() &&
10581 Info.ElementType == BoolTy &&
10582 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10583 }
10584 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10585 VT->getVectorKind() == VectorKind::Generic)
10586 return FirstType->isRVVVLSBuiltinType() &&
10587 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10588 hasSameType(VT->getElementType(),
10589 getBuiltinVectorTypeInfo(BT).ElementType);
10590 }
10591 }
10592 return false;
10593 };
10594
10595 return IsValidCast(FirstType, SecondType) ||
10596 IsValidCast(SecondType, FirstType);
10597}
10598
10600 QualType SecondType) {
10601 assert(
10602 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10603 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10604 "Expected RVV builtin type and vector type!");
10605
10606 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10607 const auto *BT = FirstType->getAs<BuiltinType>();
10608 if (!BT)
10609 return false;
10610
10611 if (!BT->isRVVVLSBuiltinType())
10612 return false;
10613
10614 const auto *VecTy = SecondType->getAs<VectorType>();
10615 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10617 getLangOpts().getLaxVectorConversions();
10618
10619 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10620 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10621 return false;
10622
10623 // If -flax-vector-conversions=all is specified, the types are
10624 // certainly compatible.
10626 return true;
10627
10628 // If -flax-vector-conversions=integer is specified, the types are
10629 // compatible if the elements are integer types.
10631 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10632 FirstType->getRVVEltType(*this)->isIntegerType();
10633 }
10634
10635 return false;
10636 };
10637
10638 return IsLaxCompatible(FirstType, SecondType) ||
10639 IsLaxCompatible(SecondType, FirstType);
10640}
10641
10643 while (true) {
10644 // __strong id
10645 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10646 if (Attr->getAttrKind() == attr::ObjCOwnership)
10647 return true;
10648
10649 Ty = Attr->getModifiedType();
10650
10651 // X *__strong (...)
10652 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10653 Ty = Paren->getInnerType();
10654
10655 // We do not want to look through typedefs, typeof(expr),
10656 // typeof(type), or any other way that the type is somehow
10657 // abstracted.
10658 } else {
10659 return false;
10660 }
10661 }
10662}
10663
10664//===----------------------------------------------------------------------===//
10665// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10666//===----------------------------------------------------------------------===//
10667
10668/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10669/// inheritance hierarchy of 'rProto'.
10670bool
10672 ObjCProtocolDecl *rProto) const {
10673 if (declaresSameEntity(lProto, rProto))
10674 return true;
10675 for (auto *PI : rProto->protocols())
10676 if (ProtocolCompatibleWithProtocol(lProto, PI))
10677 return true;
10678 return false;
10679}
10680
10681/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10682/// Class<pr1, ...>.
10684 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10685 for (auto *lhsProto : lhs->quals()) {
10686 bool match = false;
10687 for (auto *rhsProto : rhs->quals()) {
10688 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10689 match = true;
10690 break;
10691 }
10692 }
10693 if (!match)
10694 return false;
10695 }
10696 return true;
10697}
10698
10699/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10700/// ObjCQualifiedIDType.
10702 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10703 bool compare) {
10704 // Allow id<P..> and an 'id' in all cases.
10705 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10706 return true;
10707
10708 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10709 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10711 return false;
10712
10713 if (lhs->isObjCQualifiedIdType()) {
10714 if (rhs->qual_empty()) {
10715 // If the RHS is a unqualified interface pointer "NSString*",
10716 // make sure we check the class hierarchy.
10717 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10718 for (auto *I : lhs->quals()) {
10719 // when comparing an id<P> on lhs with a static type on rhs,
10720 // see if static class implements all of id's protocols, directly or
10721 // through its super class and categories.
10722 if (!rhsID->ClassImplementsProtocol(I, true))
10723 return false;
10724 }
10725 }
10726 // If there are no qualifiers and no interface, we have an 'id'.
10727 return true;
10728 }
10729 // Both the right and left sides have qualifiers.
10730 for (auto *lhsProto : lhs->quals()) {
10731 bool match = false;
10732
10733 // when comparing an id<P> on lhs with a static type on rhs,
10734 // see if static class implements all of id's protocols, directly or
10735 // through its super class and categories.
10736 for (auto *rhsProto : rhs->quals()) {
10737 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10738 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10739 match = true;
10740 break;
10741 }
10742 }
10743 // If the RHS is a qualified interface pointer "NSString<P>*",
10744 // make sure we check the class hierarchy.
10745 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10746 for (auto *I : lhs->quals()) {
10747 // when comparing an id<P> on lhs with a static type on rhs,
10748 // see if static class implements all of id's protocols, directly or
10749 // through its super class and categories.
10750 if (rhsID->ClassImplementsProtocol(I, true)) {
10751 match = true;
10752 break;
10753 }
10754 }
10755 }
10756 if (!match)
10757 return false;
10758 }
10759
10760 return true;
10761 }
10762
10763 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10764
10765 if (lhs->getInterfaceType()) {
10766 // If both the right and left sides have qualifiers.
10767 for (auto *lhsProto : lhs->quals()) {
10768 bool match = false;
10769
10770 // when comparing an id<P> on rhs with a static type on lhs,
10771 // see if static class implements all of id's protocols, directly or
10772 // through its super class and categories.
10773 // First, lhs protocols in the qualifier list must be found, direct
10774 // or indirect in rhs's qualifier list or it is a mismatch.
10775 for (auto *rhsProto : rhs->quals()) {
10776 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10777 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10778 match = true;
10779 break;
10780 }
10781 }
10782 if (!match)
10783 return false;
10784 }
10785
10786 // Static class's protocols, or its super class or category protocols
10787 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10788 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10789 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10790 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10791 // This is rather dubious but matches gcc's behavior. If lhs has
10792 // no type qualifier and its class has no static protocol(s)
10793 // assume that it is mismatch.
10794 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10795 return false;
10796 for (auto *lhsProto : LHSInheritedProtocols) {
10797 bool match = false;
10798 for (auto *rhsProto : rhs->quals()) {
10799 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10800 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10801 match = true;
10802 break;
10803 }
10804 }
10805 if (!match)
10806 return false;
10807 }
10808 }
10809 return true;
10810 }
10811 return false;
10812}
10813
10814/// canAssignObjCInterfaces - Return true if the two interface types are
10815/// compatible for assignment from RHS to LHS. This handles validation of any
10816/// protocol qualifiers on the LHS or RHS.
10818 const ObjCObjectPointerType *RHSOPT) {
10819 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10820 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10821
10822 // If either type represents the built-in 'id' type, return true.
10823 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10824 return true;
10825
10826 // Function object that propagates a successful result or handles
10827 // __kindof types.
10828 auto finish = [&](bool succeeded) -> bool {
10829 if (succeeded)
10830 return true;
10831
10832 if (!RHS->isKindOfType())
10833 return false;
10834
10835 // Strip off __kindof and protocol qualifiers, then check whether
10836 // we can assign the other way.
10838 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10839 };
10840
10841 // Casts from or to id<P> are allowed when the other side has compatible
10842 // protocols.
10843 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10844 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10845 }
10846
10847 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10848 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10849 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10850 }
10851
10852 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10853 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10854 return true;
10855 }
10856
10857 // If we have 2 user-defined types, fall into that path.
10858 if (LHS->getInterface() && RHS->getInterface()) {
10859 return finish(canAssignObjCInterfaces(LHS, RHS));
10860 }
10861
10862 return false;
10863}
10864
10865/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10866/// for providing type-safety for objective-c pointers used to pass/return
10867/// arguments in block literals. When passed as arguments, passing 'A*' where
10868/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10869/// not OK. For the return type, the opposite is not OK.
10871 const ObjCObjectPointerType *LHSOPT,
10872 const ObjCObjectPointerType *RHSOPT,
10873 bool BlockReturnType) {
10874
10875 // Function object that propagates a successful result or handles
10876 // __kindof types.
10877 auto finish = [&](bool succeeded) -> bool {
10878 if (succeeded)
10879 return true;
10880
10881 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10882 if (!Expected->isKindOfType())
10883 return false;
10884
10885 // Strip off __kindof and protocol qualifiers, then check whether
10886 // we can assign the other way.
10888 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10889 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10890 BlockReturnType);
10891 };
10892
10893 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10894 return true;
10895
10896 if (LHSOPT->isObjCBuiltinType()) {
10897 return finish(RHSOPT->isObjCBuiltinType() ||
10898 RHSOPT->isObjCQualifiedIdType());
10899 }
10900
10901 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10902 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10903 // Use for block parameters previous type checking for compatibility.
10904 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10905 // Or corrected type checking as in non-compat mode.
10906 (!BlockReturnType &&
10907 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10908 else
10910 (BlockReturnType ? LHSOPT : RHSOPT),
10911 (BlockReturnType ? RHSOPT : LHSOPT), false));
10912 }
10913
10914 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10915 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10916 if (LHS && RHS) { // We have 2 user-defined types.
10917 if (LHS != RHS) {
10918 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10919 return finish(BlockReturnType);
10920 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10921 return finish(!BlockReturnType);
10922 }
10923 else
10924 return true;
10925 }
10926 return false;
10927}
10928
10929/// Comparison routine for Objective-C protocols to be used with
10930/// llvm::array_pod_sort.
10932 ObjCProtocolDecl * const *rhs) {
10933 return (*lhs)->getName().compare((*rhs)->getName());
10934}
10935
10936/// getIntersectionOfProtocols - This routine finds the intersection of set
10937/// of protocols inherited from two distinct objective-c pointer objects with
10938/// the given common base.
10939/// It is used to build composite qualifier list of the composite type of
10940/// the conditional expression involving two objective-c pointer objects.
10941static
10943 const ObjCInterfaceDecl *CommonBase,
10944 const ObjCObjectPointerType *LHSOPT,
10945 const ObjCObjectPointerType *RHSOPT,
10946 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
10947
10948 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10949 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10950 assert(LHS->getInterface() && "LHS must have an interface base");
10951 assert(RHS->getInterface() && "RHS must have an interface base");
10952
10953 // Add all of the protocols for the LHS.
10955
10956 // Start with the protocol qualifiers.
10957 for (auto *proto : LHS->quals()) {
10958 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
10959 }
10960
10961 // Also add the protocols associated with the LHS interface.
10962 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
10963
10964 // Add all of the protocols for the RHS.
10966
10967 // Start with the protocol qualifiers.
10968 for (auto *proto : RHS->quals()) {
10969 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
10970 }
10971
10972 // Also add the protocols associated with the RHS interface.
10973 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
10974
10975 // Compute the intersection of the collected protocol sets.
10976 for (auto *proto : LHSProtocolSet) {
10977 if (RHSProtocolSet.count(proto))
10978 IntersectionSet.push_back(proto);
10979 }
10980
10981 // Compute the set of protocols that is implied by either the common type or
10982 // the protocols within the intersection.
10984 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
10985
10986 // Remove any implied protocols from the list of inherited protocols.
10987 if (!ImpliedProtocols.empty()) {
10988 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
10989 return ImpliedProtocols.contains(proto);
10990 });
10991 }
10992
10993 // Sort the remaining protocols by name.
10994 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
10996}
10997
10998/// Determine whether the first type is a subtype of the second.
11000 QualType rhs) {
11001 // Common case: two object pointers.
11002 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11003 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11004 if (lhsOPT && rhsOPT)
11005 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11006
11007 // Two block pointers.
11008 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11009 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11010 if (lhsBlock && rhsBlock)
11011 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11012
11013 // If either is an unqualified 'id' and the other is a block, it's
11014 // acceptable.
11015 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11016 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11017 return true;
11018
11019 return false;
11020}
11021
11022// Check that the given Objective-C type argument lists are equivalent.
11024 const ObjCInterfaceDecl *iface,
11025 ArrayRef<QualType> lhsArgs,
11026 ArrayRef<QualType> rhsArgs,
11027 bool stripKindOf) {
11028 if (lhsArgs.size() != rhsArgs.size())
11029 return false;
11030
11031 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11032 if (!typeParams)
11033 return false;
11034
11035 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11036 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11037 continue;
11038
11039 switch (typeParams->begin()[i]->getVariance()) {
11041 if (!stripKindOf ||
11042 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11043 rhsArgs[i].stripObjCKindOfType(ctx))) {
11044 return false;
11045 }
11046 break;
11047
11049 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11050 return false;
11051 break;
11052
11054 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11055 return false;
11056 break;
11057 }
11058 }
11059
11060 return true;
11061}
11062
11064 const ObjCObjectPointerType *Lptr,
11065 const ObjCObjectPointerType *Rptr) {
11066 const ObjCObjectType *LHS = Lptr->getObjectType();
11067 const ObjCObjectType *RHS = Rptr->getObjectType();
11068 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11069 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11070
11071 if (!LDecl || !RDecl)
11072 return {};
11073
11074 // When either LHS or RHS is a kindof type, we should return a kindof type.
11075 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11076 // kindof(A).
11077 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11078
11079 // Follow the left-hand side up the class hierarchy until we either hit a
11080 // root or find the RHS. Record the ancestors in case we don't find it.
11081 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11082 LHSAncestors;
11083 while (true) {
11084 // Record this ancestor. We'll need this if the common type isn't in the
11085 // path from the LHS to the root.
11086 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11087
11088 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11089 // Get the type arguments.
11090 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11091 bool anyChanges = false;
11092 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11093 // Both have type arguments, compare them.
11094 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11095 LHS->getTypeArgs(), RHS->getTypeArgs(),
11096 /*stripKindOf=*/true))
11097 return {};
11098 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11099 // If only one has type arguments, the result will not have type
11100 // arguments.
11101 LHSTypeArgs = {};
11102 anyChanges = true;
11103 }
11104
11105 // Compute the intersection of protocols.
11107 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11108 Protocols);
11109 if (!Protocols.empty())
11110 anyChanges = true;
11111
11112 // If anything in the LHS will have changed, build a new result type.
11113 // If we need to return a kindof type but LHS is not a kindof type, we
11114 // build a new result type.
11115 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11116 QualType Result = getObjCInterfaceType(LHS->getInterface());
11117 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11118 anyKindOf || LHS->isKindOfType());
11120 }
11121
11122 return getObjCObjectPointerType(QualType(LHS, 0));
11123 }
11124
11125 // Find the superclass.
11126 QualType LHSSuperType = LHS->getSuperClassType();
11127 if (LHSSuperType.isNull())
11128 break;
11129
11130 LHS = LHSSuperType->castAs<ObjCObjectType>();
11131 }
11132
11133 // We didn't find anything by following the LHS to its root; now check
11134 // the RHS against the cached set of ancestors.
11135 while (true) {
11136 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11137 if (KnownLHS != LHSAncestors.end()) {
11138 LHS = KnownLHS->second;
11139
11140 // Get the type arguments.
11141 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11142 bool anyChanges = false;
11143 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11144 // Both have type arguments, compare them.
11145 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11146 LHS->getTypeArgs(), RHS->getTypeArgs(),
11147 /*stripKindOf=*/true))
11148 return {};
11149 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11150 // If only one has type arguments, the result will not have type
11151 // arguments.
11152 RHSTypeArgs = {};
11153 anyChanges = true;
11154 }
11155
11156 // Compute the intersection of protocols.
11158 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11159 Protocols);
11160 if (!Protocols.empty())
11161 anyChanges = true;
11162
11163 // If we need to return a kindof type but RHS is not a kindof type, we
11164 // build a new result type.
11165 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11166 QualType Result = getObjCInterfaceType(RHS->getInterface());
11167 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11168 anyKindOf || RHS->isKindOfType());
11170 }
11171
11172 return getObjCObjectPointerType(QualType(RHS, 0));
11173 }
11174
11175 // Find the superclass of the RHS.
11176 QualType RHSSuperType = RHS->getSuperClassType();
11177 if (RHSSuperType.isNull())
11178 break;
11179
11180 RHS = RHSSuperType->castAs<ObjCObjectType>();
11181 }
11182
11183 return {};
11184}
11185
11187 const ObjCObjectType *RHS) {
11188 assert(LHS->getInterface() && "LHS is not an interface type");
11189 assert(RHS->getInterface() && "RHS is not an interface type");
11190
11191 // Verify that the base decls are compatible: the RHS must be a subclass of
11192 // the LHS.
11193 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11194 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11195 if (!IsSuperClass)
11196 return false;
11197
11198 // If the LHS has protocol qualifiers, determine whether all of them are
11199 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11200 // LHS).
11201 if (LHS->getNumProtocols() > 0) {
11202 // OK if conversion of LHS to SuperClass results in narrowing of types
11203 // ; i.e., SuperClass may implement at least one of the protocols
11204 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11205 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11206 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11207 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11208 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11209 // qualifiers.
11210 for (auto *RHSPI : RHS->quals())
11211 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11212 // If there is no protocols associated with RHS, it is not a match.
11213 if (SuperClassInheritedProtocols.empty())
11214 return false;
11215
11216 for (const auto *LHSProto : LHS->quals()) {
11217 bool SuperImplementsProtocol = false;
11218 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11219 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11220 SuperImplementsProtocol = true;
11221 break;
11222 }
11223 if (!SuperImplementsProtocol)
11224 return false;
11225 }
11226 }
11227
11228 // If the LHS is specialized, we may need to check type arguments.
11229 if (LHS->isSpecialized()) {
11230 // Follow the superclass chain until we've matched the LHS class in the
11231 // hierarchy. This substitutes type arguments through.
11232 const ObjCObjectType *RHSSuper = RHS;
11233 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11234 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11235
11236 // If the RHS is specializd, compare type arguments.
11237 if (RHSSuper->isSpecialized() &&
11238 !sameObjCTypeArgs(*this, LHS->getInterface(),
11239 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11240 /*stripKindOf=*/true)) {
11241 return false;
11242 }
11243 }
11244
11245 return true;
11246}
11247
11249 // get the "pointed to" types
11250 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11251 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11252
11253 if (!LHSOPT || !RHSOPT)
11254 return false;
11255
11256 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11257 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11258}
11259
11262 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11263 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11264}
11265
11266/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11267/// both shall have the identically qualified version of a compatible type.
11268/// C99 6.2.7p1: Two types have compatible types if their types are the
11269/// same. See 6.7.[2,3,5] for additional rules.
11271 bool CompareUnqualified) {
11272 if (getLangOpts().CPlusPlus)
11273 return hasSameType(LHS, RHS);
11274
11275 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11276}
11277
11279 return typesAreCompatible(LHS, RHS);
11280}
11281
11283 return !mergeTypes(LHS, RHS, true).isNull();
11284}
11285
11286/// mergeTransparentUnionType - if T is a transparent union type and a member
11287/// of T is compatible with SubType, return the merged type, else return
11288/// QualType()
11290 bool OfBlockPointer,
11291 bool Unqualified) {
11292 if (const RecordType *UT = T->getAsUnionType()) {
11293 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11294 if (UD->hasAttr<TransparentUnionAttr>()) {
11295 for (const auto *I : UD->fields()) {
11296 QualType ET = I->getType().getUnqualifiedType();
11297 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11298 if (!MT.isNull())
11299 return MT;
11300 }
11301 }
11302 }
11303
11304 return {};
11305}
11306
11307/// mergeFunctionParameterTypes - merge two types which appear as function
11308/// parameter types
11310 bool OfBlockPointer,
11311 bool Unqualified) {
11312 // GNU extension: two types are compatible if they appear as a function
11313 // argument, one of the types is a transparent union type and the other
11314 // type is compatible with a union member
11315 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11316 Unqualified);
11317 if (!lmerge.isNull())
11318 return lmerge;
11319
11320 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11321 Unqualified);
11322 if (!rmerge.isNull())
11323 return rmerge;
11324
11325 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11326}
11327
11329 bool OfBlockPointer, bool Unqualified,
11330 bool AllowCXX,
11331 bool IsConditionalOperator) {
11332 const auto *lbase = lhs->castAs<FunctionType>();
11333 const auto *rbase = rhs->castAs<FunctionType>();
11334 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11335 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11336 bool allLTypes = true;
11337 bool allRTypes = true;
11338
11339 // Check return type
11340 QualType retType;
11341 if (OfBlockPointer) {
11342 QualType RHS = rbase->getReturnType();
11343 QualType LHS = lbase->getReturnType();
11344 bool UnqualifiedResult = Unqualified;
11345 if (!UnqualifiedResult)
11346 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11347 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11348 }
11349 else
11350 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11351 Unqualified);
11352 if (retType.isNull())
11353 return {};
11354
11355 if (Unqualified)
11356 retType = retType.getUnqualifiedType();
11357
11358 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11359 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11360 if (Unqualified) {
11361 LRetType = LRetType.getUnqualifiedType();
11362 RRetType = RRetType.getUnqualifiedType();
11363 }
11364
11365 if (getCanonicalType(retType) != LRetType)
11366 allLTypes = false;
11367 if (getCanonicalType(retType) != RRetType)
11368 allRTypes = false;
11369
11370 // FIXME: double check this
11371 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11372 // rbase->getRegParmAttr() != 0 &&
11373 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11374 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11375 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11376
11377 // Compatible functions must have compatible calling conventions
11378 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11379 return {};
11380
11381 // Regparm is part of the calling convention.
11382 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11383 return {};
11384 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11385 return {};
11386
11387 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11388 return {};
11389 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11390 return {};
11391 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11392 return {};
11393
11394 // When merging declarations, it's common for supplemental information like
11395 // attributes to only be present in one of the declarations, and we generally
11396 // want type merging to preserve the union of information. So a merged
11397 // function type should be noreturn if it was noreturn in *either* operand
11398 // type.
11399 //
11400 // But for the conditional operator, this is backwards. The result of the
11401 // operator could be either operand, and its type should conservatively
11402 // reflect that. So a function type in a composite type is noreturn only
11403 // if it's noreturn in *both* operand types.
11404 //
11405 // Arguably, noreturn is a kind of subtype, and the conditional operator
11406 // ought to produce the most specific common supertype of its operand types.
11407 // That would differ from this rule in contravariant positions. However,
11408 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11409 // as a practical matter, it would only affect C code that does abstraction of
11410 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11411 // say the least. So we use the simpler rule.
11412 bool NoReturn = IsConditionalOperator
11413 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11414 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11415 if (lbaseInfo.getNoReturn() != NoReturn)
11416 allLTypes = false;
11417 if (rbaseInfo.getNoReturn() != NoReturn)
11418 allRTypes = false;
11419
11420 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11421
11422 std::optional<FunctionEffectSet> MergedFX;
11423
11424 if (lproto && rproto) { // two C99 style function prototypes
11425 assert((AllowCXX ||
11426 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11427 "C++ shouldn't be here");
11428 // Compatible functions must have the same number of parameters
11429 if (lproto->getNumParams() != rproto->getNumParams())
11430 return {};
11431
11432 // Variadic and non-variadic functions aren't compatible
11433 if (lproto->isVariadic() != rproto->isVariadic())
11434 return {};
11435
11436 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11437 return {};
11438
11439 // Function protos with different 'cfi_salt' values aren't compatible.
11440 if (lproto->getExtraAttributeInfo().CFISalt !=
11441 rproto->getExtraAttributeInfo().CFISalt)
11442 return {};
11443
11444 // Function effects are handled similarly to noreturn, see above.
11445 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11446 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11447 if (LHSFX != RHSFX) {
11448 if (IsConditionalOperator)
11449 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11450 else {
11452 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11453 // Here we're discarding a possible error due to conflicts in the effect
11454 // sets. But we're not in a context where we can report it. The
11455 // operation does however guarantee maintenance of invariants.
11456 }
11457 if (*MergedFX != LHSFX)
11458 allLTypes = false;
11459 if (*MergedFX != RHSFX)
11460 allRTypes = false;
11461 }
11462
11464 bool canUseLeft, canUseRight;
11465 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11466 newParamInfos))
11467 return {};
11468
11469 if (!canUseLeft)
11470 allLTypes = false;
11471 if (!canUseRight)
11472 allRTypes = false;
11473
11474 // Check parameter type compatibility
11476 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11477 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11478 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11480 lParamType, rParamType, OfBlockPointer, Unqualified);
11481 if (paramType.isNull())
11482 return {};
11483
11484 if (Unqualified)
11485 paramType = paramType.getUnqualifiedType();
11486
11487 types.push_back(paramType);
11488 if (Unqualified) {
11489 lParamType = lParamType.getUnqualifiedType();
11490 rParamType = rParamType.getUnqualifiedType();
11491 }
11492
11493 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11494 allLTypes = false;
11495 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11496 allRTypes = false;
11497 }
11498
11499 if (allLTypes) return lhs;
11500 if (allRTypes) return rhs;
11501
11502 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11503 EPI.ExtInfo = einfo;
11504 EPI.ExtParameterInfos =
11505 newParamInfos.empty() ? nullptr : newParamInfos.data();
11506 if (MergedFX)
11507 EPI.FunctionEffects = *MergedFX;
11508 return getFunctionType(retType, types, EPI);
11509 }
11510
11511 if (lproto) allRTypes = false;
11512 if (rproto) allLTypes = false;
11513
11514 const FunctionProtoType *proto = lproto ? lproto : rproto;
11515 if (proto) {
11516 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11517 if (proto->isVariadic())
11518 return {};
11519 // Check that the types are compatible with the types that
11520 // would result from default argument promotions (C99 6.7.5.3p15).
11521 // The only types actually affected are promotable integer
11522 // types and floats, which would be passed as a different
11523 // type depending on whether the prototype is visible.
11524 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11525 QualType paramTy = proto->getParamType(i);
11526
11527 // Look at the converted type of enum types, since that is the type used
11528 // to pass enum values.
11529 if (const auto *ED = paramTy->getAsEnumDecl()) {
11530 paramTy = ED->getIntegerType();
11531 if (paramTy.isNull())
11532 return {};
11533 }
11534
11535 if (isPromotableIntegerType(paramTy) ||
11536 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11537 return {};
11538 }
11539
11540 if (allLTypes) return lhs;
11541 if (allRTypes) return rhs;
11542
11544 EPI.ExtInfo = einfo;
11545 if (MergedFX)
11546 EPI.FunctionEffects = *MergedFX;
11547 return getFunctionType(retType, proto->getParamTypes(), EPI);
11548 }
11549
11550 if (allLTypes) return lhs;
11551 if (allRTypes) return rhs;
11552 return getFunctionNoProtoType(retType, einfo);
11553}
11554
11555/// Given that we have an enum type and a non-enum type, try to merge them.
11556static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11557 QualType other, bool isBlockReturnType) {
11558 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11559 // a signed integer type, or an unsigned integer type.
11560 // Compatibility is based on the underlying type, not the promotion
11561 // type.
11562 QualType underlyingType =
11563 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11564 if (underlyingType.isNull())
11565 return {};
11566 if (Context.hasSameType(underlyingType, other))
11567 return other;
11568
11569 // In block return types, we're more permissive and accept any
11570 // integral type of the same size.
11571 if (isBlockReturnType && other->isIntegerType() &&
11572 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11573 return other;
11574
11575 return {};
11576}
11577
11579 // C17 and earlier and C++ disallow two tag definitions within the same TU
11580 // from being compatible.
11581 if (LangOpts.CPlusPlus || !LangOpts.C23)
11582 return {};
11583
11584 // C23, on the other hand, requires the members to be "the same enough", so
11585 // we use a structural equivalence check.
11588 getLangOpts(), *this, *this, NonEquivalentDecls,
11589 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11590 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11591 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11592}
11593
11594QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11595 bool Unqualified, bool BlockReturnType,
11596 bool IsConditionalOperator) {
11597 // For C++ we will not reach this code with reference types (see below),
11598 // for OpenMP variant call overloading we might.
11599 //
11600 // C++ [expr]: If an expression initially has the type "reference to T", the
11601 // type is adjusted to "T" prior to any further analysis, the expression
11602 // designates the object or function denoted by the reference, and the
11603 // expression is an lvalue unless the reference is an rvalue reference and
11604 // the expression is a function call (possibly inside parentheses).
11605 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11606 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11607 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11608 LHS->getTypeClass() == RHS->getTypeClass())
11609 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11610 OfBlockPointer, Unqualified, BlockReturnType);
11611 if (LHSRefTy || RHSRefTy)
11612 return {};
11613
11614 if (Unqualified) {
11615 LHS = LHS.getUnqualifiedType();
11616 RHS = RHS.getUnqualifiedType();
11617 }
11618
11619 QualType LHSCan = getCanonicalType(LHS),
11620 RHSCan = getCanonicalType(RHS);
11621
11622 // If two types are identical, they are compatible.
11623 if (LHSCan == RHSCan)
11624 return LHS;
11625
11626 // If the qualifiers are different, the types aren't compatible... mostly.
11627 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11628 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11629 if (LQuals != RQuals) {
11630 // If any of these qualifiers are different, we have a type
11631 // mismatch.
11632 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11633 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11634 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11635 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11636 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11637 return {};
11638
11639 // Exactly one GC qualifier difference is allowed: __strong is
11640 // okay if the other type has no GC qualifier but is an Objective
11641 // C object pointer (i.e. implicitly strong by default). We fix
11642 // this by pretending that the unqualified type was actually
11643 // qualified __strong.
11644 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11645 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11646 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11647
11648 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11649 return {};
11650
11651 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11653 }
11654 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11656 }
11657 return {};
11658 }
11659
11660 // Okay, qualifiers are equal.
11661
11662 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11663 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11664
11665 // We want to consider the two function types to be the same for these
11666 // comparisons, just force one to the other.
11667 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11668 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11669
11670 // Same as above for arrays
11671 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11672 LHSClass = Type::ConstantArray;
11673 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11674 RHSClass = Type::ConstantArray;
11675
11676 // ObjCInterfaces are just specialized ObjCObjects.
11677 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11678 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11679
11680 // Canonicalize ExtVector -> Vector.
11681 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11682 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11683
11684 // If the canonical type classes don't match.
11685 if (LHSClass != RHSClass) {
11686 // Note that we only have special rules for turning block enum
11687 // returns into block int returns, not vice-versa.
11688 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11689 return mergeEnumWithInteger(*this, ETy, RHS, false);
11690 }
11691 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11692 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11693 }
11694 // allow block pointer type to match an 'id' type.
11695 if (OfBlockPointer && !BlockReturnType) {
11696 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11697 return LHS;
11698 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11699 return RHS;
11700 }
11701 // Allow __auto_type to match anything; it merges to the type with more
11702 // information.
11703 if (const auto *AT = LHS->getAs<AutoType>()) {
11704 if (!AT->isDeduced() && AT->isGNUAutoType())
11705 return RHS;
11706 }
11707 if (const auto *AT = RHS->getAs<AutoType>()) {
11708 if (!AT->isDeduced() && AT->isGNUAutoType())
11709 return LHS;
11710 }
11711 return {};
11712 }
11713
11714 // The canonical type classes match.
11715 switch (LHSClass) {
11716#define TYPE(Class, Base)
11717#define ABSTRACT_TYPE(Class, Base)
11718#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11719#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11720#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11721#include "clang/AST/TypeNodes.inc"
11722 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11723
11724 case Type::Auto:
11725 case Type::DeducedTemplateSpecialization:
11726 case Type::LValueReference:
11727 case Type::RValueReference:
11728 case Type::MemberPointer:
11729 llvm_unreachable("C++ should never be in mergeTypes");
11730
11731 case Type::ObjCInterface:
11732 case Type::IncompleteArray:
11733 case Type::VariableArray:
11734 case Type::FunctionProto:
11735 case Type::ExtVector:
11736 llvm_unreachable("Types are eliminated above");
11737
11738 case Type::Pointer:
11739 {
11740 // Merge two pointer types, while trying to preserve typedef info
11741 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11742 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11743 if (Unqualified) {
11744 LHSPointee = LHSPointee.getUnqualifiedType();
11745 RHSPointee = RHSPointee.getUnqualifiedType();
11746 }
11747 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11748 Unqualified);
11749 if (ResultType.isNull())
11750 return {};
11751 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11752 return LHS;
11753 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11754 return RHS;
11755 return getPointerType(ResultType);
11756 }
11757 case Type::BlockPointer:
11758 {
11759 // Merge two block pointer types, while trying to preserve typedef info
11760 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11761 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11762 if (Unqualified) {
11763 LHSPointee = LHSPointee.getUnqualifiedType();
11764 RHSPointee = RHSPointee.getUnqualifiedType();
11765 }
11766 if (getLangOpts().OpenCL) {
11767 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11768 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11769 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11770 // 6.12.5) thus the following check is asymmetric.
11771 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11772 return {};
11773 LHSPteeQual.removeAddressSpace();
11774 RHSPteeQual.removeAddressSpace();
11775 LHSPointee =
11776 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11777 RHSPointee =
11778 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11779 }
11780 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11781 Unqualified);
11782 if (ResultType.isNull())
11783 return {};
11784 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11785 return LHS;
11786 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11787 return RHS;
11788 return getBlockPointerType(ResultType);
11789 }
11790 case Type::Atomic:
11791 {
11792 // Merge two pointer types, while trying to preserve typedef info
11793 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11794 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11795 if (Unqualified) {
11796 LHSValue = LHSValue.getUnqualifiedType();
11797 RHSValue = RHSValue.getUnqualifiedType();
11798 }
11799 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11800 Unqualified);
11801 if (ResultType.isNull())
11802 return {};
11803 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11804 return LHS;
11805 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11806 return RHS;
11807 return getAtomicType(ResultType);
11808 }
11809 case Type::ConstantArray:
11810 {
11811 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11812 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11813 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11814 return {};
11815
11816 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11817 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11818 if (Unqualified) {
11819 LHSElem = LHSElem.getUnqualifiedType();
11820 RHSElem = RHSElem.getUnqualifiedType();
11821 }
11822
11823 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11824 if (ResultType.isNull())
11825 return {};
11826
11827 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11828 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11829
11830 // If either side is a variable array, and both are complete, check whether
11831 // the current dimension is definite.
11832 if (LVAT || RVAT) {
11833 auto SizeFetch = [this](const VariableArrayType* VAT,
11834 const ConstantArrayType* CAT)
11835 -> std::pair<bool,llvm::APInt> {
11836 if (VAT) {
11837 std::optional<llvm::APSInt> TheInt;
11838 Expr *E = VAT->getSizeExpr();
11839 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11840 return std::make_pair(true, *TheInt);
11841 return std::make_pair(false, llvm::APSInt());
11842 }
11843 if (CAT)
11844 return std::make_pair(true, CAT->getSize());
11845 return std::make_pair(false, llvm::APInt());
11846 };
11847
11848 bool HaveLSize, HaveRSize;
11849 llvm::APInt LSize, RSize;
11850 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11851 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11852 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11853 return {}; // Definite, but unequal, array dimension
11854 }
11855
11856 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11857 return LHS;
11858 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11859 return RHS;
11860 if (LCAT)
11861 return getConstantArrayType(ResultType, LCAT->getSize(),
11862 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11863 if (RCAT)
11864 return getConstantArrayType(ResultType, RCAT->getSize(),
11865 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11866 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11867 return LHS;
11868 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11869 return RHS;
11870 if (LVAT) {
11871 // FIXME: This isn't correct! But tricky to implement because
11872 // the array's size has to be the size of LHS, but the type
11873 // has to be different.
11874 return LHS;
11875 }
11876 if (RVAT) {
11877 // FIXME: This isn't correct! But tricky to implement because
11878 // the array's size has to be the size of RHS, but the type
11879 // has to be different.
11880 return RHS;
11881 }
11882 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11883 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11884 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11885 }
11886 case Type::FunctionNoProto:
11887 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11888 /*AllowCXX=*/false, IsConditionalOperator);
11889 case Type::Record:
11890 case Type::Enum:
11891 return mergeTagDefinitions(LHS, RHS);
11892 case Type::Builtin:
11893 // Only exactly equal builtin types are compatible, which is tested above.
11894 return {};
11895 case Type::Complex:
11896 // Distinct complex types are incompatible.
11897 return {};
11898 case Type::Vector:
11899 // FIXME: The merged type should be an ExtVector!
11900 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11901 RHSCan->castAs<VectorType>()))
11902 return LHS;
11903 return {};
11904 case Type::ConstantMatrix:
11906 RHSCan->castAs<ConstantMatrixType>()))
11907 return LHS;
11908 return {};
11909 case Type::ObjCObject: {
11910 // Check if the types are assignment compatible.
11911 // FIXME: This should be type compatibility, e.g. whether
11912 // "LHS x; RHS x;" at global scope is legal.
11914 RHS->castAs<ObjCObjectType>()))
11915 return LHS;
11916 return {};
11917 }
11918 case Type::ObjCObjectPointer:
11919 if (OfBlockPointer) {
11922 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11923 return LHS;
11924 return {};
11925 }
11928 return LHS;
11929 return {};
11930 case Type::Pipe:
11931 assert(LHS != RHS &&
11932 "Equivalent pipe types should have already been handled!");
11933 return {};
11934 case Type::ArrayParameter:
11935 assert(LHS != RHS &&
11936 "Equivalent ArrayParameter types should have already been handled!");
11937 return {};
11938 case Type::BitInt: {
11939 // Merge two bit-precise int types, while trying to preserve typedef info.
11940 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11941 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11942 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11943 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
11944
11945 // Like unsigned/int, shouldn't have a type if they don't match.
11946 if (LHSUnsigned != RHSUnsigned)
11947 return {};
11948
11949 if (LHSBits != RHSBits)
11950 return {};
11951 return LHS;
11952 }
11953 case Type::HLSLAttributedResource: {
11954 const HLSLAttributedResourceType *LHSTy =
11955 LHS->castAs<HLSLAttributedResourceType>();
11956 const HLSLAttributedResourceType *RHSTy =
11957 RHS->castAs<HLSLAttributedResourceType>();
11958 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
11959 LHSTy->getWrappedType()->isHLSLResourceType() &&
11960 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
11961
11962 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
11963 LHSTy->getContainedType() == RHSTy->getContainedType())
11964 return LHS;
11965 return {};
11966 }
11967 case Type::HLSLInlineSpirv:
11968 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
11969 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
11970
11971 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
11972 LHSTy->getSize() == RHSTy->getSize() &&
11973 LHSTy->getAlignment() == RHSTy->getAlignment()) {
11974 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
11975 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
11976 return {};
11977
11978 return LHS;
11979 }
11980 return {};
11981 }
11982
11983 llvm_unreachable("Invalid Type::Class!");
11984}
11985
11987 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
11988 bool &CanUseFirst, bool &CanUseSecond,
11990 assert(NewParamInfos.empty() && "param info list not empty");
11991 CanUseFirst = CanUseSecond = true;
11992 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
11993 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
11994
11995 // Fast path: if the first type doesn't have ext parameter infos,
11996 // we match if and only if the second type also doesn't have them.
11997 if (!FirstHasInfo && !SecondHasInfo)
11998 return true;
11999
12000 bool NeedParamInfo = false;
12001 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12002 : SecondFnType->getExtParameterInfos().size();
12003
12004 for (size_t I = 0; I < E; ++I) {
12005 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12006 if (FirstHasInfo)
12007 FirstParam = FirstFnType->getExtParameterInfo(I);
12008 if (SecondHasInfo)
12009 SecondParam = SecondFnType->getExtParameterInfo(I);
12010
12011 // Cannot merge unless everything except the noescape flag matches.
12012 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12013 return false;
12014
12015 bool FirstNoEscape = FirstParam.isNoEscape();
12016 bool SecondNoEscape = SecondParam.isNoEscape();
12017 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12018 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12019 if (NewParamInfos.back().getOpaqueValue())
12020 NeedParamInfo = true;
12021 if (FirstNoEscape != IsNoEscape)
12022 CanUseFirst = false;
12023 if (SecondNoEscape != IsNoEscape)
12024 CanUseSecond = false;
12025 }
12026
12027 if (!NeedParamInfo)
12028 NewParamInfos.clear();
12029
12030 return true;
12031}
12032
12034 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12035 It->second = nullptr;
12036 for (auto *SubClass : ObjCSubClasses[D])
12037 ResetObjCLayout(SubClass);
12038 }
12039}
12040
12041/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12042/// 'RHS' attributes and returns the merged version; including for function
12043/// return types.
12045 QualType LHSCan = getCanonicalType(LHS),
12046 RHSCan = getCanonicalType(RHS);
12047 // If two types are identical, they are compatible.
12048 if (LHSCan == RHSCan)
12049 return LHS;
12050 if (RHSCan->isFunctionType()) {
12051 if (!LHSCan->isFunctionType())
12052 return {};
12053 QualType OldReturnType =
12054 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12055 QualType NewReturnType =
12056 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12057 QualType ResReturnType =
12058 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12059 if (ResReturnType.isNull())
12060 return {};
12061 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12062 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12063 // In either case, use OldReturnType to build the new function type.
12064 const auto *F = LHS->castAs<FunctionType>();
12065 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12066 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12067 EPI.ExtInfo = getFunctionExtInfo(LHS);
12068 QualType ResultType =
12069 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12070 return ResultType;
12071 }
12072 }
12073 return {};
12074 }
12075
12076 // If the qualifiers are different, the types can still be merged.
12077 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12078 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12079 if (LQuals != RQuals) {
12080 // If any of these qualifiers are different, we have a type mismatch.
12081 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12082 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12083 return {};
12084
12085 // Exactly one GC qualifier difference is allowed: __strong is
12086 // okay if the other type has no GC qualifier but is an Objective
12087 // C object pointer (i.e. implicitly strong by default). We fix
12088 // this by pretending that the unqualified type was actually
12089 // qualified __strong.
12090 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12091 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12092 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12093
12094 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12095 return {};
12096
12097 if (GC_L == Qualifiers::Strong)
12098 return LHS;
12099 if (GC_R == Qualifiers::Strong)
12100 return RHS;
12101 return {};
12102 }
12103
12104 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12105 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12106 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12107 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12108 if (ResQT == LHSBaseQT)
12109 return LHS;
12110 if (ResQT == RHSBaseQT)
12111 return RHS;
12112 }
12113 return {};
12114}
12115
12116//===----------------------------------------------------------------------===//
12117// Integer Predicates
12118//===----------------------------------------------------------------------===//
12119
12121 if (const auto *ED = T->getAsEnumDecl())
12122 T = ED->getIntegerType();
12123 if (T->isBooleanType())
12124 return 1;
12125 if (const auto *EIT = T->getAs<BitIntType>())
12126 return EIT->getNumBits();
12127 // For builtin types, just use the standard type sizing method
12128 return (unsigned)getTypeSize(T);
12129}
12130
12132 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12133 T->isFixedPointType()) &&
12134 "Unexpected type");
12135
12136 // Turn <4 x signed int> -> <4 x unsigned int>
12137 if (const auto *VTy = T->getAs<VectorType>())
12138 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12139 VTy->getNumElements(), VTy->getVectorKind());
12140
12141 // For _BitInt, return an unsigned _BitInt with same width.
12142 if (const auto *EITy = T->getAs<BitIntType>())
12143 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12144
12145 // For enums, get the underlying integer type of the enum, and let the general
12146 // integer type signchanging code handle it.
12147 if (const auto *ED = T->getAsEnumDecl())
12148 T = ED->getIntegerType();
12149
12150 switch (T->castAs<BuiltinType>()->getKind()) {
12151 case BuiltinType::Char_U:
12152 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12153 case BuiltinType::Char_S:
12154 case BuiltinType::SChar:
12155 case BuiltinType::Char8:
12156 return UnsignedCharTy;
12157 case BuiltinType::Short:
12158 return UnsignedShortTy;
12159 case BuiltinType::Int:
12160 return UnsignedIntTy;
12161 case BuiltinType::Long:
12162 return UnsignedLongTy;
12163 case BuiltinType::LongLong:
12164 return UnsignedLongLongTy;
12165 case BuiltinType::Int128:
12166 return UnsignedInt128Ty;
12167 // wchar_t is special. It is either signed or not, but when it's signed,
12168 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12169 // version of its underlying type instead.
12170 case BuiltinType::WChar_S:
12171 return getUnsignedWCharType();
12172
12173 case BuiltinType::ShortAccum:
12174 return UnsignedShortAccumTy;
12175 case BuiltinType::Accum:
12176 return UnsignedAccumTy;
12177 case BuiltinType::LongAccum:
12178 return UnsignedLongAccumTy;
12179 case BuiltinType::SatShortAccum:
12181 case BuiltinType::SatAccum:
12182 return SatUnsignedAccumTy;
12183 case BuiltinType::SatLongAccum:
12185 case BuiltinType::ShortFract:
12186 return UnsignedShortFractTy;
12187 case BuiltinType::Fract:
12188 return UnsignedFractTy;
12189 case BuiltinType::LongFract:
12190 return UnsignedLongFractTy;
12191 case BuiltinType::SatShortFract:
12193 case BuiltinType::SatFract:
12194 return SatUnsignedFractTy;
12195 case BuiltinType::SatLongFract:
12197 default:
12198 assert((T->hasUnsignedIntegerRepresentation() ||
12199 T->isUnsignedFixedPointType()) &&
12200 "Unexpected signed integer or fixed point type");
12201 return T;
12202 }
12203}
12204
12206 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12207 T->isFixedPointType()) &&
12208 "Unexpected type");
12209
12210 // Turn <4 x unsigned int> -> <4 x signed int>
12211 if (const auto *VTy = T->getAs<VectorType>())
12212 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12213 VTy->getNumElements(), VTy->getVectorKind());
12214
12215 // For _BitInt, return a signed _BitInt with same width.
12216 if (const auto *EITy = T->getAs<BitIntType>())
12217 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12218
12219 // For enums, get the underlying integer type of the enum, and let the general
12220 // integer type signchanging code handle it.
12221 if (const auto *ED = T->getAsEnumDecl())
12222 T = ED->getIntegerType();
12223
12224 switch (T->castAs<BuiltinType>()->getKind()) {
12225 case BuiltinType::Char_S:
12226 // Plain `char` is mapped to `signed char` even if it's already signed
12227 case BuiltinType::Char_U:
12228 case BuiltinType::UChar:
12229 case BuiltinType::Char8:
12230 return SignedCharTy;
12231 case BuiltinType::UShort:
12232 return ShortTy;
12233 case BuiltinType::UInt:
12234 return IntTy;
12235 case BuiltinType::ULong:
12236 return LongTy;
12237 case BuiltinType::ULongLong:
12238 return LongLongTy;
12239 case BuiltinType::UInt128:
12240 return Int128Ty;
12241 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12242 // there's no matching "signed wchar_t". Therefore we return the signed
12243 // version of its underlying type instead.
12244 case BuiltinType::WChar_U:
12245 return getSignedWCharType();
12246
12247 case BuiltinType::UShortAccum:
12248 return ShortAccumTy;
12249 case BuiltinType::UAccum:
12250 return AccumTy;
12251 case BuiltinType::ULongAccum:
12252 return LongAccumTy;
12253 case BuiltinType::SatUShortAccum:
12254 return SatShortAccumTy;
12255 case BuiltinType::SatUAccum:
12256 return SatAccumTy;
12257 case BuiltinType::SatULongAccum:
12258 return SatLongAccumTy;
12259 case BuiltinType::UShortFract:
12260 return ShortFractTy;
12261 case BuiltinType::UFract:
12262 return FractTy;
12263 case BuiltinType::ULongFract:
12264 return LongFractTy;
12265 case BuiltinType::SatUShortFract:
12266 return SatShortFractTy;
12267 case BuiltinType::SatUFract:
12268 return SatFractTy;
12269 case BuiltinType::SatULongFract:
12270 return SatLongFractTy;
12271 default:
12272 assert(
12273 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12274 "Unexpected signed integer or fixed point type");
12275 return T;
12276 }
12277}
12278
12280
12283
12284//===----------------------------------------------------------------------===//
12285// Builtin Type Computation
12286//===----------------------------------------------------------------------===//
12287
12288/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12289/// pointer over the consumed characters. This returns the resultant type. If
12290/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12291/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12292/// a vector of "i*".
12293///
12294/// RequiresICE is filled in on return to indicate whether the value is required
12295/// to be an Integer Constant Expression.
12296static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12298 bool &RequiresICE,
12299 bool AllowTypeModifiers) {
12300 // Modifiers.
12301 int HowLong = 0;
12302 bool Signed = false, Unsigned = false;
12303 RequiresICE = false;
12304
12305 // Read the prefixed modifiers first.
12306 bool Done = false;
12307 #ifndef NDEBUG
12308 bool IsSpecial = false;
12309 #endif
12310 while (!Done) {
12311 switch (*Str++) {
12312 default: Done = true; --Str; break;
12313 case 'I':
12314 RequiresICE = true;
12315 break;
12316 case 'S':
12317 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12318 assert(!Signed && "Can't use 'S' modifier multiple times!");
12319 Signed = true;
12320 break;
12321 case 'U':
12322 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12323 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12324 Unsigned = true;
12325 break;
12326 case 'L':
12327 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12328 assert(HowLong <= 2 && "Can't have LLLL modifier");
12329 ++HowLong;
12330 break;
12331 case 'N':
12332 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12333 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12334 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12335 #ifndef NDEBUG
12336 IsSpecial = true;
12337 #endif
12338 if (Context.getTargetInfo().getLongWidth() == 32)
12339 ++HowLong;
12340 break;
12341 case 'W':
12342 // This modifier represents int64 type.
12343 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12344 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12345 #ifndef NDEBUG
12346 IsSpecial = true;
12347 #endif
12348 switch (Context.getTargetInfo().getInt64Type()) {
12349 default:
12350 llvm_unreachable("Unexpected integer type");
12352 HowLong = 1;
12353 break;
12355 HowLong = 2;
12356 break;
12357 }
12358 break;
12359 case 'Z':
12360 // This modifier represents int32 type.
12361 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12362 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12363 #ifndef NDEBUG
12364 IsSpecial = true;
12365 #endif
12366 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12367 default:
12368 llvm_unreachable("Unexpected integer type");
12370 HowLong = 0;
12371 break;
12373 HowLong = 1;
12374 break;
12376 HowLong = 2;
12377 break;
12378 }
12379 break;
12380 case 'O':
12381 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12382 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12383 #ifndef NDEBUG
12384 IsSpecial = true;
12385 #endif
12386 if (Context.getLangOpts().OpenCL)
12387 HowLong = 1;
12388 else
12389 HowLong = 2;
12390 break;
12391 }
12392 }
12393
12394 QualType Type;
12395
12396 // Read the base type.
12397 switch (*Str++) {
12398 default: llvm_unreachable("Unknown builtin type letter!");
12399 case 'x':
12400 assert(HowLong == 0 && !Signed && !Unsigned &&
12401 "Bad modifiers used with 'x'!");
12402 Type = Context.Float16Ty;
12403 break;
12404 case 'y':
12405 assert(HowLong == 0 && !Signed && !Unsigned &&
12406 "Bad modifiers used with 'y'!");
12407 Type = Context.BFloat16Ty;
12408 break;
12409 case 'v':
12410 assert(HowLong == 0 && !Signed && !Unsigned &&
12411 "Bad modifiers used with 'v'!");
12412 Type = Context.VoidTy;
12413 break;
12414 case 'h':
12415 assert(HowLong == 0 && !Signed && !Unsigned &&
12416 "Bad modifiers used with 'h'!");
12417 Type = Context.HalfTy;
12418 break;
12419 case 'f':
12420 assert(HowLong == 0 && !Signed && !Unsigned &&
12421 "Bad modifiers used with 'f'!");
12422 Type = Context.FloatTy;
12423 break;
12424 case 'd':
12425 assert(HowLong < 3 && !Signed && !Unsigned &&
12426 "Bad modifiers used with 'd'!");
12427 if (HowLong == 1)
12428 Type = Context.LongDoubleTy;
12429 else if (HowLong == 2)
12430 Type = Context.Float128Ty;
12431 else
12432 Type = Context.DoubleTy;
12433 break;
12434 case 's':
12435 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12436 if (Unsigned)
12437 Type = Context.UnsignedShortTy;
12438 else
12439 Type = Context.ShortTy;
12440 break;
12441 case 'i':
12442 if (HowLong == 3)
12443 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12444 else if (HowLong == 2)
12445 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12446 else if (HowLong == 1)
12447 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12448 else
12449 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12450 break;
12451 case 'c':
12452 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12453 if (Signed)
12454 Type = Context.SignedCharTy;
12455 else if (Unsigned)
12456 Type = Context.UnsignedCharTy;
12457 else
12458 Type = Context.CharTy;
12459 break;
12460 case 'b': // boolean
12461 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12462 Type = Context.BoolTy;
12463 break;
12464 case 'z': // size_t.
12465 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12466 Type = Context.getSizeType();
12467 break;
12468 case 'w': // wchar_t.
12469 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12470 Type = Context.getWideCharType();
12471 break;
12472 case 'F':
12473 Type = Context.getCFConstantStringType();
12474 break;
12475 case 'G':
12476 Type = Context.getObjCIdType();
12477 break;
12478 case 'H':
12479 Type = Context.getObjCSelType();
12480 break;
12481 case 'M':
12482 Type = Context.getObjCSuperType();
12483 break;
12484 case 'a':
12485 Type = Context.getBuiltinVaListType();
12486 assert(!Type.isNull() && "builtin va list type not initialized!");
12487 break;
12488 case 'A':
12489 // This is a "reference" to a va_list; however, what exactly
12490 // this means depends on how va_list is defined. There are two
12491 // different kinds of va_list: ones passed by value, and ones
12492 // passed by reference. An example of a by-value va_list is
12493 // x86, where va_list is a char*. An example of by-ref va_list
12494 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12495 // we want this argument to be a char*&; for x86-64, we want
12496 // it to be a __va_list_tag*.
12497 Type = Context.getBuiltinVaListType();
12498 assert(!Type.isNull() && "builtin va list type not initialized!");
12499 if (Type->isArrayType())
12500 Type = Context.getArrayDecayedType(Type);
12501 else
12502 Type = Context.getLValueReferenceType(Type);
12503 break;
12504 case 'q': {
12505 char *End;
12506 unsigned NumElements = strtoul(Str, &End, 10);
12507 assert(End != Str && "Missing vector size");
12508 Str = End;
12509
12510 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12511 RequiresICE, false);
12512 assert(!RequiresICE && "Can't require vector ICE");
12513
12514 Type = Context.getScalableVectorType(ElementType, NumElements);
12515 break;
12516 }
12517 case 'Q': {
12518 switch (*Str++) {
12519 case 'a': {
12520 Type = Context.SveCountTy;
12521 break;
12522 }
12523 case 'b': {
12524 Type = Context.AMDGPUBufferRsrcTy;
12525 break;
12526 }
12527 case 't': {
12528 Type = Context.AMDGPUTextureTy;
12529 break;
12530 }
12531 default:
12532 llvm_unreachable("Unexpected target builtin type");
12533 }
12534 break;
12535 }
12536 case 'V': {
12537 char *End;
12538 unsigned NumElements = strtoul(Str, &End, 10);
12539 assert(End != Str && "Missing vector size");
12540 Str = End;
12541
12542 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12543 RequiresICE, false);
12544 assert(!RequiresICE && "Can't require vector ICE");
12545
12546 // TODO: No way to make AltiVec vectors in builtins yet.
12547 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12548 break;
12549 }
12550 case 'E': {
12551 char *End;
12552
12553 unsigned NumElements = strtoul(Str, &End, 10);
12554 assert(End != Str && "Missing vector size");
12555
12556 Str = End;
12557
12558 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12559 false);
12560 Type = Context.getExtVectorType(ElementType, NumElements);
12561 break;
12562 }
12563 case 'X': {
12564 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12565 false);
12566 assert(!RequiresICE && "Can't require complex ICE");
12567 Type = Context.getComplexType(ElementType);
12568 break;
12569 }
12570 case 'Y':
12571 Type = Context.getPointerDiffType();
12572 break;
12573 case 'P':
12574 Type = Context.getFILEType();
12575 if (Type.isNull()) {
12577 return {};
12578 }
12579 break;
12580 case 'J':
12581 if (Signed)
12582 Type = Context.getsigjmp_bufType();
12583 else
12584 Type = Context.getjmp_bufType();
12585
12586 if (Type.isNull()) {
12588 return {};
12589 }
12590 break;
12591 case 'K':
12592 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12593 Type = Context.getucontext_tType();
12594
12595 if (Type.isNull()) {
12597 return {};
12598 }
12599 break;
12600 case 'p':
12601 Type = Context.getProcessIDType();
12602 break;
12603 case 'm':
12604 Type = Context.MFloat8Ty;
12605 break;
12606 }
12607
12608 // If there are modifiers and if we're allowed to parse them, go for it.
12609 Done = !AllowTypeModifiers;
12610 while (!Done) {
12611 switch (char c = *Str++) {
12612 default: Done = true; --Str; break;
12613 case '*':
12614 case '&': {
12615 // Both pointers and references can have their pointee types
12616 // qualified with an address space.
12617 char *End;
12618 unsigned AddrSpace = strtoul(Str, &End, 10);
12619 if (End != Str) {
12620 // Note AddrSpace == 0 is not the same as an unspecified address space.
12621 Type = Context.getAddrSpaceQualType(
12622 Type,
12623 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12624 Str = End;
12625 }
12626 if (c == '*')
12627 Type = Context.getPointerType(Type);
12628 else
12629 Type = Context.getLValueReferenceType(Type);
12630 break;
12631 }
12632 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12633 case 'C':
12634 Type = Type.withConst();
12635 break;
12636 case 'D':
12637 Type = Context.getVolatileType(Type);
12638 break;
12639 case 'R':
12640 Type = Type.withRestrict();
12641 break;
12642 }
12643 }
12644
12645 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12646 "Integer constant 'I' type must be an integer");
12647
12648 return Type;
12649}
12650
12651// On some targets such as PowerPC, some of the builtins are defined with custom
12652// type descriptors for target-dependent types. These descriptors are decoded in
12653// other functions, but it may be useful to be able to fall back to default
12654// descriptor decoding to define builtins mixing target-dependent and target-
12655// independent types. This function allows decoding one type descriptor with
12656// default decoding.
12657QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12658 GetBuiltinTypeError &Error, bool &RequireICE,
12659 bool AllowTypeModifiers) const {
12660 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12661}
12662
12663/// GetBuiltinType - Return the type for the specified builtin.
12666 unsigned *IntegerConstantArgs) const {
12667 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12668 if (TypeStr[0] == '\0') {
12670 return {};
12671 }
12672
12673 SmallVector<QualType, 8> ArgTypes;
12674
12675 bool RequiresICE = false;
12676 Error = GE_None;
12677 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12678 RequiresICE, true);
12679 if (Error != GE_None)
12680 return {};
12681
12682 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12683
12684 while (TypeStr[0] && TypeStr[0] != '.') {
12685 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12686 if (Error != GE_None)
12687 return {};
12688
12689 // If this argument is required to be an IntegerConstantExpression and the
12690 // caller cares, fill in the bitmask we return.
12691 if (RequiresICE && IntegerConstantArgs)
12692 *IntegerConstantArgs |= 1 << ArgTypes.size();
12693
12694 // Do array -> pointer decay. The builtin should use the decayed type.
12695 if (Ty->isArrayType())
12696 Ty = getArrayDecayedType(Ty);
12697
12698 ArgTypes.push_back(Ty);
12699 }
12700
12701 if (Id == Builtin::BI__GetExceptionInfo)
12702 return {};
12703
12704 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12705 "'.' should only occur at end of builtin type list!");
12706
12707 bool Variadic = (TypeStr[0] == '.');
12708
12709 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12710 if (BuiltinInfo.isNoReturn(Id))
12711 EI = EI.withNoReturn(true);
12712
12713 // We really shouldn't be making a no-proto type here.
12714 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12715 return getFunctionNoProtoType(ResType, EI);
12716
12718 EPI.ExtInfo = EI;
12719 EPI.Variadic = Variadic;
12720 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12721 EPI.ExceptionSpec.Type =
12723
12724 return getFunctionType(ResType, ArgTypes, EPI);
12725}
12726
12728 const FunctionDecl *FD) {
12729 if (!FD->isExternallyVisible())
12730 return GVA_Internal;
12731
12732 // Non-user-provided functions get emitted as weak definitions with every
12733 // use, no matter whether they've been explicitly instantiated etc.
12734 if (!FD->isUserProvided())
12735 return GVA_DiscardableODR;
12736
12738 switch (FD->getTemplateSpecializationKind()) {
12739 case TSK_Undeclared:
12742 break;
12743
12745 return GVA_StrongODR;
12746
12747 // C++11 [temp.explicit]p10:
12748 // [ Note: The intent is that an inline function that is the subject of
12749 // an explicit instantiation declaration will still be implicitly
12750 // instantiated when used so that the body can be considered for
12751 // inlining, but that no out-of-line copy of the inline function would be
12752 // generated in the translation unit. -- end note ]
12755
12758 break;
12759 }
12760
12761 if (!FD->isInlined())
12762 return External;
12763
12764 if ((!Context.getLangOpts().CPlusPlus &&
12765 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12766 !FD->hasAttr<DLLExportAttr>()) ||
12767 FD->hasAttr<GNUInlineAttr>()) {
12768 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12769
12770 // GNU or C99 inline semantics. Determine whether this symbol should be
12771 // externally visible.
12773 return External;
12774
12775 // C99 inline semantics, where the symbol is not externally visible.
12777 }
12778
12779 // Functions specified with extern and inline in -fms-compatibility mode
12780 // forcibly get emitted. While the body of the function cannot be later
12781 // replaced, the function definition cannot be discarded.
12782 if (FD->isMSExternInline())
12783 return GVA_StrongODR;
12784
12785 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12787 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12788 // Our approach to inheriting constructors is fundamentally different from
12789 // that used by the MS ABI, so keep our inheriting constructor thunks
12790 // internal rather than trying to pick an unambiguous mangling for them.
12791 return GVA_Internal;
12792
12793 return GVA_DiscardableODR;
12794}
12795
12797 const Decl *D, GVALinkage L) {
12798 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12799 // dllexport/dllimport on inline functions.
12800 if (D->hasAttr<DLLImportAttr>()) {
12801 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12803 } else if (D->hasAttr<DLLExportAttr>()) {
12804 if (L == GVA_DiscardableODR)
12805 return GVA_StrongODR;
12806 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12807 // Device-side functions with __global__ attribute must always be
12808 // visible externally so they can be launched from host.
12809 if (D->hasAttr<CUDAGlobalAttr>() &&
12810 (L == GVA_DiscardableODR || L == GVA_Internal))
12811 return GVA_StrongODR;
12812 // Single source offloading languages like CUDA/HIP need to be able to
12813 // access static device variables from host code of the same compilation
12814 // unit. This is done by externalizing the static variable with a shared
12815 // name between the host and device compilation which is the same for the
12816 // same compilation unit whereas different among different compilation
12817 // units.
12818 if (Context.shouldExternalize(D))
12819 return GVA_StrongExternal;
12820 }
12821 return L;
12822}
12823
12824/// Adjust the GVALinkage for a declaration based on what an external AST source
12825/// knows about whether there can be other definitions of this declaration.
12826static GVALinkage
12828 GVALinkage L) {
12829 ExternalASTSource *Source = Ctx.getExternalSource();
12830 if (!Source)
12831 return L;
12832
12833 switch (Source->hasExternalDefinitions(D)) {
12835 // Other translation units rely on us to provide the definition.
12836 if (L == GVA_DiscardableODR)
12837 return GVA_StrongODR;
12838 break;
12839
12842
12844 break;
12845 }
12846 return L;
12847}
12848
12854
12856 const VarDecl *VD) {
12857 // As an extension for interactive REPLs, make sure constant variables are
12858 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12859 // marking them as internal.
12860 if (Context.getLangOpts().CPlusPlus &&
12861 Context.getLangOpts().IncrementalExtensions &&
12862 VD->getType().isConstQualified() &&
12863 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12865 return GVA_DiscardableODR;
12866
12867 if (!VD->isExternallyVisible())
12868 return GVA_Internal;
12869
12870 if (VD->isStaticLocal()) {
12871 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12872 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12873 LexicalContext = LexicalContext->getLexicalParent();
12874
12875 // ObjC Blocks can create local variables that don't have a FunctionDecl
12876 // LexicalContext.
12877 if (!LexicalContext)
12878 return GVA_DiscardableODR;
12879
12880 // Otherwise, let the static local variable inherit its linkage from the
12881 // nearest enclosing function.
12882 auto StaticLocalLinkage =
12883 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12884
12885 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12886 // be emitted in any object with references to the symbol for the object it
12887 // contains, whether inline or out-of-line."
12888 // Similar behavior is observed with MSVC. An alternative ABI could use
12889 // StrongODR/AvailableExternally to match the function, but none are
12890 // known/supported currently.
12891 if (StaticLocalLinkage == GVA_StrongODR ||
12892 StaticLocalLinkage == GVA_AvailableExternally)
12893 return GVA_DiscardableODR;
12894 return StaticLocalLinkage;
12895 }
12896
12897 // MSVC treats in-class initialized static data members as definitions.
12898 // By giving them non-strong linkage, out-of-line definitions won't
12899 // cause link errors.
12900 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12901 return GVA_DiscardableODR;
12902
12903 // Most non-template variables have strong linkage; inline variables are
12904 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12905 GVALinkage StrongLinkage;
12906 switch (Context.getInlineVariableDefinitionKind(VD)) {
12908 StrongLinkage = GVA_StrongExternal;
12909 break;
12912 StrongLinkage = GVA_DiscardableODR;
12913 break;
12915 StrongLinkage = GVA_StrongODR;
12916 break;
12917 }
12918
12919 switch (VD->getTemplateSpecializationKind()) {
12920 case TSK_Undeclared:
12921 return StrongLinkage;
12922
12924 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12925 VD->isStaticDataMember()
12927 : StrongLinkage;
12928
12930 return GVA_StrongODR;
12931
12934
12936 return GVA_DiscardableODR;
12937 }
12938
12939 llvm_unreachable("Invalid Linkage!");
12940}
12941
12947
12949 if (const auto *VD = dyn_cast<VarDecl>(D)) {
12950 if (!VD->isFileVarDecl())
12951 return false;
12952 // Global named register variables (GNU extension) are never emitted.
12953 if (VD->getStorageClass() == SC_Register)
12954 return false;
12955 if (VD->getDescribedVarTemplate() ||
12957 return false;
12958 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
12959 // We never need to emit an uninstantiated function template.
12960 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12961 return false;
12962 } else if (isa<PragmaCommentDecl>(D))
12963 return true;
12965 return true;
12966 else if (isa<OMPRequiresDecl>(D))
12967 return true;
12968 else if (isa<OMPThreadPrivateDecl>(D))
12969 return !D->getDeclContext()->isDependentContext();
12970 else if (isa<OMPAllocateDecl>(D))
12971 return !D->getDeclContext()->isDependentContext();
12973 return !D->getDeclContext()->isDependentContext();
12974 else if (isa<ImportDecl>(D))
12975 return true;
12976 else
12977 return false;
12978
12979 // If this is a member of a class template, we do not need to emit it.
12981 return false;
12982
12983 // Weak references don't produce any output by themselves.
12984 if (D->hasAttr<WeakRefAttr>())
12985 return false;
12986
12987 // SYCL device compilation requires that functions defined with the
12988 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
12989 // other entities are emitted only if they are used by a function
12990 // defined with one of those attributes.
12991 if (LangOpts.SYCLIsDevice)
12992 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
12993 D->hasAttr<SYCLExternalAttr>());
12994
12995 // Aliases and used decls are required.
12996 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
12997 return true;
12998
12999 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13000 // Forward declarations aren't required.
13001 if (!FD->doesThisDeclarationHaveABody())
13002 return FD->doesDeclarationForceExternallyVisibleDefinition();
13003
13004 // Constructors and destructors are required.
13005 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13006 return true;
13007
13008 // The key function for a class is required. This rule only comes
13009 // into play when inline functions can be key functions, though.
13010 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13011 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13012 const CXXRecordDecl *RD = MD->getParent();
13013 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13014 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13015 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13016 return true;
13017 }
13018 }
13019 }
13020
13022
13023 // static, static inline, always_inline, and extern inline functions can
13024 // always be deferred. Normal inline functions can be deferred in C99/C++.
13025 // Implicit template instantiations can also be deferred in C++.
13027 }
13028
13029 const auto *VD = cast<VarDecl>(D);
13030 assert(VD->isFileVarDecl() && "Expected file scoped var");
13031
13032 // If the decl is marked as `declare target to`, it should be emitted for the
13033 // host and for the device.
13034 if (LangOpts.OpenMP &&
13035 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13036 return true;
13037
13038 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13040 return false;
13041
13042 if (VD->shouldEmitInExternalSource())
13043 return false;
13044
13045 // Variables that can be needed in other TUs are required.
13048 return true;
13049
13050 // We never need to emit a variable that is available in another TU.
13052 return false;
13053
13054 // Variables that have destruction with side-effects are required.
13055 if (VD->needsDestruction(*this))
13056 return true;
13057
13058 // Variables that have initialization with side-effects are required.
13059 if (VD->hasInitWithSideEffects())
13060 return true;
13061
13062 // Likewise, variables with tuple-like bindings are required if their
13063 // bindings have side-effects.
13064 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13065 for (const auto *BD : DD->flat_bindings())
13066 if (const auto *BindingVD = BD->getHoldingVar())
13067 if (DeclMustBeEmitted(BindingVD))
13068 return true;
13069 }
13070
13071 return false;
13072}
13073
13075 const FunctionDecl *FD,
13076 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13077 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13078 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13079 FD = FD->getMostRecentDecl();
13080 // FIXME: The order of traversal here matters and depends on the order of
13081 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13082 // shouldn't rely on that.
13083 for (auto *CurDecl :
13085 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13086 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13087 SeenDecls.insert(CurFD).second) {
13088 Pred(CurFD);
13089 }
13090 }
13091}
13092
13094 bool IsCXXMethod) const {
13095 // Pass through to the C++ ABI object
13096 if (IsCXXMethod)
13097 return ABI->getDefaultMethodCallConv(IsVariadic);
13098
13099 switch (LangOpts.getDefaultCallingConv()) {
13101 break;
13103 return CC_C;
13105 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13106 return CC_X86FastCall;
13107 break;
13109 if (!IsVariadic)
13110 return CC_X86StdCall;
13111 break;
13113 // __vectorcall cannot be applied to variadic functions.
13114 if (!IsVariadic)
13115 return CC_X86VectorCall;
13116 break;
13118 // __regcall cannot be applied to variadic functions.
13119 if (!IsVariadic)
13120 return CC_X86RegCall;
13121 break;
13123 if (!IsVariadic)
13124 return CC_M68kRTD;
13125 break;
13126 }
13127 return Target->getDefaultCallingConv();
13128}
13129
13131 // Pass through to the C++ ABI object
13132 return ABI->isNearlyEmpty(RD);
13133}
13134
13136 if (!VTContext) {
13137 auto ABI = Target->getCXXABI();
13138 if (ABI.isMicrosoft())
13139 VTContext.reset(new MicrosoftVTableContext(*this));
13140 else {
13141 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13144 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13145 }
13146 }
13147 return VTContext.get();
13148}
13149
13151 if (!T)
13152 T = Target;
13153 switch (T->getCXXABI().getKind()) {
13154 case TargetCXXABI::AppleARM64:
13155 case TargetCXXABI::Fuchsia:
13156 case TargetCXXABI::GenericAArch64:
13157 case TargetCXXABI::GenericItanium:
13158 case TargetCXXABI::GenericARM:
13159 case TargetCXXABI::GenericMIPS:
13160 case TargetCXXABI::iOS:
13161 case TargetCXXABI::WebAssembly:
13162 case TargetCXXABI::WatchOS:
13163 case TargetCXXABI::XL:
13165 case TargetCXXABI::Microsoft:
13167 }
13168 llvm_unreachable("Unsupported ABI");
13169}
13170
13172 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13173 "Device mangle context does not support Microsoft mangling.");
13174 switch (T.getCXXABI().getKind()) {
13175 case TargetCXXABI::AppleARM64:
13176 case TargetCXXABI::Fuchsia:
13177 case TargetCXXABI::GenericAArch64:
13178 case TargetCXXABI::GenericItanium:
13179 case TargetCXXABI::GenericARM:
13180 case TargetCXXABI::GenericMIPS:
13181 case TargetCXXABI::iOS:
13182 case TargetCXXABI::WebAssembly:
13183 case TargetCXXABI::WatchOS:
13184 case TargetCXXABI::XL:
13186 *this, getDiagnostics(),
13187 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13188 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13189 return RD->getDeviceLambdaManglingNumber();
13190 return std::nullopt;
13191 },
13192 /*IsAux=*/true);
13193 case TargetCXXABI::Microsoft:
13195 /*IsAux=*/true);
13196 }
13197 llvm_unreachable("Unsupported ABI");
13198}
13199
13200CXXABI::~CXXABI() = default;
13201
13203 return ASTRecordLayouts.getMemorySize() +
13204 llvm::capacity_in_bytes(ObjCLayouts) +
13205 llvm::capacity_in_bytes(KeyFunctions) +
13206 llvm::capacity_in_bytes(ObjCImpls) +
13207 llvm::capacity_in_bytes(BlockVarCopyInits) +
13208 llvm::capacity_in_bytes(DeclAttrs) +
13209 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13210 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13211 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13212 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13213 llvm::capacity_in_bytes(OverriddenMethods) +
13214 llvm::capacity_in_bytes(Types) +
13215 llvm::capacity_in_bytes(VariableArrayTypes);
13216}
13217
13218/// getIntTypeForBitwidth -
13219/// sets integer QualTy according to specified details:
13220/// bitwidth, signed/unsigned.
13221/// Returns empty type if there is no appropriate target types.
13223 unsigned Signed) const {
13225 CanQualType QualTy = getFromTargetType(Ty);
13226 if (!QualTy && DestWidth == 128)
13227 return Signed ? Int128Ty : UnsignedInt128Ty;
13228 return QualTy;
13229}
13230
13231/// getRealTypeForBitwidth -
13232/// sets floating point QualTy according to specified bitwidth.
13233/// Returns empty type if there is no appropriate target types.
13235 FloatModeKind ExplicitType) const {
13236 FloatModeKind Ty =
13237 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13238 switch (Ty) {
13240 return HalfTy;
13242 return FloatTy;
13244 return DoubleTy;
13246 return LongDoubleTy;
13248 return Float128Ty;
13250 return Ibm128Ty;
13252 return {};
13253 }
13254
13255 llvm_unreachable("Unhandled TargetInfo::RealType value");
13256}
13257
13258void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13259 if (Number <= 1)
13260 return;
13261
13262 MangleNumbers[ND] = Number;
13263
13264 if (Listener)
13265 Listener->AddedManglingNumber(ND, Number);
13266}
13267
13269 bool ForAuxTarget) const {
13270 auto I = MangleNumbers.find(ND);
13271 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13272 // CUDA/HIP host compilation encodes host and device mangling numbers
13273 // as lower and upper half of 32 bit integer.
13274 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13275 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13276 } else {
13277 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13278 "number for aux target");
13279 }
13280 return Res > 1 ? Res : 1;
13281}
13282
13283void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13284 if (Number <= 1)
13285 return;
13286
13287 StaticLocalNumbers[VD] = Number;
13288
13289 if (Listener)
13290 Listener->AddedStaticLocalNumbers(VD, Number);
13291}
13292
13294 auto I = StaticLocalNumbers.find(VD);
13295 return I != StaticLocalNumbers.end() ? I->second : 1;
13296}
13297
13299 bool IsDestroying) {
13300 if (!IsDestroying) {
13301 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13302 return;
13303 }
13304 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13305}
13306
13308 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13309}
13310
13312 bool IsTypeAware) {
13313 if (!IsTypeAware) {
13314 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13315 return;
13316 }
13317 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13318}
13319
13321 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13322}
13323
13326 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13327 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13328 if (!MCtx)
13330 return *MCtx;
13331}
13332
13335 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13336 std::unique_ptr<MangleNumberingContext> &MCtx =
13337 ExtraMangleNumberingContexts[D];
13338 if (!MCtx)
13340 return *MCtx;
13341}
13342
13343std::unique_ptr<MangleNumberingContext>
13345 return ABI->createMangleNumberingContext();
13346}
13347
13348const CXXConstructorDecl *
13350 return ABI->getCopyConstructorForExceptionObject(
13352}
13353
13355 CXXConstructorDecl *CD) {
13356 return ABI->addCopyConstructorForExceptionObject(
13359}
13360
13362 TypedefNameDecl *DD) {
13363 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13364}
13365
13368 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13369}
13370
13372 DeclaratorDecl *DD) {
13373 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13374}
13375
13377 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13378}
13379
13381 ParamIndices[D] = index;
13382}
13383
13385 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13386 assert(I != ParamIndices.end() &&
13387 "ParmIndices lacks entry set by ParmVarDecl");
13388 return I->second;
13389}
13390
13392 unsigned Length) const {
13393 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13394 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13395 EltTy = EltTy.withConst();
13396
13397 EltTy = adjustStringLiteralBaseType(EltTy);
13398
13399 // Get an array type for the string, according to C99 6.4.5. This includes
13400 // the null terminator character.
13401 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13402 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13403}
13404
13407 StringLiteral *&Result = StringLiteralCache[Key];
13408 if (!Result)
13410 *this, Key, StringLiteralKind::Ordinary,
13411 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13412 SourceLocation());
13413 return Result;
13414}
13415
13416MSGuidDecl *
13418 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13419
13420 llvm::FoldingSetNodeID ID;
13421 MSGuidDecl::Profile(ID, Parts);
13422
13423 void *InsertPos;
13424 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13425 return Existing;
13426
13427 QualType GUIDType = getMSGuidType().withConst();
13428 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13429 MSGuidDecls.InsertNode(New, InsertPos);
13430 return New;
13431}
13432
13435 const APValue &APVal) const {
13436 llvm::FoldingSetNodeID ID;
13438
13439 void *InsertPos;
13440 if (UnnamedGlobalConstantDecl *Existing =
13441 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13442 return Existing;
13443
13445 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13446 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13447 return New;
13448}
13449
13452 assert(T->isRecordType() && "template param object of unexpected type");
13453
13454 // C++ [temp.param]p8:
13455 // [...] a static storage duration object of type 'const T' [...]
13456 T.addConst();
13457
13458 llvm::FoldingSetNodeID ID;
13460
13461 void *InsertPos;
13462 if (TemplateParamObjectDecl *Existing =
13463 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13464 return Existing;
13465
13466 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13467 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13468 return New;
13469}
13470
13472 const llvm::Triple &T = getTargetInfo().getTriple();
13473 if (!T.isOSDarwin())
13474 return false;
13475
13476 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13477 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13478 return false;
13479
13480 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13481 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13482 uint64_t Size = sizeChars.getQuantity();
13483 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13484 unsigned Align = alignChars.getQuantity();
13485 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13486 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13487}
13488
13489bool
13491 const ObjCMethodDecl *MethodImpl) {
13492 // No point trying to match an unavailable/deprecated mothod.
13493 if (MethodDecl->hasAttr<UnavailableAttr>()
13494 || MethodDecl->hasAttr<DeprecatedAttr>())
13495 return false;
13496 if (MethodDecl->getObjCDeclQualifier() !=
13497 MethodImpl->getObjCDeclQualifier())
13498 return false;
13499 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13500 return false;
13501
13502 if (MethodDecl->param_size() != MethodImpl->param_size())
13503 return false;
13504
13505 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13506 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13507 EF = MethodDecl->param_end();
13508 IM != EM && IF != EF; ++IM, ++IF) {
13509 const ParmVarDecl *DeclVar = (*IF);
13510 const ParmVarDecl *ImplVar = (*IM);
13511 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13512 return false;
13513 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13514 return false;
13515 }
13516
13517 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13518}
13519
13521 LangAS AS;
13523 AS = LangAS::Default;
13524 else
13525 AS = QT->getPointeeType().getAddressSpace();
13526
13528}
13529
13532}
13533
13534bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13535 if (X == Y)
13536 return true;
13537 if (!X || !Y)
13538 return false;
13539 llvm::FoldingSetNodeID IDX, IDY;
13540 X->Profile(IDX, *this, /*Canonical=*/true);
13541 Y->Profile(IDY, *this, /*Canonical=*/true);
13542 return IDX == IDY;
13543}
13544
13545// The getCommon* helpers return, for given 'same' X and Y entities given as
13546// inputs, another entity which is also the 'same' as the inputs, but which
13547// is closer to the canonical form of the inputs, each according to a given
13548// criteria.
13549// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13550// the regular ones.
13551
13553 if (!declaresSameEntity(X, Y))
13554 return nullptr;
13555 for (const Decl *DX : X->redecls()) {
13556 // If we reach Y before reaching the first decl, that means X is older.
13557 if (DX == Y)
13558 return X;
13559 // If we reach the first decl, then Y is older.
13560 if (DX->isFirstDecl())
13561 return Y;
13562 }
13563 llvm_unreachable("Corrupt redecls chain");
13564}
13565
13566template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13567static T *getCommonDecl(T *X, T *Y) {
13568 return cast_or_null<T>(
13569 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13570 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13571}
13572
13573template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13574static T *getCommonDeclChecked(T *X, T *Y) {
13575 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13576 const_cast<Decl *>(cast<Decl>(Y))));
13577}
13578
13580 TemplateName Y,
13581 bool IgnoreDeduced = false) {
13582 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13583 return X;
13584 // FIXME: There are cases here where we could find a common template name
13585 // with more sugar. For example one could be a SubstTemplateTemplate*
13586 // replacing the other.
13587 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13588 if (CX.getAsVoidPointer() !=
13590 return TemplateName();
13591 return CX;
13592}
13593
13596 bool IgnoreDeduced) {
13597 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13598 assert(R.getAsVoidPointer() != nullptr);
13599 return R;
13600}
13601
13603 ArrayRef<QualType> Ys, bool Unqualified = false) {
13604 assert(Xs.size() == Ys.size());
13605 SmallVector<QualType, 8> Rs(Xs.size());
13606 for (size_t I = 0; I < Rs.size(); ++I)
13607 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13608 return Rs;
13609}
13610
13611template <class T>
13612static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13613 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13614 : SourceLocation();
13615}
13616
13618 const TemplateArgument &X,
13619 const TemplateArgument &Y) {
13620 if (X.getKind() != Y.getKind())
13621 return TemplateArgument();
13622
13623 switch (X.getKind()) {
13625 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13626 return TemplateArgument();
13627 return TemplateArgument(
13628 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13630 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13631 return TemplateArgument();
13632 return TemplateArgument(
13633 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13634 /*Unqualified=*/true);
13636 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13637 return TemplateArgument();
13638 // FIXME: Try to keep the common sugar.
13639 return X;
13641 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13642 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13643 if (!CTN.getAsVoidPointer())
13644 return TemplateArgument();
13645 return TemplateArgument(CTN);
13646 }
13648 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13650 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13651 if (!CTN.getAsVoidPointer())
13652 return TemplateName();
13653 auto NExpX = X.getNumTemplateExpansions();
13654 assert(NExpX == Y.getNumTemplateExpansions());
13655 return TemplateArgument(CTN, NExpX);
13656 }
13657 default:
13658 // FIXME: Handle the other argument kinds.
13659 return X;
13660 }
13661}
13662
13667 if (Xs.size() != Ys.size())
13668 return true;
13669 R.resize(Xs.size());
13670 for (size_t I = 0; I < R.size(); ++I) {
13671 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13672 if (R[I].isNull())
13673 return true;
13674 }
13675 return false;
13676}
13677
13682 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13683 assert(!Different);
13684 (void)Different;
13685 return R;
13686}
13687
13688template <class T>
13690 bool IsSame) {
13691 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13692 if (KX == KY)
13693 return KX;
13695 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13696 return KX;
13697}
13698
13699/// Returns a NestedNameSpecifier which has only the common sugar
13700/// present in both NNS1 and NNS2.
13703 NestedNameSpecifier NNS2, bool IsSame) {
13704 // If they are identical, all sugar is common.
13705 if (NNS1 == NNS2)
13706 return NNS1;
13707
13708 // IsSame implies both Qualifiers are equivalent.
13709 NestedNameSpecifier Canon = NNS1.getCanonical();
13710 if (Canon != NNS2.getCanonical()) {
13711 assert(!IsSame && "Should be the same NestedNameSpecifier");
13712 // If they are not the same, there is nothing to unify.
13713 return std::nullopt;
13714 }
13715
13716 NestedNameSpecifier R = std::nullopt;
13717 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13718 assert(Kind == NNS2.getKind());
13719 switch (Kind) {
13721 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13722 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13723 auto Kind = Namespace1->getKind();
13724 if (Kind != Namespace2->getKind() ||
13725 (Kind == Decl::NamespaceAlias &&
13726 !declaresSameEntity(Namespace1, Namespace2))) {
13728 Ctx,
13729 ::getCommonDeclChecked(Namespace1->getNamespace(),
13730 Namespace2->getNamespace()),
13731 /*Prefix=*/std::nullopt);
13732 break;
13733 }
13734 // The prefixes for namespaces are not significant, its declaration
13735 // identifies it uniquely.
13736 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13737 /*IsSame=*/false);
13738 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13739 Prefix);
13740 break;
13741 }
13743 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13744 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13745 /*Unqualified=*/true)
13746 .getTypePtr();
13748 break;
13749 }
13751 // FIXME: Can __super even be used with data members?
13752 // If it's only usable in functions, we will never see it here,
13753 // unless we save the qualifiers used in function types.
13754 // In that case, it might be possible NNS2 is a type,
13755 // in which case we should degrade the result to
13756 // a CXXRecordType.
13758 NNS2.getAsMicrosoftSuper()));
13759 break;
13760 }
13763 // These are singletons.
13764 llvm_unreachable("singletons did not compare equal");
13765 }
13766 assert(R.getCanonical() == Canon);
13767 return R;
13768}
13769
13770template <class T>
13772 const T *Y, bool IsSame) {
13773 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13774}
13775
13776template <class T>
13777static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13778 const T *Y) {
13779 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13780}
13781
13782template <class T>
13784 Qualifiers &QX, const T *Y,
13785 Qualifiers &QY) {
13786 QualType EX = X->getElementType(), EY = Y->getElementType();
13787 QualType R = Ctx.getCommonSugaredType(EX, EY,
13788 /*Unqualified=*/true);
13789 // Qualifiers common to both element types.
13790 Qualifiers RQ = R.getQualifiers();
13791 // For each side, move to the top level any qualifiers which are not common to
13792 // both element types. The caller must assume top level qualifiers might
13793 // be different, even if they are the same type, and can be treated as sugar.
13794 QX += EX.getQualifiers() - RQ;
13795 QY += EY.getQualifiers() - RQ;
13796 return R;
13797}
13798
13799template <class T>
13800static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13801 const T *Y) {
13802 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13803}
13804
13805template <class T>
13806static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13807 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13808 return X->getSizeExpr();
13809}
13810
13811static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13812 assert(X->getSizeModifier() == Y->getSizeModifier());
13813 return X->getSizeModifier();
13814}
13815
13817 const ArrayType *Y) {
13818 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13819 return X->getIndexTypeCVRQualifiers();
13820}
13821
13822// Merges two type lists such that the resulting vector will contain
13823// each type (in a canonical sense) only once, in the order they appear
13824// from X to Y. If they occur in both X and Y, the result will contain
13825// the common sugared type between them.
13826static void mergeTypeLists(const ASTContext &Ctx,
13829 llvm::DenseMap<QualType, unsigned> Found;
13830 for (auto Ts : {X, Y}) {
13831 for (QualType T : Ts) {
13832 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13833 if (!Res.second) {
13834 QualType &U = Out[Res.first->second];
13835 U = Ctx.getCommonSugaredType(U, T);
13836 } else {
13837 Out.emplace_back(T);
13838 }
13839 }
13840 }
13841}
13842
13843FunctionProtoType::ExceptionSpecInfo
13846 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13847 bool AcceptDependent) const {
13848 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13849
13850 // If either of them can throw anything, that is the result.
13851 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13852 if (EST1 == I)
13853 return ESI1;
13854 if (EST2 == I)
13855 return ESI2;
13856 }
13857
13858 // If either of them is non-throwing, the result is the other.
13859 for (auto I :
13861 if (EST1 == I)
13862 return ESI2;
13863 if (EST2 == I)
13864 return ESI1;
13865 }
13866
13867 // If we're left with value-dependent computed noexcept expressions, we're
13868 // stuck. Before C++17, we can just drop the exception specification entirely,
13869 // since it's not actually part of the canonical type. And this should never
13870 // happen in C++17, because it would mean we were computing the composite
13871 // pointer type of dependent types, which should never happen.
13872 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13873 assert(AcceptDependent &&
13874 "computing composite pointer type of dependent types");
13876 }
13877
13878 // Switch over the possibilities so that people adding new values know to
13879 // update this function.
13880 switch (EST1) {
13881 case EST_None:
13882 case EST_DynamicNone:
13883 case EST_MSAny:
13884 case EST_BasicNoexcept:
13886 case EST_NoexceptFalse:
13887 case EST_NoexceptTrue:
13888 case EST_NoThrow:
13889 llvm_unreachable("These ESTs should be handled above");
13890
13891 case EST_Dynamic: {
13892 // This is the fun case: both exception specifications are dynamic. Form
13893 // the union of the two lists.
13894 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13895 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13896 ESI2.Exceptions);
13898 Result.Exceptions = ExceptionTypeStorage;
13899 return Result;
13900 }
13901
13902 case EST_Unevaluated:
13903 case EST_Uninstantiated:
13904 case EST_Unparsed:
13905 llvm_unreachable("shouldn't see unresolved exception specifications here");
13906 }
13907
13908 llvm_unreachable("invalid ExceptionSpecificationType");
13909}
13910
13912 Qualifiers &QX, const Type *Y,
13913 Qualifiers &QY) {
13914 Type::TypeClass TC = X->getTypeClass();
13915 assert(TC == Y->getTypeClass());
13916 switch (TC) {
13917#define UNEXPECTED_TYPE(Class, Kind) \
13918 case Type::Class: \
13919 llvm_unreachable("Unexpected " Kind ": " #Class);
13920
13921#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13922#define TYPE(Class, Base)
13923#include "clang/AST/TypeNodes.inc"
13924
13925#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13927 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13928 SUGAR_FREE_TYPE(DependentBitInt)
13930 SUGAR_FREE_TYPE(ObjCInterface)
13931 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13932 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
13933 SUGAR_FREE_TYPE(UnresolvedUsing)
13934 SUGAR_FREE_TYPE(HLSLAttributedResource)
13935 SUGAR_FREE_TYPE(HLSLInlineSpirv)
13936#undef SUGAR_FREE_TYPE
13937#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13938 NON_UNIQUE_TYPE(TypeOfExpr)
13939 NON_UNIQUE_TYPE(VariableArray)
13940#undef NON_UNIQUE_TYPE
13941
13942 UNEXPECTED_TYPE(TypeOf, "sugar")
13943
13944#undef UNEXPECTED_TYPE
13945
13946 case Type::Auto: {
13947 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
13948 assert(AX->getDeducedType().isNull());
13949 assert(AY->getDeducedType().isNull());
13950 assert(AX->getKeyword() == AY->getKeyword());
13951 assert(AX->isInstantiationDependentType() ==
13952 AY->isInstantiationDependentType());
13953 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
13954 AY->getTypeConstraintArguments());
13955 return Ctx.getAutoType(QualType(), AX->getKeyword(),
13957 AX->containsUnexpandedParameterPack(),
13958 getCommonDeclChecked(AX->getTypeConstraintConcept(),
13959 AY->getTypeConstraintConcept()),
13960 As);
13961 }
13962 case Type::IncompleteArray: {
13963 const auto *AX = cast<IncompleteArrayType>(X),
13965 return Ctx.getIncompleteArrayType(
13966 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13968 }
13969 case Type::DependentSizedArray: {
13970 const auto *AX = cast<DependentSizedArrayType>(X),
13972 return Ctx.getDependentSizedArrayType(
13973 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
13974 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
13976 }
13977 case Type::ConstantArray: {
13978 const auto *AX = cast<ConstantArrayType>(X),
13979 *AY = cast<ConstantArrayType>(Y);
13980 assert(AX->getSize() == AY->getSize());
13981 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13982 ? AX->getSizeExpr()
13983 : nullptr;
13984 return Ctx.getConstantArrayType(
13985 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13987 }
13988 case Type::ArrayParameter: {
13989 const auto *AX = cast<ArrayParameterType>(X),
13990 *AY = cast<ArrayParameterType>(Y);
13991 assert(AX->getSize() == AY->getSize());
13992 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
13993 ? AX->getSizeExpr()
13994 : nullptr;
13995 auto ArrayTy = Ctx.getConstantArrayType(
13996 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
13998 return Ctx.getArrayParameterType(ArrayTy);
13999 }
14000 case Type::Atomic: {
14001 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14002 return Ctx.getAtomicType(
14003 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14004 }
14005 case Type::Complex: {
14006 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14007 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14008 }
14009 case Type::Pointer: {
14010 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14011 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14012 }
14013 case Type::BlockPointer: {
14014 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14015 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14016 }
14017 case Type::ObjCObjectPointer: {
14018 const auto *PX = cast<ObjCObjectPointerType>(X),
14020 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14021 }
14022 case Type::MemberPointer: {
14023 const auto *PX = cast<MemberPointerType>(X),
14024 *PY = cast<MemberPointerType>(Y);
14025 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14026 PY->getMostRecentCXXRecordDecl()));
14027 return Ctx.getMemberPointerType(
14028 getCommonPointeeType(Ctx, PX, PY),
14029 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14030 PX->getMostRecentCXXRecordDecl());
14031 }
14032 case Type::LValueReference: {
14033 const auto *PX = cast<LValueReferenceType>(X),
14035 // FIXME: Preserve PointeeTypeAsWritten.
14036 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14037 PX->isSpelledAsLValue() ||
14038 PY->isSpelledAsLValue());
14039 }
14040 case Type::RValueReference: {
14041 const auto *PX = cast<RValueReferenceType>(X),
14043 // FIXME: Preserve PointeeTypeAsWritten.
14044 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14045 }
14046 case Type::DependentAddressSpace: {
14047 const auto *PX = cast<DependentAddressSpaceType>(X),
14049 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14050 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14051 PX->getAddrSpaceExpr(),
14052 getCommonAttrLoc(PX, PY));
14053 }
14054 case Type::FunctionNoProto: {
14055 const auto *FX = cast<FunctionNoProtoType>(X),
14057 assert(FX->getExtInfo() == FY->getExtInfo());
14058 return Ctx.getFunctionNoProtoType(
14059 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14060 FX->getExtInfo());
14061 }
14062 case Type::FunctionProto: {
14063 const auto *FX = cast<FunctionProtoType>(X),
14064 *FY = cast<FunctionProtoType>(Y);
14065 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14066 EPIY = FY->getExtProtoInfo();
14067 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14068 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14069 assert(!EPIX.ExtParameterInfos ||
14070 llvm::equal(
14071 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14072 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14073 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14074 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14075 assert(EPIX.Variadic == EPIY.Variadic);
14076
14077 // FIXME: Can we handle an empty EllipsisLoc?
14078 // Use emtpy EllipsisLoc if X and Y differ.
14079
14080 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14081
14082 QualType R =
14083 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14084 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14085 /*Unqualified=*/true);
14086
14087 SmallVector<QualType, 8> Exceptions;
14089 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14090 return Ctx.getFunctionType(R, P, EPIX);
14091 }
14092 case Type::ObjCObject: {
14093 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14094 assert(
14095 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14096 OY->getProtocols().begin(), OY->getProtocols().end(),
14097 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14098 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14099 }) &&
14100 "protocol lists must be the same");
14101 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14102 OY->getTypeArgsAsWritten());
14103 return Ctx.getObjCObjectType(
14104 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14105 OX->getProtocols(),
14106 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14107 }
14108 case Type::ConstantMatrix: {
14109 const auto *MX = cast<ConstantMatrixType>(X),
14110 *MY = cast<ConstantMatrixType>(Y);
14111 assert(MX->getNumRows() == MY->getNumRows());
14112 assert(MX->getNumColumns() == MY->getNumColumns());
14113 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14114 MX->getNumRows(), MX->getNumColumns());
14115 }
14116 case Type::DependentSizedMatrix: {
14117 const auto *MX = cast<DependentSizedMatrixType>(X),
14119 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14120 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14121 return Ctx.getDependentSizedMatrixType(
14122 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14123 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14124 }
14125 case Type::Vector: {
14126 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14127 assert(VX->getNumElements() == VY->getNumElements());
14128 assert(VX->getVectorKind() == VY->getVectorKind());
14129 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14130 VX->getNumElements(), VX->getVectorKind());
14131 }
14132 case Type::ExtVector: {
14133 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14134 assert(VX->getNumElements() == VY->getNumElements());
14135 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14136 VX->getNumElements());
14137 }
14138 case Type::DependentSizedExtVector: {
14139 const auto *VX = cast<DependentSizedExtVectorType>(X),
14142 getCommonSizeExpr(Ctx, VX, VY),
14143 getCommonAttrLoc(VX, VY));
14144 }
14145 case Type::DependentVector: {
14146 const auto *VX = cast<DependentVectorType>(X),
14148 assert(VX->getVectorKind() == VY->getVectorKind());
14149 return Ctx.getDependentVectorType(
14150 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14151 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14152 }
14153 case Type::Enum:
14154 case Type::Record:
14155 case Type::InjectedClassName: {
14156 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14157 return Ctx.getTagType(
14158 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14159 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14160 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14161 /*OwnedTag=*/false);
14162 }
14163 case Type::TemplateSpecialization: {
14164 const auto *TX = cast<TemplateSpecializationType>(X),
14166 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14167 TY->template_arguments());
14169 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14170 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14171 TY->getTemplateName(),
14172 /*IgnoreDeduced=*/true),
14173 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14174 }
14175 case Type::Decltype: {
14176 const auto *DX = cast<DecltypeType>(X);
14177 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14178 assert(DX->isDependentType());
14179 assert(DY->isDependentType());
14180 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14181 // As Decltype is not uniqued, building a common type would be wasteful.
14182 return QualType(DX, 0);
14183 }
14184 case Type::PackIndexing: {
14185 const auto *DX = cast<PackIndexingType>(X);
14186 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14187 assert(DX->isDependentType());
14188 assert(DY->isDependentType());
14189 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14190 return QualType(DX, 0);
14191 }
14192 case Type::DependentName: {
14193 const auto *NX = cast<DependentNameType>(X),
14194 *NY = cast<DependentNameType>(Y);
14195 assert(NX->getIdentifier() == NY->getIdentifier());
14196 return Ctx.getDependentNameType(
14197 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14198 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14199 }
14200 case Type::UnaryTransform: {
14201 const auto *TX = cast<UnaryTransformType>(X),
14202 *TY = cast<UnaryTransformType>(Y);
14203 assert(TX->getUTTKind() == TY->getUTTKind());
14204 return Ctx.getUnaryTransformType(
14205 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14206 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14207 TY->getUnderlyingType()),
14208 TX->getUTTKind());
14209 }
14210 case Type::PackExpansion: {
14211 const auto *PX = cast<PackExpansionType>(X),
14212 *PY = cast<PackExpansionType>(Y);
14213 assert(PX->getNumExpansions() == PY->getNumExpansions());
14214 return Ctx.getPackExpansionType(
14215 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14216 PX->getNumExpansions(), false);
14217 }
14218 case Type::Pipe: {
14219 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14220 assert(PX->isReadOnly() == PY->isReadOnly());
14221 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14223 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14224 }
14225 case Type::TemplateTypeParm: {
14226 const auto *TX = cast<TemplateTypeParmType>(X),
14228 assert(TX->getDepth() == TY->getDepth());
14229 assert(TX->getIndex() == TY->getIndex());
14230 assert(TX->isParameterPack() == TY->isParameterPack());
14231 return Ctx.getTemplateTypeParmType(
14232 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14233 getCommonDecl(TX->getDecl(), TY->getDecl()));
14234 }
14235 }
14236 llvm_unreachable("Unknown Type Class");
14237}
14238
14240 const Type *Y,
14241 SplitQualType Underlying) {
14242 Type::TypeClass TC = X->getTypeClass();
14243 if (TC != Y->getTypeClass())
14244 return QualType();
14245 switch (TC) {
14246#define UNEXPECTED_TYPE(Class, Kind) \
14247 case Type::Class: \
14248 llvm_unreachable("Unexpected " Kind ": " #Class);
14249#define TYPE(Class, Base)
14250#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14251#include "clang/AST/TypeNodes.inc"
14252
14253#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14256 CANONICAL_TYPE(BlockPointer)
14259 CANONICAL_TYPE(ConstantArray)
14260 CANONICAL_TYPE(ArrayParameter)
14261 CANONICAL_TYPE(ConstantMatrix)
14263 CANONICAL_TYPE(ExtVector)
14264 CANONICAL_TYPE(FunctionNoProto)
14265 CANONICAL_TYPE(FunctionProto)
14266 CANONICAL_TYPE(IncompleteArray)
14267 CANONICAL_TYPE(HLSLAttributedResource)
14268 CANONICAL_TYPE(HLSLInlineSpirv)
14269 CANONICAL_TYPE(LValueReference)
14270 CANONICAL_TYPE(ObjCInterface)
14271 CANONICAL_TYPE(ObjCObject)
14272 CANONICAL_TYPE(ObjCObjectPointer)
14276 CANONICAL_TYPE(RValueReference)
14277 CANONICAL_TYPE(VariableArray)
14279#undef CANONICAL_TYPE
14280
14281#undef UNEXPECTED_TYPE
14282
14283 case Type::Adjusted: {
14284 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14285 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14286 if (!Ctx.hasSameType(OX, OY))
14287 return QualType();
14288 // FIXME: It's inefficient to have to unify the original types.
14289 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14290 Ctx.getQualifiedType(Underlying));
14291 }
14292 case Type::Decayed: {
14293 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14294 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14295 if (!Ctx.hasSameType(OX, OY))
14296 return QualType();
14297 // FIXME: It's inefficient to have to unify the original types.
14298 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14299 Ctx.getQualifiedType(Underlying));
14300 }
14301 case Type::Attributed: {
14302 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14303 AttributedType::Kind Kind = AX->getAttrKind();
14304 if (Kind != AY->getAttrKind())
14305 return QualType();
14306 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14307 if (!Ctx.hasSameType(MX, MY))
14308 return QualType();
14309 // FIXME: It's inefficient to have to unify the modified types.
14310 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14311 Ctx.getQualifiedType(Underlying),
14312 AX->getAttr());
14313 }
14314 case Type::BTFTagAttributed: {
14315 const auto *BX = cast<BTFTagAttributedType>(X);
14316 const BTFTypeTagAttr *AX = BX->getAttr();
14317 // The attribute is not uniqued, so just compare the tag.
14318 if (AX->getBTFTypeTag() !=
14319 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14320 return QualType();
14321 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14322 }
14323 case Type::Auto: {
14324 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14325
14326 AutoTypeKeyword KW = AX->getKeyword();
14327 if (KW != AY->getKeyword())
14328 return QualType();
14329
14330 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14331 AY->getTypeConstraintConcept());
14333 if (CD &&
14334 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14335 AY->getTypeConstraintArguments())) {
14336 CD = nullptr; // The arguments differ, so make it unconstrained.
14337 As.clear();
14338 }
14339
14340 // Both auto types can't be dependent, otherwise they wouldn't have been
14341 // sugar. This implies they can't contain unexpanded packs either.
14342 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14343 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14344 }
14345 case Type::PackIndexing:
14346 case Type::Decltype:
14347 return QualType();
14348 case Type::DeducedTemplateSpecialization:
14349 // FIXME: Try to merge these.
14350 return QualType();
14351 case Type::MacroQualified: {
14352 const auto *MX = cast<MacroQualifiedType>(X),
14353 *MY = cast<MacroQualifiedType>(Y);
14354 const IdentifierInfo *IX = MX->getMacroIdentifier();
14355 if (IX != MY->getMacroIdentifier())
14356 return QualType();
14357 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14358 }
14359 case Type::SubstTemplateTypeParm: {
14360 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14362 Decl *CD =
14363 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14364 if (!CD)
14365 return QualType();
14366 unsigned Index = SX->getIndex();
14367 if (Index != SY->getIndex())
14368 return QualType();
14369 auto PackIndex = SX->getPackIndex();
14370 if (PackIndex != SY->getPackIndex())
14371 return QualType();
14372 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14373 CD, Index, PackIndex,
14374 SX->getFinal() && SY->getFinal());
14375 }
14376 case Type::ObjCTypeParam:
14377 // FIXME: Try to merge these.
14378 return QualType();
14379 case Type::Paren:
14380 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14381
14382 case Type::TemplateSpecialization: {
14383 const auto *TX = cast<TemplateSpecializationType>(X),
14385 TemplateName CTN =
14386 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14387 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14388 if (!CTN.getAsVoidPointer())
14389 return QualType();
14391 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14392 TY->template_arguments()))
14393 return QualType();
14395 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14396 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14397 }
14398 case Type::Typedef: {
14399 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14400 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14401 if (!CD)
14402 return QualType();
14403 return Ctx.getTypedefType(
14404 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14405 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14406 Ctx.getQualifiedType(Underlying));
14407 }
14408 case Type::TypeOf: {
14409 // The common sugar between two typeof expressions, where one is
14410 // potentially a typeof_unqual and the other is not, we unify to the
14411 // qualified type as that retains the most information along with the type.
14412 // We only return a typeof_unqual type when both types are unqual types.
14417 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14418 }
14419 case Type::TypeOfExpr:
14420 return QualType();
14421
14422 case Type::UnaryTransform: {
14423 const auto *UX = cast<UnaryTransformType>(X),
14424 *UY = cast<UnaryTransformType>(Y);
14425 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14426 if (KX != UY->getUTTKind())
14427 return QualType();
14428 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14429 if (!Ctx.hasSameType(BX, BY))
14430 return QualType();
14431 // FIXME: It's inefficient to have to unify the base types.
14432 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14433 Ctx.getQualifiedType(Underlying), KX);
14434 }
14435 case Type::Using: {
14436 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14437 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14438 if (!CD)
14439 return QualType();
14440 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14441 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14442 CD, Ctx.getQualifiedType(Underlying));
14443 }
14444 case Type::MemberPointer: {
14445 const auto *PX = cast<MemberPointerType>(X),
14446 *PY = cast<MemberPointerType>(Y);
14447 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14448 assert(Cls == PY->getMostRecentCXXRecordDecl());
14449 return Ctx.getMemberPointerType(
14450 ::getCommonPointeeType(Ctx, PX, PY),
14451 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14452 }
14453 case Type::CountAttributed: {
14454 const auto *DX = cast<CountAttributedType>(X),
14456 if (DX->isCountInBytes() != DY->isCountInBytes())
14457 return QualType();
14458 if (DX->isOrNull() != DY->isOrNull())
14459 return QualType();
14460 Expr *CEX = DX->getCountExpr();
14461 Expr *CEY = DY->getCountExpr();
14462 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14463 if (Ctx.hasSameExpr(CEX, CEY))
14464 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14465 DX->isCountInBytes(), DX->isOrNull(),
14466 CDX);
14467 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14468 return QualType();
14469 // Two declarations with the same integer constant may still differ in their
14470 // expression pointers, so we need to evaluate them.
14471 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14472 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14473 if (VX != VY)
14474 return QualType();
14475 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14476 DX->isCountInBytes(), DX->isOrNull(),
14477 CDX);
14478 }
14479 case Type::PredefinedSugar:
14480 assert(cast<PredefinedSugarType>(X)->getKind() !=
14482 return QualType();
14483 }
14484 llvm_unreachable("Unhandled Type Class");
14485}
14486
14487static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14489 while (true) {
14490 QTotal.addConsistentQualifiers(T.Quals);
14491 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14492 if (NT == QualType(T.Ty, 0))
14493 break;
14494 R.push_back(T);
14495 T = NT.split();
14496 }
14497 return R;
14498}
14499
14501 bool Unqualified) const {
14502 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14503 if (X == Y)
14504 return X;
14505 if (!Unqualified) {
14506 if (X.isCanonical())
14507 return X;
14508 if (Y.isCanonical())
14509 return Y;
14510 }
14511
14512 SplitQualType SX = X.split(), SY = Y.split();
14513 Qualifiers QX, QY;
14514 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14515 // until we reach their underlying "canonical nodes". Note these are not
14516 // necessarily canonical types, as they may still have sugared properties.
14517 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14518 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14519
14520 // If this is an ArrayType, the element qualifiers are interchangeable with
14521 // the top level qualifiers.
14522 // * In case the canonical nodes are the same, the elements types are already
14523 // the same.
14524 // * Otherwise, the element types will be made the same, and any different
14525 // element qualifiers will be moved up to the top level qualifiers, per
14526 // 'getCommonArrayElementType'.
14527 // In both cases, this means there may be top level qualifiers which differ
14528 // between X and Y. If so, these differing qualifiers are redundant with the
14529 // element qualifiers, and can be removed without changing the canonical type.
14530 // The desired behaviour is the same as for the 'Unqualified' case here:
14531 // treat the redundant qualifiers as sugar, remove the ones which are not
14532 // common to both sides.
14533 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14534
14535 if (SX.Ty != SY.Ty) {
14536 // The canonical nodes differ. Build a common canonical node out of the two,
14537 // unifying their sugar. This may recurse back here.
14538 SX.Ty =
14539 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14540 } else {
14541 // The canonical nodes were identical: We may have desugared too much.
14542 // Add any common sugar back in.
14543 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14544 QX -= SX.Quals;
14545 QY -= SY.Quals;
14546 SX = Xs.pop_back_val();
14547 SY = Ys.pop_back_val();
14548 }
14549 }
14550 if (KeepCommonQualifiers)
14552 else
14553 assert(QX == QY);
14554
14555 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14556 // related. Walk up these nodes, unifying them and adding the result.
14557 while (!Xs.empty() && !Ys.empty()) {
14558 auto Underlying = SplitQualType(
14559 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14560 SX = Xs.pop_back_val();
14561 SY = Ys.pop_back_val();
14562 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14564 // Stop at the first pair which is unrelated.
14565 if (!SX.Ty) {
14566 SX.Ty = Underlying.Ty;
14567 break;
14568 }
14569 QX -= Underlying.Quals;
14570 };
14571
14572 // Add back the missing accumulated qualifiers, which were stripped off
14573 // with the sugar nodes we could not unify.
14574 QualType R = getQualifiedType(SX.Ty, QX);
14575 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14576 return R;
14577}
14578
14580 assert(Ty->isFixedPointType());
14581
14583 return Ty;
14584
14585 switch (Ty->castAs<BuiltinType>()->getKind()) {
14586 default:
14587 llvm_unreachable("Not a saturated fixed point type!");
14588 case BuiltinType::SatShortAccum:
14589 return ShortAccumTy;
14590 case BuiltinType::SatAccum:
14591 return AccumTy;
14592 case BuiltinType::SatLongAccum:
14593 return LongAccumTy;
14594 case BuiltinType::SatUShortAccum:
14595 return UnsignedShortAccumTy;
14596 case BuiltinType::SatUAccum:
14597 return UnsignedAccumTy;
14598 case BuiltinType::SatULongAccum:
14599 return UnsignedLongAccumTy;
14600 case BuiltinType::SatShortFract:
14601 return ShortFractTy;
14602 case BuiltinType::SatFract:
14603 return FractTy;
14604 case BuiltinType::SatLongFract:
14605 return LongFractTy;
14606 case BuiltinType::SatUShortFract:
14607 return UnsignedShortFractTy;
14608 case BuiltinType::SatUFract:
14609 return UnsignedFractTy;
14610 case BuiltinType::SatULongFract:
14611 return UnsignedLongFractTy;
14612 }
14613}
14614
14616 assert(Ty->isFixedPointType());
14617
14618 if (Ty->isSaturatedFixedPointType()) return Ty;
14619
14620 switch (Ty->castAs<BuiltinType>()->getKind()) {
14621 default:
14622 llvm_unreachable("Not a fixed point type!");
14623 case BuiltinType::ShortAccum:
14624 return SatShortAccumTy;
14625 case BuiltinType::Accum:
14626 return SatAccumTy;
14627 case BuiltinType::LongAccum:
14628 return SatLongAccumTy;
14629 case BuiltinType::UShortAccum:
14631 case BuiltinType::UAccum:
14632 return SatUnsignedAccumTy;
14633 case BuiltinType::ULongAccum:
14635 case BuiltinType::ShortFract:
14636 return SatShortFractTy;
14637 case BuiltinType::Fract:
14638 return SatFractTy;
14639 case BuiltinType::LongFract:
14640 return SatLongFractTy;
14641 case BuiltinType::UShortFract:
14643 case BuiltinType::UFract:
14644 return SatUnsignedFractTy;
14645 case BuiltinType::ULongFract:
14647 }
14648}
14649
14651 if (LangOpts.OpenCL)
14653
14654 if (LangOpts.CUDA)
14656
14657 return getLangASFromTargetAS(AS);
14658}
14659
14660// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14661// doesn't include ASTContext.h
14662template
14664 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14666 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14667 const clang::ASTContext &Ctx, Decl *Value);
14668
14670 assert(Ty->isFixedPointType());
14671
14672 const TargetInfo &Target = getTargetInfo();
14673 switch (Ty->castAs<BuiltinType>()->getKind()) {
14674 default:
14675 llvm_unreachable("Not a fixed point type!");
14676 case BuiltinType::ShortAccum:
14677 case BuiltinType::SatShortAccum:
14678 return Target.getShortAccumScale();
14679 case BuiltinType::Accum:
14680 case BuiltinType::SatAccum:
14681 return Target.getAccumScale();
14682 case BuiltinType::LongAccum:
14683 case BuiltinType::SatLongAccum:
14684 return Target.getLongAccumScale();
14685 case BuiltinType::UShortAccum:
14686 case BuiltinType::SatUShortAccum:
14687 return Target.getUnsignedShortAccumScale();
14688 case BuiltinType::UAccum:
14689 case BuiltinType::SatUAccum:
14690 return Target.getUnsignedAccumScale();
14691 case BuiltinType::ULongAccum:
14692 case BuiltinType::SatULongAccum:
14693 return Target.getUnsignedLongAccumScale();
14694 case BuiltinType::ShortFract:
14695 case BuiltinType::SatShortFract:
14696 return Target.getShortFractScale();
14697 case BuiltinType::Fract:
14698 case BuiltinType::SatFract:
14699 return Target.getFractScale();
14700 case BuiltinType::LongFract:
14701 case BuiltinType::SatLongFract:
14702 return Target.getLongFractScale();
14703 case BuiltinType::UShortFract:
14704 case BuiltinType::SatUShortFract:
14705 return Target.getUnsignedShortFractScale();
14706 case BuiltinType::UFract:
14707 case BuiltinType::SatUFract:
14708 return Target.getUnsignedFractScale();
14709 case BuiltinType::ULongFract:
14710 case BuiltinType::SatULongFract:
14711 return Target.getUnsignedLongFractScale();
14712 }
14713}
14714
14716 assert(Ty->isFixedPointType());
14717
14718 const TargetInfo &Target = getTargetInfo();
14719 switch (Ty->castAs<BuiltinType>()->getKind()) {
14720 default:
14721 llvm_unreachable("Not a fixed point type!");
14722 case BuiltinType::ShortAccum:
14723 case BuiltinType::SatShortAccum:
14724 return Target.getShortAccumIBits();
14725 case BuiltinType::Accum:
14726 case BuiltinType::SatAccum:
14727 return Target.getAccumIBits();
14728 case BuiltinType::LongAccum:
14729 case BuiltinType::SatLongAccum:
14730 return Target.getLongAccumIBits();
14731 case BuiltinType::UShortAccum:
14732 case BuiltinType::SatUShortAccum:
14733 return Target.getUnsignedShortAccumIBits();
14734 case BuiltinType::UAccum:
14735 case BuiltinType::SatUAccum:
14736 return Target.getUnsignedAccumIBits();
14737 case BuiltinType::ULongAccum:
14738 case BuiltinType::SatULongAccum:
14739 return Target.getUnsignedLongAccumIBits();
14740 case BuiltinType::ShortFract:
14741 case BuiltinType::SatShortFract:
14742 case BuiltinType::Fract:
14743 case BuiltinType::SatFract:
14744 case BuiltinType::LongFract:
14745 case BuiltinType::SatLongFract:
14746 case BuiltinType::UShortFract:
14747 case BuiltinType::SatUShortFract:
14748 case BuiltinType::UFract:
14749 case BuiltinType::SatUFract:
14750 case BuiltinType::ULongFract:
14751 case BuiltinType::SatULongFract:
14752 return 0;
14753 }
14754}
14755
14756llvm::FixedPointSemantics
14758 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14759 "Can only get the fixed point semantics for a "
14760 "fixed point or integer type.");
14761 if (Ty->isIntegerType())
14762 return llvm::FixedPointSemantics::GetIntegerSemantics(
14763 getIntWidth(Ty), Ty->isSignedIntegerType());
14764
14765 bool isSigned = Ty->isSignedFixedPointType();
14766 return llvm::FixedPointSemantics(
14767 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14769 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14770}
14771
14772llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14773 assert(Ty->isFixedPointType());
14774 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14775}
14776
14777llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14778 assert(Ty->isFixedPointType());
14779 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14780}
14781
14783 assert(Ty->isUnsignedFixedPointType() &&
14784 "Expected unsigned fixed point type");
14785
14786 switch (Ty->castAs<BuiltinType>()->getKind()) {
14787 case BuiltinType::UShortAccum:
14788 return ShortAccumTy;
14789 case BuiltinType::UAccum:
14790 return AccumTy;
14791 case BuiltinType::ULongAccum:
14792 return LongAccumTy;
14793 case BuiltinType::SatUShortAccum:
14794 return SatShortAccumTy;
14795 case BuiltinType::SatUAccum:
14796 return SatAccumTy;
14797 case BuiltinType::SatULongAccum:
14798 return SatLongAccumTy;
14799 case BuiltinType::UShortFract:
14800 return ShortFractTy;
14801 case BuiltinType::UFract:
14802 return FractTy;
14803 case BuiltinType::ULongFract:
14804 return LongFractTy;
14805 case BuiltinType::SatUShortFract:
14806 return SatShortFractTy;
14807 case BuiltinType::SatUFract:
14808 return SatFractTy;
14809 case BuiltinType::SatULongFract:
14810 return SatLongFractTy;
14811 default:
14812 llvm_unreachable("Unexpected unsigned fixed point type");
14813 }
14814}
14815
14816// Given a list of FMV features, return a concatenated list of the
14817// corresponding backend features (which may contain duplicates).
14818static std::vector<std::string> getFMVBackendFeaturesFor(
14819 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14820 std::vector<std::string> BackendFeats;
14821 llvm::AArch64::ExtensionSet FeatureBits;
14822 for (StringRef F : FMVFeatStrings)
14823 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14824 if (FMVExt->ID)
14825 FeatureBits.enable(*FMVExt->ID);
14826 FeatureBits.toLLVMFeatureList(BackendFeats);
14827 return BackendFeats;
14828}
14829
14830ParsedTargetAttr
14831ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14832 assert(TD != nullptr);
14833 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14834
14835 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14836 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14837 });
14838 return ParsedAttr;
14839}
14840
14841void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14842 const FunctionDecl *FD) const {
14843 if (FD)
14844 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14845 else
14846 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14847 Target->getTargetOpts().CPU,
14848 Target->getTargetOpts().Features);
14849}
14850
14851// Fills in the supplied string map with the set of target features for the
14852// passed in function.
14853void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14854 GlobalDecl GD) const {
14855 StringRef TargetCPU = Target->getTargetOpts().CPU;
14856 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14857 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14859
14860 // Make a copy of the features as passed on the command line into the
14861 // beginning of the additional features from the function to override.
14862 // AArch64 handles command line option features in parseTargetAttr().
14863 if (!Target->getTriple().isAArch64())
14864 ParsedAttr.Features.insert(
14865 ParsedAttr.Features.begin(),
14866 Target->getTargetOpts().FeaturesAsWritten.begin(),
14867 Target->getTargetOpts().FeaturesAsWritten.end());
14868
14869 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14870 TargetCPU = ParsedAttr.CPU;
14871
14872 // Now populate the feature map, first with the TargetCPU which is either
14873 // the default or a new one from the target attribute string. Then we'll use
14874 // the passed in features (FeaturesAsWritten) along with the new ones from
14875 // the attribute.
14876 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14877 ParsedAttr.Features);
14878 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14880 Target->getCPUSpecificCPUDispatchFeatures(
14881 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14882 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14883 Features.insert(Features.begin(),
14884 Target->getTargetOpts().FeaturesAsWritten.begin(),
14885 Target->getTargetOpts().FeaturesAsWritten.end());
14886 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14887 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14888 if (Target->getTriple().isAArch64()) {
14890 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14891 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14892 Features.insert(Features.begin(),
14893 Target->getTargetOpts().FeaturesAsWritten.begin(),
14894 Target->getTargetOpts().FeaturesAsWritten.end());
14895 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14896 } else if (Target->getTriple().isRISCV()) {
14897 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14898 std::vector<std::string> Features;
14899 if (VersionStr != "default") {
14900 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14901 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14902 ParsedAttr.Features.end());
14903 }
14904 Features.insert(Features.begin(),
14905 Target->getTargetOpts().FeaturesAsWritten.begin(),
14906 Target->getTargetOpts().FeaturesAsWritten.end());
14907 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14908 } else {
14909 std::vector<std::string> Features;
14910 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14911 if (VersionStr.starts_with("arch="))
14912 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14913 else if (VersionStr != "default")
14914 Features.push_back((StringRef{"+"} + VersionStr).str());
14915 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14916 }
14917 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14918 std::vector<std::string> Features;
14919 if (Target->getTriple().isRISCV()) {
14920 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14921 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14922 ParsedAttr.Features.end());
14923 } else {
14924 assert(Target->getTriple().isAArch64());
14926 TV->getFeatures(Feats);
14927 Features = getFMVBackendFeaturesFor(Feats);
14928 }
14929 Features.insert(Features.begin(),
14930 Target->getTargetOpts().FeaturesAsWritten.begin(),
14931 Target->getTargetOpts().FeaturesAsWritten.end());
14932 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14933 } else {
14934 FeatureMap = Target->getTargetOpts().FeatureMap;
14935 }
14936}
14937
14939 CanQualType KernelNameType,
14940 const FunctionDecl *FD) {
14941 // Host and device compilation may use different ABIs and different ABIs
14942 // may allocate name mangling discriminators differently. A discriminator
14943 // override is used to ensure consistent discriminator allocation across
14944 // host and device compilation.
14945 auto DeviceDiscriminatorOverrider =
14946 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
14947 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
14948 if (RD->isLambda())
14949 return RD->getDeviceLambdaManglingNumber();
14950 return std::nullopt;
14951 };
14952 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
14953 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
14954
14955 // Construct a mangled name for the SYCL kernel caller offload entry point.
14956 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
14957 // name the SYCL kernel caller offload entry point function. This mangling
14958 // does not suffice to clearly identify symbols that correspond to SYCL
14959 // kernel caller functions, nor is this mangling natural for targets that
14960 // use a non-Itanium ABI.
14961 std::string Buffer;
14962 Buffer.reserve(128);
14963 llvm::raw_string_ostream Out(Buffer);
14964 MC->mangleCanonicalTypeName(KernelNameType, Out);
14965 std::string KernelName = Out.str();
14966
14967 return {KernelNameType, FD, KernelName};
14968}
14969
14971 // If the function declaration to register is invalid or dependent, the
14972 // registration attempt is ignored.
14973 if (FD->isInvalidDecl() || FD->isTemplated())
14974 return;
14975
14976 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
14977 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
14978
14979 // Be tolerant of multiple registration attempts so long as each attempt
14980 // is for the same entity. Callers are obligated to detect and diagnose
14981 // conflicting kernel names prior to calling this function.
14982 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
14983 auto IT = SYCLKernels.find(KernelNameType);
14984 assert((IT == SYCLKernels.end() ||
14985 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
14986 "SYCL kernel name conflict");
14987 (void)IT;
14988 SYCLKernels.insert(std::make_pair(
14989 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
14990}
14991
14993 CanQualType KernelNameType = getCanonicalType(T);
14994 return SYCLKernels.at(KernelNameType);
14995}
14996
14998 CanQualType KernelNameType = getCanonicalType(T);
14999 auto IT = SYCLKernels.find(KernelNameType);
15000 if (IT != SYCLKernels.end())
15001 return &IT->second;
15002 return nullptr;
15003}
15004
15006 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15007 return *OMPTraitInfoVector.back();
15008}
15009
15012 const ASTContext::SectionInfo &Section) {
15013 if (Section.Decl)
15014 return DB << Section.Decl;
15015 return DB << "a prior #pragma section";
15016}
15017
15018bool ASTContext::mayExternalize(const Decl *D) const {
15019 bool IsInternalVar =
15020 isa<VarDecl>(D) &&
15022 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15023 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15024 (D->hasAttr<CUDAConstantAttr>() &&
15025 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15026 // CUDA/HIP: managed variables need to be externalized since it is
15027 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15028 // anonymous name space needs to be externalized to avoid duplicate symbols.
15029 return (IsInternalVar &&
15030 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15031 (D->hasAttr<CUDAGlobalAttr>() &&
15033 GVA_Internal);
15034}
15035
15037 return mayExternalize(D) &&
15038 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15040}
15041
15042StringRef ASTContext::getCUIDHash() const {
15043 if (!CUIDHash.empty())
15044 return CUIDHash;
15045 if (LangOpts.CUID.empty())
15046 return StringRef();
15047 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15048 return CUIDHash;
15049}
15050
15051const CXXRecordDecl *
15053 assert(ThisClass);
15054 assert(ThisClass->isPolymorphic());
15055 const CXXRecordDecl *PrimaryBase = ThisClass;
15056 while (1) {
15057 assert(PrimaryBase);
15058 assert(PrimaryBase->isPolymorphic());
15059 auto &Layout = getASTRecordLayout(PrimaryBase);
15060 auto Base = Layout.getPrimaryBase();
15061 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15062 break;
15063 PrimaryBase = Base;
15064 }
15065 return PrimaryBase;
15066}
15067
15069 StringRef MangledName) {
15070 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15071 assert(Method->isVirtual());
15072 bool DefaultIncludesPointerAuth =
15073 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15074
15075 if (!DefaultIncludesPointerAuth)
15076 return true;
15077
15078 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15079 if (Existing != ThunksToBeAbbreviated.end())
15080 return Existing->second.contains(MangledName.str());
15081
15082 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15083 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15084 auto VtableContext = getVTableContext();
15085 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15086 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15087 for (const auto &Thunk : *ThunkInfos) {
15088 SmallString<256> ElidedName;
15089 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15090 if (Destructor)
15091 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15092 Thunk, /* elideOverrideInfo */ true,
15093 ElidedNameStream);
15094 else
15095 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15096 ElidedNameStream);
15097 SmallString<256> MangledName;
15098 llvm::raw_svector_ostream mangledNameStream(MangledName);
15099 if (Destructor)
15100 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15101 Thunk, /* elideOverrideInfo */ false,
15102 mangledNameStream);
15103 else
15104 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15105 mangledNameStream);
15106
15107 Thunks[ElidedName].push_back(std::string(MangledName));
15108 }
15109 }
15110 llvm::StringSet<> SimplifiedThunkNames;
15111 for (auto &ThunkList : Thunks) {
15112 llvm::sort(ThunkList.second);
15113 SimplifiedThunkNames.insert(ThunkList.second[0]);
15114 }
15115 bool Result = SimplifiedThunkNames.contains(MangledName);
15116 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15117 return Result;
15118}
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 void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:451
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:988
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType 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.
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:776
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:777
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
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:926
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:773
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:959
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:555
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:775
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition ASTContext.h:962
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:221
void PrintStats() const
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:778
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
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:547
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:968
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:846
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition ASTContext.h:984
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition ASTContext.h:975
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3510
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
llvm::APInt getArraySize() const
Definition Expr.h:5924
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3740
QualType getElementType() const
Definition TypeBase.h:3734
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3744
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:6814
Expr * getPtr() const
Definition Expr.h:6845
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8098
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8146
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8163
unsigned getNumBits() const
Definition TypeBase.h:8158
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4654
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Pointer to a block type.
Definition TypeBase.h:3542
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3559
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:3164
Kind getKind() const
Definition TypeBase.h:3212
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3363
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3290
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:3760
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3875
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4394
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4411
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4391
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4402
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3436
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3472
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3525
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:1270
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:319
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h: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:4061
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4083
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8191
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4011
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4040
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4126
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4432
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4452
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:6211
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6216
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4252
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.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:905
Represents an enum.
Definition Decl.h:4007
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4216
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4230
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4114
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
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:3090
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4205
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
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:3065
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:4042
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1717
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1764
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
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:5467
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:4740
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:4688
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:3750
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:3879
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3735
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:4405
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:4066
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5234
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5641
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5679
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5066
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5100
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4844
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4860
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5770
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5573
unsigned getNumParams() const
Definition TypeBase.h:5544
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3956
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5579
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5670
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5739
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5735
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4573
CallingConv getCC() const
Definition TypeBase.h:4632
unsigned getRegParm() const
Definition TypeBase.h:4625
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4621
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4644
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4488
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4528
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4462
ExtInfo getExtInfo() const
Definition TypeBase.h:4818
QualType getReturnType() const
Definition TypeBase.h:4802
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:5035
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3926
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:3617
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4398
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4435
MSGuidDeclParts Parts
Definition DeclCXX.h:4400
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6145
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4351
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4358
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3696
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:3261
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
bool isCanonical() const
Whether this nested name specifier is canonical.
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
Helper data structure representing the traits in a match clause of an declare variant or metadirectiv...
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2329
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2545
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2597
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_range ivars() const
Definition DeclObjC.h:1451
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1810
known_extensions_range known_extensions() const
Definition DeclObjC.h:1762
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7856
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:951
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1987
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclObjC.h:246
unsigned param_size() const
Definition DeclObjC.h:347
param_const_iterator param_end() const
Definition DeclObjC.h:358
param_const_iterator param_begin() const
Definition DeclObjC.h:354
bool isVariadic() const
Definition DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:349
Selector getSelector() const
Definition DeclObjC.h:327
bool isInstanceMethod() const
Definition DeclObjC.h:426
QualType getReturnType() const
Definition DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition TypeBase.h:7912
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7993
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:958
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:7987
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8069
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7949
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7970
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7924
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7964
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8031
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7976
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4365
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3316
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1790
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1854
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8129
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:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3343
PredefinedSugarKind Kind
Definition TypeBase.h:8205
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1457
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8378
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8425
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8383
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1296
QualType withConst() const
Definition TypeBase.h:1159
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1064
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8294
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8420
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8334
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8346
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8388
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8315
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8367
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8351
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8298
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition Type.cpp:2990
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8326
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:8234
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8241
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:3635
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:4312
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5172
bool hasFlexibleArrayMember() const
Definition Decl.h:4345
field_range fields() const
Definition Decl.h:4515
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5158
RecordDecl * getMostRecentDecl()
Definition Decl.h:4338
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5217
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4496
bool field_empty() const
Definition Decl.h:4523
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:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3599
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:1799
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
TagTypeKind TagKind
Definition Decl.h:3722
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3948
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4894
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4887
bool isUnion() const
Definition Decl.h:3922
TagKind getTagKind() const
Definition Decl.h:3911
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h: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:216
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6177
A container of type source information.
Definition TypeBase.h:8265
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8551
bool isVoidType() const
Definition TypeBase.h:8887
bool isObjCBuiltinType() const
Definition TypeBase.h:8751
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2678
bool isIncompleteArrayType() const
Definition TypeBase.h:8638
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2205
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:8634
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:2426
bool isArrayType() const
Definition TypeBase.h:8630
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8531
bool isArrayParameterType() const
Definition TypeBase.h:8646
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8931
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9174
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:8971
bool isEnumeralType() const
Definition TypeBase.h:8662
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8721
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9005
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8796
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8654
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8943
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8959
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3119
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2281
@ SizeT
The "size_t" type.
Definition TypeBase.h:2275
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2278
bool isObjCIdType() const
Definition TypeBase.h:8733
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8967
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9160
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:2436
bool isFunctionType() const
Definition TypeBase.h:8527
bool isObjCObjectPointerType() const
Definition TypeBase.h:8700
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:8985
bool isVectorType() const
Definition TypeBase.h:8670
bool isObjCClassType() const
Definition TypeBase.h:8739
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2660
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
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:2253
bool isAnyPointerType() const
Definition TypeBase.h:8539
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9107
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:653
bool isNullPtrType() const
Definition TypeBase.h:8924
bool isRecordType() const
Definition TypeBase.h:8658
bool isObjCRetainableType() const
Definition Type.cpp:5291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
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:5680
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:6121
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4483
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5982
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6019
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4037
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4102
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3792
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6059
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:5500
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:2810
bool hasInit() const
Definition Decl.cpp:2398
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h: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:2375
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4199
VectorKind getVectorKind() const
Definition TypeBase.h:4195
QualType getElementType() const
Definition TypeBase.h:4189
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8429
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:3719
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5895
@ Struct
The "struct" keyword.
Definition TypeBase.h:5892
@ Class
The "class" keyword.
Definition TypeBase.h:5901
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
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:4145
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4154
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4142
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4160
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4163
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4157
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:176
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:187
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:181
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:184
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5865
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5870
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5876
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5873
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5883
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:6604
Expr * getCopyExpr() const
Definition Expr.h:6611
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:5323
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5325
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5328
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5331
Extra information about a function prototype.
Definition TypeBase.h:5351
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5397
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5356
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5401
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5390
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:3259
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:207
bool isAlignRequired()
Definition ASTContext.h:199
AlignRequirementKind AlignRequirement
Definition ASTContext.h:193
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