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
333/// If we have a 'templated' declaration for a template, adjust 'D' to
334/// refer to the actual template.
335/// If we have an implicit instantiation, adjust 'D' to refer to template.
336static const Decl &adjustDeclToTemplate(const Decl &D) {
337 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
338 // Is this function declaration part of a function template?
339 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
340 return *FTD;
341
342 // Nothing to do if function is not an implicit instantiation.
343 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
344 return D;
345
346 // Function is an implicit instantiation of a function template?
347 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
348 return *FTD;
349
350 // Function is instantiated from a member definition of a class template?
351 if (const FunctionDecl *MemberDecl =
353 return *MemberDecl;
354
355 return D;
356 }
357 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
358 // Static data member is instantiated from a member definition of a class
359 // template?
360 if (VD->isStaticDataMember())
361 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
362 return *MemberDecl;
363
364 return D;
365 }
366 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
367 // Is this class declaration part of a class template?
368 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
369 return *CTD;
370
371 // Class is an implicit instantiation of a class template or partial
372 // specialization?
373 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
374 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
375 return D;
376 llvm::PointerUnion<ClassTemplateDecl *,
379 return isa<ClassTemplateDecl *>(PU)
380 ? *static_cast<const Decl *>(cast<ClassTemplateDecl *>(PU))
381 : *static_cast<const Decl *>(
383 }
384
385 // Class is instantiated from a member definition of a class template?
386 if (const MemberSpecializationInfo *Info =
387 CRD->getMemberSpecializationInfo())
388 return *Info->getInstantiatedFrom();
389
390 return D;
391 }
392 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
393 // Enum is instantiated from a member definition of a class template?
394 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
395 return *MemberDecl;
396
397 return D;
398 }
399 // FIXME: Adjust alias templates?
400 return D;
401}
402
404 const Decl *D,
405 const Decl **OriginalDecl) const {
406 if (!D) {
407 if (OriginalDecl)
408 OriginalDecl = nullptr;
409 return nullptr;
410 }
411
412 D = &adjustDeclToTemplate(*D);
413
414 // Any comment directly attached to D?
415 {
416 auto DeclComment = DeclRawComments.find(D);
417 if (DeclComment != DeclRawComments.end()) {
418 if (OriginalDecl)
419 *OriginalDecl = D;
420 return DeclComment->second;
421 }
422 }
423
424 // Any comment attached to any redeclaration of D?
425 const Decl *CanonicalD = D->getCanonicalDecl();
426 if (!CanonicalD)
427 return nullptr;
428
429 {
430 auto RedeclComment = RedeclChainComments.find(CanonicalD);
431 if (RedeclComment != RedeclChainComments.end()) {
432 if (OriginalDecl)
433 *OriginalDecl = RedeclComment->second;
434 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
435 assert(CommentAtRedecl != DeclRawComments.end() &&
436 "This decl is supposed to have comment attached.");
437 return CommentAtRedecl->second;
438 }
439 }
440
441 // Any redeclarations of D that we haven't checked for comments yet?
442 const Decl *LastCheckedRedecl = [&]() {
443 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
444 bool CanUseCommentlessCache = false;
445 if (LastChecked) {
446 for (auto *Redecl : CanonicalD->redecls()) {
447 if (Redecl == D) {
448 CanUseCommentlessCache = true;
449 break;
450 }
451 if (Redecl == LastChecked)
452 break;
453 }
454 }
455 // FIXME: This could be improved so that even if CanUseCommentlessCache
456 // is false, once we've traversed past CanonicalD we still skip ahead
457 // LastChecked.
458 return CanUseCommentlessCache ? LastChecked : nullptr;
459 }();
460
461 for (const Decl *Redecl : D->redecls()) {
462 assert(Redecl);
463 // Skip all redeclarations that have been checked previously.
464 if (LastCheckedRedecl) {
465 if (LastCheckedRedecl == Redecl) {
466 LastCheckedRedecl = nullptr;
467 }
468 continue;
469 }
470 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
471 if (RedeclComment) {
472 cacheRawCommentForDecl(*Redecl, *RedeclComment);
473 if (OriginalDecl)
474 *OriginalDecl = Redecl;
475 return RedeclComment;
476 }
477 CommentlessRedeclChains[CanonicalD] = Redecl;
478 }
479
480 if (OriginalDecl)
481 *OriginalDecl = nullptr;
482 return nullptr;
483}
484
486 const RawComment &Comment) const {
487 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
488 DeclRawComments.try_emplace(&OriginalD, &Comment);
489 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
490 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
491 CommentlessRedeclChains.erase(CanonicalDecl);
492}
493
494static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
496 const DeclContext *DC = ObjCMethod->getDeclContext();
497 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
498 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
499 if (!ID)
500 return;
501 // Add redeclared method here.
502 for (const auto *Ext : ID->known_extensions()) {
503 if (ObjCMethodDecl *RedeclaredMethod =
504 Ext->getMethod(ObjCMethod->getSelector(),
505 ObjCMethod->isInstanceMethod()))
506 Redeclared.push_back(RedeclaredMethod);
507 }
508 }
509}
510
512 const Preprocessor *PP) {
513 if (Comments.empty() || Decls.empty())
514 return;
515
516 FileID File;
517 for (const Decl *D : Decls) {
518 if (D->isInvalidDecl())
519 continue;
520
521 D = &adjustDeclToTemplate(*D);
522 SourceLocation Loc = D->getLocation();
523 if (Loc.isValid()) {
524 // See if there are any new comments that are not attached to a decl.
525 // The location doesn't have to be precise - we care only about the file.
526 File = SourceMgr.getDecomposedLoc(Loc).first;
527 break;
528 }
529 }
530
531 if (File.isInvalid())
532 return;
533
534 auto CommentsInThisFile = Comments.getCommentsInFile(File);
535 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
536 CommentsInThisFile->rbegin()->second->isAttached())
537 return;
538
539 // There is at least one comment not attached to a decl.
540 // Maybe it should be attached to one of Decls?
541 //
542 // Note that this way we pick up not only comments that precede the
543 // declaration, but also comments that *follow* the declaration -- thanks to
544 // the lookahead in the lexer: we've consumed the semicolon and looked
545 // ahead through comments.
546 for (const Decl *D : Decls) {
547 assert(D);
548 if (D->isInvalidDecl())
549 continue;
550
551 D = &adjustDeclToTemplate(*D);
552
553 if (DeclRawComments.count(D) > 0)
554 continue;
555
556 const auto DeclLocs = getDeclLocsForCommentSearch(D, SourceMgr);
557
558 for (const auto DeclLoc : DeclLocs) {
559 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
560 continue;
561
562 if (RawComment *const DocComment = getRawCommentForDeclNoCacheImpl(
563 D, DeclLoc, *CommentsInThisFile)) {
564 cacheRawCommentForDecl(*D, *DocComment);
565 comments::FullComment *FC = DocComment->parse(*this, PP, D);
566 ParsedComments[D->getCanonicalDecl()] = FC;
567 break;
568 }
569 }
570 }
571}
572
574 const Decl *D) const {
575 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
576 ThisDeclInfo->CommentDecl = D;
577 ThisDeclInfo->IsFilled = false;
578 ThisDeclInfo->fill();
579 ThisDeclInfo->CommentDecl = FC->getDecl();
580 if (!ThisDeclInfo->TemplateParameters)
581 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
583 new (*this) comments::FullComment(FC->getBlocks(),
584 ThisDeclInfo);
585 return CFC;
586}
587
590 return RC ? RC->parse(*this, nullptr, D) : nullptr;
591}
592
594 const Decl *D,
595 const Preprocessor *PP) const {
596 if (!D || D->isInvalidDecl())
597 return nullptr;
598 D = &adjustDeclToTemplate(*D);
599
600 const Decl *Canonical = D->getCanonicalDecl();
601 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
602 ParsedComments.find(Canonical);
603
604 if (Pos != ParsedComments.end()) {
605 if (Canonical != D) {
606 comments::FullComment *FC = Pos->second;
608 return CFC;
609 }
610 return Pos->second;
611 }
612
613 const Decl *OriginalDecl = nullptr;
614
615 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
616 if (!RC) {
619 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
620 if (OMD && OMD->isPropertyAccessor())
621 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
622 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
623 return cloneFullComment(FC, D);
624 if (OMD)
625 addRedeclaredMethods(OMD, Overridden);
626 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
627 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
628 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
632 // Attach any tag type's documentation to its typedef if latter
633 // does not have one of its own.
634 QualType QT = TD->getUnderlyingType();
635 if (const auto *TT = QT->getAs<TagType>())
636 if (comments::FullComment *FC =
637 getCommentForDecl(TT->getOriginalDecl(), PP))
638 return cloneFullComment(FC, D);
639 }
640 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
641 while (IC->getSuperClass()) {
642 IC = IC->getSuperClass();
644 return cloneFullComment(FC, D);
645 }
646 }
647 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
648 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
650 return cloneFullComment(FC, D);
651 }
652 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
653 if (!(RD = RD->getDefinition()))
654 return nullptr;
655 // Check non-virtual bases.
656 for (const auto &I : RD->bases()) {
657 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
658 continue;
659 QualType Ty = I.getType();
660 if (Ty.isNull())
661 continue;
663 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
664 continue;
665
667 return cloneFullComment(FC, D);
668 }
669 }
670 // Check virtual bases.
671 for (const auto &I : RD->vbases()) {
672 if (I.getAccessSpecifier() != AS_public)
673 continue;
674 QualType Ty = I.getType();
675 if (Ty.isNull())
676 continue;
677 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
678 if (!(VirtualBase= VirtualBase->getDefinition()))
679 continue;
681 return cloneFullComment(FC, D);
682 }
683 }
684 }
685 return nullptr;
686 }
687
688 // If the RawComment was attached to other redeclaration of this Decl, we
689 // should parse the comment in context of that other Decl. This is important
690 // because comments can contain references to parameter names which can be
691 // different across redeclarations.
692 if (D != OriginalDecl && OriginalDecl)
693 return getCommentForDecl(OriginalDecl, PP);
694
695 comments::FullComment *FC = RC->parse(*this, PP, D);
696 ParsedComments[Canonical] = FC;
697 return FC;
698}
699
700void ASTContext::CanonicalTemplateTemplateParm::Profile(
701 llvm::FoldingSetNodeID &ID, const ASTContext &C,
703 ID.AddInteger(Parm->getDepth());
704 ID.AddInteger(Parm->getPosition());
705 ID.AddBoolean(Parm->isParameterPack());
706 ID.AddInteger(Parm->templateParameterKind());
707
709 ID.AddInteger(Params->size());
711 PEnd = Params->end();
712 P != PEnd; ++P) {
713 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
714 ID.AddInteger(0);
715 ID.AddBoolean(TTP->isParameterPack());
716 ID.AddInteger(
717 TTP->getNumExpansionParameters().toInternalRepresentation());
718 continue;
719 }
720
721 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
722 ID.AddInteger(1);
723 ID.AddBoolean(NTTP->isParameterPack());
724 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
725 .getAsOpaquePtr());
726 if (NTTP->isExpandedParameterPack()) {
727 ID.AddBoolean(true);
728 ID.AddInteger(NTTP->getNumExpansionTypes());
729 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
730 QualType T = NTTP->getExpansionType(I);
731 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
732 }
733 } else
734 ID.AddBoolean(false);
735 continue;
736 }
737
738 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
739 ID.AddInteger(2);
740 Profile(ID, C, TTP);
741 }
742}
743
744TemplateTemplateParmDecl *
746 TemplateTemplateParmDecl *TTP) const {
747 // Check if we already have a canonical template template parameter.
748 llvm::FoldingSetNodeID ID;
749 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
750 void *InsertPos = nullptr;
751 CanonicalTemplateTemplateParm *Canonical
752 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
753 if (Canonical)
754 return Canonical->getParam();
755
756 // Build a canonical template parameter list.
758 SmallVector<NamedDecl *, 4> CanonParams;
759 CanonParams.reserve(Params->size());
761 PEnd = Params->end();
762 P != PEnd; ++P) {
763 // Note that, per C++20 [temp.over.link]/6, when determining whether
764 // template-parameters are equivalent, constraints are ignored.
765 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
768 TTP->getDepth(), TTP->getIndex(), nullptr, false,
769 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
770 TTP->getNumExpansionParameters());
771 CanonParams.push_back(NewTTP);
772 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
776 if (NTTP->isExpandedParameterPack()) {
777 SmallVector<QualType, 2> ExpandedTypes;
779 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
780 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
781 ExpandedTInfos.push_back(
782 getTrivialTypeSourceInfo(ExpandedTypes.back()));
783 }
784
788 NTTP->getDepth(),
789 NTTP->getPosition(), nullptr,
790 T,
791 TInfo,
792 ExpandedTypes,
793 ExpandedTInfos);
794 } else {
798 NTTP->getDepth(),
799 NTTP->getPosition(), nullptr,
800 T,
801 NTTP->isParameterPack(),
802 TInfo);
803 }
804 CanonParams.push_back(Param);
805 } else
806 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
808 }
809
812 TTP->getPosition(), TTP->isParameterPack(), nullptr,
814 /*Typename=*/false,
816 CanonParams, SourceLocation(),
817 /*RequiresClause=*/nullptr));
818
819 // Get the new insert position for the node we care about.
820 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
821 assert(!Canonical && "Shouldn't be in the map!");
822 (void)Canonical;
823
824 // Create the canonical template template parameter entry.
825 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
826 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
827 return CanonTTP;
828}
829
832 TemplateTemplateParmDecl *TTP) const {
833 llvm::FoldingSetNodeID ID;
834 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
835 void *InsertPos = nullptr;
836 CanonicalTemplateTemplateParm *Canonical =
837 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
838 return Canonical ? Canonical->getParam() : nullptr;
839}
840
843 TemplateTemplateParmDecl *CanonTTP) const {
844 llvm::FoldingSetNodeID ID;
845 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
846 void *InsertPos = nullptr;
847 if (auto *Existing =
848 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
849 return Existing->getParam();
850 CanonTemplateTemplateParms.InsertNode(
851 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
852 return CanonTTP;
853}
854
855/// Check if a type can have its sanitizer instrumentation elided based on its
856/// presence within an ignorelist.
858 const QualType &Ty) const {
859 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
860 return NoSanitizeL->containsType(Mask, TyName);
861}
862
864 auto Kind = getTargetInfo().getCXXABI().getKind();
865 return getLangOpts().CXXABI.value_or(Kind);
866}
867
868CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
869 if (!LangOpts.CPlusPlus) return nullptr;
870
871 switch (getCXXABIKind()) {
872 case TargetCXXABI::AppleARM64:
873 case TargetCXXABI::Fuchsia:
874 case TargetCXXABI::GenericARM: // Same as Itanium at this level
875 case TargetCXXABI::iOS:
876 case TargetCXXABI::WatchOS:
877 case TargetCXXABI::GenericAArch64:
878 case TargetCXXABI::GenericMIPS:
879 case TargetCXXABI::GenericItanium:
880 case TargetCXXABI::WebAssembly:
881 case TargetCXXABI::XL:
882 return CreateItaniumCXXABI(*this);
883 case TargetCXXABI::Microsoft:
884 return CreateMicrosoftCXXABI(*this);
885 }
886 llvm_unreachable("Invalid CXXABI type!");
887}
888
890 if (!InterpContext) {
891 InterpContext.reset(new interp::Context(*this));
892 }
893 return *InterpContext;
894}
895
897 if (!ParentMapCtx)
898 ParentMapCtx.reset(new ParentMapContext(*this));
899 return *ParentMapCtx;
900}
901
903 const LangOptions &LangOpts) {
904 switch (LangOpts.getAddressSpaceMapMangling()) {
906 return TI.useAddressSpaceMapMangling();
908 return true;
910 return false;
911 }
912 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
913}
914
916 IdentifierTable &idents, SelectorTable &sels,
918 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
919 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
920 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
921 DependentSizedMatrixTypes(this_()),
922 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
923 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
924 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
925 DependentBitIntTypes(this_()), SubstTemplateTemplateParmPacks(this_()),
926 DeducedTemplates(this_()), ArrayParameterTypes(this_()),
927 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
928 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
929 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
930 LangOpts.XRayNeverInstrumentFiles,
931 LangOpts.XRayAttrListFiles, SM)),
932 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
933 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
934 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
935 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
936 CompCategories(this_()), LastSDM(nullptr, 0) {
938}
939
941 // Release the DenseMaps associated with DeclContext objects.
942 // FIXME: Is this the ideal solution?
943 ReleaseDeclContextMaps();
944
945 // Call all of the deallocation functions on all of their targets.
946 for (auto &Pair : Deallocations)
947 (Pair.first)(Pair.second);
948 Deallocations.clear();
949
950 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
951 // because they can contain DenseMaps.
952 for (llvm::DenseMap<const ObjCInterfaceDecl *,
954 I = ObjCLayouts.begin(),
955 E = ObjCLayouts.end();
956 I != E;)
957 // Increment in loop to prevent using deallocated memory.
958 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
959 R->Destroy(*this);
960 ObjCLayouts.clear();
961
962 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
963 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
964 // Increment in loop to prevent using deallocated memory.
965 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
966 R->Destroy(*this);
967 }
968 ASTRecordLayouts.clear();
969
970 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
971 AEnd = DeclAttrs.end();
972 A != AEnd; ++A)
973 A->second->~AttrVec();
974 DeclAttrs.clear();
975
976 for (const auto &Value : ModuleInitializers)
977 Value.second->~PerModuleInitializers();
978 ModuleInitializers.clear();
979}
980
982
983void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
984 TraversalScope = TopLevelDecls;
986}
987
988void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
989 Deallocations.push_back({Callback, Data});
990}
991
992void
996
998 llvm::errs() << "\n*** AST Context Stats:\n";
999 llvm::errs() << " " << Types.size() << " types total.\n";
1000
1001 unsigned counts[] = {
1002#define TYPE(Name, Parent) 0,
1003#define ABSTRACT_TYPE(Name, Parent)
1004#include "clang/AST/TypeNodes.inc"
1005 0 // Extra
1006 };
1007
1008 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1009 Type *T = Types[i];
1010 counts[(unsigned)T->getTypeClass()]++;
1011 }
1012
1013 unsigned Idx = 0;
1014 unsigned TotalBytes = 0;
1015#define TYPE(Name, Parent) \
1016 if (counts[Idx]) \
1017 llvm::errs() << " " << counts[Idx] << " " << #Name \
1018 << " types, " << sizeof(Name##Type) << " each " \
1019 << "(" << counts[Idx] * sizeof(Name##Type) \
1020 << " bytes)\n"; \
1021 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1022 ++Idx;
1023#define ABSTRACT_TYPE(Name, Parent)
1024#include "clang/AST/TypeNodes.inc"
1025
1026 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1027
1028 // Implicit special member functions.
1029 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1031 << " implicit default constructors created\n";
1032 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1034 << " implicit copy constructors created\n";
1035 if (getLangOpts().CPlusPlus)
1036 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1038 << " implicit move constructors created\n";
1039 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1041 << " implicit copy assignment operators created\n";
1042 if (getLangOpts().CPlusPlus)
1043 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1045 << " implicit move assignment operators created\n";
1046 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1048 << " implicit destructors created\n";
1049
1050 if (ExternalSource) {
1051 llvm::errs() << "\n";
1052 ExternalSource->PrintStats();
1053 }
1054
1055 BumpAlloc.PrintStats();
1056}
1057
1059 bool NotifyListeners) {
1060 if (NotifyListeners)
1061 if (auto *Listener = getASTMutationListener();
1063 Listener->RedefinedHiddenDefinition(ND, M);
1064
1065 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1066}
1067
1069 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1070 if (It == MergedDefModules.end())
1071 return;
1072
1073 auto &Merged = It->second;
1074 llvm::DenseSet<Module*> Found;
1075 for (Module *&M : Merged)
1076 if (!Found.insert(M).second)
1077 M = nullptr;
1078 llvm::erase(Merged, nullptr);
1079}
1080
1083 auto MergedIt =
1084 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1085 if (MergedIt == MergedDefModules.end())
1086 return {};
1087 return MergedIt->second;
1088}
1089
1090void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1091 if (LazyInitializers.empty())
1092 return;
1093
1094 auto *Source = Ctx.getExternalSource();
1095 assert(Source && "lazy initializers but no external source");
1096
1097 auto LazyInits = std::move(LazyInitializers);
1098 LazyInitializers.clear();
1099
1100 for (auto ID : LazyInits)
1101 Initializers.push_back(Source->GetExternalDecl(ID));
1102
1103 assert(LazyInitializers.empty() &&
1104 "GetExternalDecl for lazy module initializer added more inits");
1105}
1106
1108 // One special case: if we add a module initializer that imports another
1109 // module, and that module's only initializer is an ImportDecl, simplify.
1110 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1111 auto It = ModuleInitializers.find(ID->getImportedModule());
1112
1113 // Maybe the ImportDecl does nothing at all. (Common case.)
1114 if (It == ModuleInitializers.end())
1115 return;
1116
1117 // Maybe the ImportDecl only imports another ImportDecl.
1118 auto &Imported = *It->second;
1119 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1120 Imported.resolve(*this);
1121 auto *OnlyDecl = Imported.Initializers.front();
1122 if (isa<ImportDecl>(OnlyDecl))
1123 D = OnlyDecl;
1124 }
1125 }
1126
1127 auto *&Inits = ModuleInitializers[M];
1128 if (!Inits)
1129 Inits = new (*this) PerModuleInitializers;
1130 Inits->Initializers.push_back(D);
1131}
1132
1135 auto *&Inits = ModuleInitializers[M];
1136 if (!Inits)
1137 Inits = new (*this) PerModuleInitializers;
1138 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1139 IDs.begin(), IDs.end());
1140}
1141
1143 auto It = ModuleInitializers.find(M);
1144 if (It == ModuleInitializers.end())
1145 return {};
1146
1147 auto *Inits = It->second;
1148 Inits->resolve(*this);
1149 return Inits->Initializers;
1150}
1151
1153 assert(M->isNamedModule());
1154 assert(!CurrentCXXNamedModule &&
1155 "We should set named module for ASTContext for only once");
1156 CurrentCXXNamedModule = M;
1157}
1158
1159bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1160 if (!M1 != !M2)
1161 return false;
1162
1163 /// Get the representative module for M. The representative module is the
1164 /// first module unit for a specific primary module name. So that the module
1165 /// units have the same representative module belongs to the same module.
1166 ///
1167 /// The process is helpful to reduce the expensive string operations.
1168 auto GetRepresentativeModule = [this](const Module *M) {
1169 auto Iter = SameModuleLookupSet.find(M);
1170 if (Iter != SameModuleLookupSet.end())
1171 return Iter->second;
1172
1173 const Module *RepresentativeModule =
1174 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1175 .first->second;
1176 SameModuleLookupSet[M] = RepresentativeModule;
1177 return RepresentativeModule;
1178 };
1179
1180 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1181 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1182}
1183
1185 if (!ExternCContext)
1186 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1187
1188 return ExternCContext;
1189}
1190
1201
1202#define BuiltinTemplate(BTName) \
1203 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1204 if (!Decl##BTName) \
1205 Decl##BTName = \
1206 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1207 return Decl##BTName; \
1208 }
1209#include "clang/Basic/BuiltinTemplates.inc"
1210
1212 RecordDecl::TagKind TK) const {
1213 SourceLocation Loc;
1214 RecordDecl *NewDecl;
1215 if (getLangOpts().CPlusPlus)
1216 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217 Loc, &Idents.get(Name));
1218 else
1219 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1220 &Idents.get(Name));
1221 NewDecl->setImplicit();
1222 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1224 return NewDecl;
1225}
1226
1228 StringRef Name) const {
1231 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233 NewDecl->setImplicit();
1234 return NewDecl;
1235}
1236
1238 if (!Int128Decl)
1239 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1240 return Int128Decl;
1241}
1242
1244 if (!UInt128Decl)
1245 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1246 return UInt128Decl;
1247}
1248
1249void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1252 Types.push_back(Ty);
1253}
1254
1256 const TargetInfo *AuxTarget) {
1257 assert((!this->Target || this->Target == &Target) &&
1258 "Incorrect target reinitialization");
1259 assert(VoidTy.isNull() && "Context reinitialized?");
1260
1261 this->Target = &Target;
1262 this->AuxTarget = AuxTarget;
1263
1264 ABI.reset(createCXXABI(Target));
1265 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1266
1267 // C99 6.2.5p19.
1268 InitBuiltinType(VoidTy, BuiltinType::Void);
1269
1270 // C99 6.2.5p2.
1271 InitBuiltinType(BoolTy, BuiltinType::Bool);
1272 // C99 6.2.5p3.
1273 if (LangOpts.CharIsSigned)
1274 InitBuiltinType(CharTy, BuiltinType::Char_S);
1275 else
1276 InitBuiltinType(CharTy, BuiltinType::Char_U);
1277 // C99 6.2.5p4.
1278 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1279 InitBuiltinType(ShortTy, BuiltinType::Short);
1280 InitBuiltinType(IntTy, BuiltinType::Int);
1281 InitBuiltinType(LongTy, BuiltinType::Long);
1282 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1283
1284 // C99 6.2.5p6.
1285 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1286 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1287 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1288 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1289 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1290
1291 // C99 6.2.5p10.
1292 InitBuiltinType(FloatTy, BuiltinType::Float);
1293 InitBuiltinType(DoubleTy, BuiltinType::Double);
1294 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1295
1296 // GNU extension, __float128 for IEEE quadruple precision
1297 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1298
1299 // __ibm128 for IBM extended precision
1300 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1301
1302 // C11 extension ISO/IEC TS 18661-3
1303 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1304
1305 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1306 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1307 InitBuiltinType(AccumTy, BuiltinType::Accum);
1308 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1309 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1310 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1311 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1312 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1313 InitBuiltinType(FractTy, BuiltinType::Fract);
1314 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1315 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1316 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1317 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1318 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1319 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1320 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1321 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1322 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1323 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1324 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1325 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1326 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1327 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1328 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1329 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1330
1331 // GNU extension, 128-bit integers.
1332 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1333 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1334
1335 // C++ 3.9.1p5
1336 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1337 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1338 else // -fshort-wchar makes wchar_t be unsigned.
1339 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1340 if (LangOpts.CPlusPlus && LangOpts.WChar)
1342 else {
1343 // C99 (or C++ using -fno-wchar).
1344 WideCharTy = getFromTargetType(Target.getWCharType());
1345 }
1346
1347 WIntTy = getFromTargetType(Target.getWIntType());
1348
1349 // C++20 (proposed)
1350 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1351
1352 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1353 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1354 else // C99
1355 Char16Ty = getFromTargetType(Target.getChar16Type());
1356
1357 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1358 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1359 else // C99
1360 Char32Ty = getFromTargetType(Target.getChar32Type());
1361
1362 // Placeholder type for type-dependent expressions whose type is
1363 // completely unknown. No code should ever check a type against
1364 // DependentTy and users should never see it; however, it is here to
1365 // help diagnose failures to properly check for type-dependent
1366 // expressions.
1367 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1368
1369 // Placeholder type for functions.
1370 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1371
1372 // Placeholder type for bound members.
1373 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1374
1375 // Placeholder type for unresolved templates.
1376 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1377
1378 // Placeholder type for pseudo-objects.
1379 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1380
1381 // "any" type; useful for debugger-like clients.
1382 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1383
1384 // Placeholder type for unbridged ARC casts.
1385 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1386
1387 // Placeholder type for builtin functions.
1388 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1389
1390 // Placeholder type for OMP array sections.
1391 if (LangOpts.OpenMP) {
1392 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1393 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1394 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1395 }
1396 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1397 // don't bother, as we're just using the same type as OMP.
1398 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1399 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1400 }
1401 if (LangOpts.MatrixTypes)
1402 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1403
1404 // Builtin types for 'id', 'Class', and 'SEL'.
1405 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1406 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1407 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1408
1409 if (LangOpts.OpenCL) {
1410#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1411 InitBuiltinType(SingletonId, BuiltinType::Id);
1412#include "clang/Basic/OpenCLImageTypes.def"
1413
1414 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1415 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1416 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1417 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1418 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1419
1420#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1421 InitBuiltinType(Id##Ty, BuiltinType::Id);
1422#include "clang/Basic/OpenCLExtensionTypes.def"
1423 }
1424
1425 if (LangOpts.HLSL) {
1426#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1427 InitBuiltinType(SingletonId, BuiltinType::Id);
1428#include "clang/Basic/HLSLIntangibleTypes.def"
1429 }
1430
1431 if (Target.hasAArch64ACLETypes() ||
1432 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1433#define SVE_TYPE(Name, Id, SingletonId) \
1434 InitBuiltinType(SingletonId, BuiltinType::Id);
1435#include "clang/Basic/AArch64ACLETypes.def"
1436 }
1437
1438 if (Target.getTriple().isPPC64()) {
1439#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1440 InitBuiltinType(Id##Ty, BuiltinType::Id);
1441#include "clang/Basic/PPCTypes.def"
1442#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/PPCTypes.def"
1445 }
1446
1447 if (Target.hasRISCVVTypes()) {
1448#define RVV_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/RISCVVTypes.def"
1451 }
1452
1453 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1454#define WASM_TYPE(Name, Id, SingletonId) \
1455 InitBuiltinType(SingletonId, BuiltinType::Id);
1456#include "clang/Basic/WebAssemblyReferenceTypes.def"
1457 }
1458
1459 if (Target.getTriple().isAMDGPU() ||
1460 (AuxTarget && AuxTarget->getTriple().isAMDGPU())) {
1461#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1462 InitBuiltinType(SingletonId, BuiltinType::Id);
1463#include "clang/Basic/AMDGPUTypes.def"
1464 }
1465
1466 // Builtin type for __objc_yes and __objc_no
1467 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1469
1470 ObjCConstantStringType = QualType();
1471
1472 ObjCSuperType = QualType();
1473
1474 // void * type
1475 if (LangOpts.OpenCLGenericAddressSpace) {
1476 auto Q = VoidTy.getQualifiers();
1477 Q.setAddressSpace(LangAS::opencl_generic);
1479 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1480 } else {
1482 }
1483
1484 // nullptr type (C++0x 2.14.7)
1485 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1486
1487 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1488 InitBuiltinType(HalfTy, BuiltinType::Half);
1489
1490 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1491
1492 // Builtin type used to help define __builtin_va_list.
1493 VaListTagDecl = nullptr;
1494
1495 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1496 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1499 }
1500}
1501
1503 return SourceMgr.getDiagnostics();
1504}
1505
1507 AttrVec *&Result = DeclAttrs[D];
1508 if (!Result) {
1509 void *Mem = Allocate(sizeof(AttrVec));
1510 Result = new (Mem) AttrVec;
1511 }
1512
1513 return *Result;
1514}
1515
1516/// Erase the attributes corresponding to the given declaration.
1518 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1519 if (Pos != DeclAttrs.end()) {
1520 Pos->second->~AttrVec();
1521 DeclAttrs.erase(Pos);
1522 }
1523}
1524
1525// FIXME: Remove ?
1528 assert(Var->isStaticDataMember() && "Not a static data member");
1530 .dyn_cast<MemberSpecializationInfo *>();
1531}
1532
1535 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1536 TemplateOrInstantiation.find(Var);
1537 if (Pos == TemplateOrInstantiation.end())
1538 return {};
1539
1540 return Pos->second;
1541}
1542
1543void
1546 SourceLocation PointOfInstantiation) {
1547 assert(Inst->isStaticDataMember() && "Not a static data member");
1548 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1550 Tmpl, TSK, PointOfInstantiation));
1551}
1552
1553void
1556 assert(!TemplateOrInstantiation[Inst] &&
1557 "Already noted what the variable was instantiated from");
1558 TemplateOrInstantiation[Inst] = TSI;
1559}
1560
1561NamedDecl *
1563 return InstantiatedFromUsingDecl.lookup(UUD);
1564}
1565
1566void
1568 assert((isa<UsingDecl>(Pattern) ||
1571 "pattern decl is not a using decl");
1572 assert((isa<UsingDecl>(Inst) ||
1575 "instantiation did not produce a using decl");
1576 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1577 InstantiatedFromUsingDecl[Inst] = Pattern;
1578}
1579
1582 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1583}
1584
1586 UsingEnumDecl *Pattern) {
1587 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1588 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1589}
1590
1593 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1594}
1595
1596void
1598 UsingShadowDecl *Pattern) {
1599 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1600 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1601}
1602
1603FieldDecl *
1605 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1606}
1607
1609 FieldDecl *Tmpl) {
1610 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1611 "Instantiated field decl is not unnamed");
1612 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1613 "Template field decl is not unnamed");
1614 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1615 "Already noted what unnamed field was instantiated from");
1616
1617 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1618}
1619
1624
1629
1630unsigned
1632 auto Range = overridden_methods(Method);
1633 return Range.end() - Range.begin();
1634}
1635
1638 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1639 OverriddenMethods.find(Method->getCanonicalDecl());
1640 if (Pos == OverriddenMethods.end())
1641 return overridden_method_range(nullptr, nullptr);
1642 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1643}
1644
1646 const CXXMethodDecl *Overridden) {
1647 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1648 OverriddenMethods[Method].push_back(Overridden);
1649}
1650
1652 const NamedDecl *D,
1653 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1654 assert(D);
1655
1656 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1657 Overridden.append(overridden_methods_begin(CXXMethod),
1658 overridden_methods_end(CXXMethod));
1659 return;
1660 }
1661
1662 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1663 if (!Method)
1664 return;
1665
1667 Method->getOverriddenMethods(OverDecls);
1668 Overridden.append(OverDecls.begin(), OverDecls.end());
1669}
1670
1671std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1673 assert(RD);
1674 CXXRecordDecl *D = RD->getDefinition();
1675 auto it = RelocatableClasses.find(D);
1676 if (it != RelocatableClasses.end())
1677 return it->getSecond();
1678 return std::nullopt;
1679}
1680
1683 assert(RD);
1684 CXXRecordDecl *D = RD->getDefinition();
1685 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1686 RelocatableClasses.insert({D, Info});
1687}
1688
1690 const ASTContext &Context, const CXXRecordDecl *Class) {
1691 if (!Class->isPolymorphic())
1692 return false;
1693 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1694 using AuthAttr = VTablePointerAuthenticationAttr;
1695 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1696 if (!ExplicitAuth)
1697 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1698 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1699 ExplicitAuth->getAddressDiscrimination();
1700 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1701 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1702 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1703}
1704
1705ASTContext::PointerAuthContent
1706ASTContext::findPointerAuthContent(QualType T) const {
1707 assert(isPointerAuthenticationAvailable());
1708
1709 T = T.getCanonicalType();
1710 if (T->isDependentType())
1711 return PointerAuthContent::None;
1712
1713 if (T.hasAddressDiscriminatedPointerAuth())
1714 return PointerAuthContent::AddressDiscriminatedData;
1715 const RecordDecl *RD = T->getAsRecordDecl();
1716 if (!RD)
1717 return PointerAuthContent::None;
1718
1719 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1720 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1721 return Existing->second;
1722
1723 PointerAuthContent Result = PointerAuthContent::None;
1724
1725 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1726 auto [ResultIter, DidAdd] =
1727 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1728 (void)ResultIter;
1729 (void)DidAdd;
1730 assert(DidAdd);
1731 return Result;
1732 };
1733 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1734 static_assert(PointerAuthContent::None <
1735 PointerAuthContent::AddressDiscriminatedVTable);
1736 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1737 PointerAuthContent::AddressDiscriminatedData);
1738 if (NewResult > Result)
1739 Result = NewResult;
1740 return Result != PointerAuthContent::AddressDiscriminatedData;
1741 };
1742 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1744 !ShouldContinueAfterUpdate(
1745 PointerAuthContent::AddressDiscriminatedVTable))
1746 return SaveResultAndReturn();
1747 for (auto Base : CXXRD->bases()) {
1748 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1749 return SaveResultAndReturn();
1750 }
1751 }
1752 for (auto *FieldDecl : RD->fields()) {
1753 if (!ShouldContinueAfterUpdate(
1754 findPointerAuthContent(FieldDecl->getType())))
1755 return SaveResultAndReturn();
1756 }
1757 return SaveResultAndReturn();
1758}
1759
1761 assert(!Import->getNextLocalImport() &&
1762 "Import declaration already in the chain");
1763 assert(!Import->isFromASTFile() && "Non-local import declaration");
1764 if (!FirstLocalImport) {
1765 FirstLocalImport = Import;
1766 LastLocalImport = Import;
1767 return;
1768 }
1769
1770 LastLocalImport->setNextLocalImport(Import);
1771 LastLocalImport = Import;
1772}
1773
1774//===----------------------------------------------------------------------===//
1775// Type Sizing and Analysis
1776//===----------------------------------------------------------------------===//
1777
1778/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1779/// scalar floating point type.
1780const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1781 switch (T->castAs<BuiltinType>()->getKind()) {
1782 default:
1783 llvm_unreachable("Not a floating point type!");
1784 case BuiltinType::BFloat16:
1785 return Target->getBFloat16Format();
1786 case BuiltinType::Float16:
1787 return Target->getHalfFormat();
1788 case BuiltinType::Half:
1789 return Target->getHalfFormat();
1790 case BuiltinType::Float: return Target->getFloatFormat();
1791 case BuiltinType::Double: return Target->getDoubleFormat();
1792 case BuiltinType::Ibm128:
1793 return Target->getIbm128Format();
1794 case BuiltinType::LongDouble:
1795 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1796 return AuxTarget->getLongDoubleFormat();
1797 return Target->getLongDoubleFormat();
1798 case BuiltinType::Float128:
1799 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1800 return AuxTarget->getFloat128Format();
1801 return Target->getFloat128Format();
1802 }
1803}
1804
1805CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1806 unsigned Align = Target->getCharWidth();
1807
1808 const unsigned AlignFromAttr = D->getMaxAlignment();
1809 if (AlignFromAttr)
1810 Align = AlignFromAttr;
1811
1812 // __attribute__((aligned)) can increase or decrease alignment
1813 // *except* on a struct or struct member, where it only increases
1814 // alignment unless 'packed' is also specified.
1815 //
1816 // It is an error for alignas to decrease alignment, so we can
1817 // ignore that possibility; Sema should diagnose it.
1818 bool UseAlignAttrOnly;
1819 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1820 UseAlignAttrOnly =
1821 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1822 else
1823 UseAlignAttrOnly = AlignFromAttr != 0;
1824 // If we're using the align attribute only, just ignore everything
1825 // else about the declaration and its type.
1826 if (UseAlignAttrOnly) {
1827 // do nothing
1828 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1829 QualType T = VD->getType();
1830 if (const auto *RT = T->getAs<ReferenceType>()) {
1831 if (ForAlignof)
1832 T = RT->getPointeeType();
1833 else
1834 T = getPointerType(RT->getPointeeType());
1835 }
1836 QualType BaseT = getBaseElementType(T);
1837 if (T->isFunctionType())
1838 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1839 else if (!BaseT->isIncompleteType()) {
1840 // Adjust alignments of declarations with array type by the
1841 // large-array alignment on the target.
1842 if (const ArrayType *arrayType = getAsArrayType(T)) {
1843 unsigned MinWidth = Target->getLargeArrayMinWidth();
1844 if (!ForAlignof && MinWidth) {
1846 Align = std::max(Align, Target->getLargeArrayAlign());
1849 Align = std::max(Align, Target->getLargeArrayAlign());
1850 }
1851 }
1852 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1853 if (BaseT.getQualifiers().hasUnaligned())
1854 Align = Target->getCharWidth();
1855 }
1856
1857 // Ensure minimum alignment for global variables.
1858 if (const auto *VD = dyn_cast<VarDecl>(D))
1859 if (VD->hasGlobalStorage() && !ForAlignof) {
1860 uint64_t TypeSize =
1861 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1862 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1863 }
1864
1865 // Fields can be subject to extra alignment constraints, like if
1866 // the field is packed, the struct is packed, or the struct has a
1867 // a max-field-alignment constraint (#pragma pack). So calculate
1868 // the actual alignment of the field within the struct, and then
1869 // (as we're expected to) constrain that by the alignment of the type.
1870 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1871 const RecordDecl *Parent = Field->getParent();
1872 // We can only produce a sensible answer if the record is valid.
1873 if (!Parent->isInvalidDecl()) {
1874 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1875
1876 // Start with the record's overall alignment.
1877 unsigned FieldAlign = toBits(Layout.getAlignment());
1878
1879 // Use the GCD of that and the offset within the record.
1880 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1881 if (Offset > 0) {
1882 // Alignment is always a power of 2, so the GCD will be a power of 2,
1883 // which means we get to do this crazy thing instead of Euclid's.
1884 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1885 if (LowBitOfOffset < FieldAlign)
1886 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1887 }
1888
1889 Align = std::min(Align, FieldAlign);
1890 }
1891 }
1892 }
1893
1894 // Some targets have hard limitation on the maximum requestable alignment in
1895 // aligned attribute for static variables.
1896 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1897 const auto *VD = dyn_cast<VarDecl>(D);
1898 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1899 Align = std::min(Align, MaxAlignedAttr);
1900
1901 return toCharUnitsFromBits(Align);
1902}
1903
1905 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1906}
1907
1908// getTypeInfoDataSizeInChars - Return the size of a type, in
1909// chars. If the type is a record, its data size is returned. This is
1910// the size of the memcpy that's performed when assigning this type
1911// using a trivial copy/move assignment operator.
1914
1915 // In C++, objects can sometimes be allocated into the tail padding
1916 // of a base-class subobject. We decide whether that's possible
1917 // during class layout, so here we can just trust the layout results.
1918 if (getLangOpts().CPlusPlus) {
1919 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1920 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1921 Info.Width = layout.getDataSize();
1922 }
1923 }
1924
1925 return Info;
1926}
1927
1928/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1929/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1932 const ConstantArrayType *CAT) {
1933 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1934 uint64_t Size = CAT->getZExtSize();
1935 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1936 (uint64_t)(-1)/Size) &&
1937 "Overflow in array type char size evaluation");
1938 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1939 unsigned Align = EltInfo.Align.getQuantity();
1940 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1941 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1942 Width = llvm::alignTo(Width, Align);
1945 EltInfo.AlignRequirement);
1946}
1947
1949 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1950 return getConstantArrayInfoInChars(*this, CAT);
1951 TypeInfo Info = getTypeInfo(T);
1954}
1955
1959
1961 // HLSL doesn't promote all small integer types to int, it
1962 // just uses the rank-based promotion rules for all types.
1963 if (getLangOpts().HLSL)
1964 return false;
1965
1966 if (const auto *BT = T->getAs<BuiltinType>())
1967 switch (BT->getKind()) {
1968 case BuiltinType::Bool:
1969 case BuiltinType::Char_S:
1970 case BuiltinType::Char_U:
1971 case BuiltinType::SChar:
1972 case BuiltinType::UChar:
1973 case BuiltinType::Short:
1974 case BuiltinType::UShort:
1975 case BuiltinType::WChar_S:
1976 case BuiltinType::WChar_U:
1977 case BuiltinType::Char8:
1978 case BuiltinType::Char16:
1979 case BuiltinType::Char32:
1980 return true;
1981 default:
1982 return false;
1983 }
1984
1985 // Enumerated types are promotable to their compatible integer types
1986 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1987 if (const auto *ED = T->getAsEnumDecl()) {
1988 if (T->isDependentType() || ED->getPromotionType().isNull() ||
1989 ED->isScoped())
1990 return false;
1991
1992 return true;
1993 }
1994
1995 return false;
1996}
1997
2001
2003 return isAlignmentRequired(T.getTypePtr());
2004}
2005
2007 bool NeedsPreferredAlignment) const {
2008 // An alignment on a typedef overrides anything else.
2009 if (const auto *TT = T->getAs<TypedefType>())
2010 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2011 return Align;
2012
2013 // If we have an (array of) complete type, we're done.
2015 if (!T->isIncompleteType())
2016 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2017
2018 // If we had an array type, its element type might be a typedef
2019 // type with an alignment attribute.
2020 if (const auto *TT = T->getAs<TypedefType>())
2021 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2022 return Align;
2023
2024 // Otherwise, see if the declaration of the type had an attribute.
2025 if (const auto *TD = T->getAsTagDecl())
2026 return TD->getMaxAlignment();
2027
2028 return 0;
2029}
2030
2032 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2033 if (I != MemoizedTypeInfo.end())
2034 return I->second;
2035
2036 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2037 TypeInfo TI = getTypeInfoImpl(T);
2038 MemoizedTypeInfo[T] = TI;
2039 return TI;
2040}
2041
2042/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2043/// method does not work on incomplete types.
2044///
2045/// FIXME: Pointers into different addr spaces could have different sizes and
2046/// alignment requirements: getPointerInfo should take an AddrSpace, this
2047/// should take a QualType, &c.
2048TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2049 uint64_t Width = 0;
2050 unsigned Align = 8;
2053 switch (T->getTypeClass()) {
2054#define TYPE(Class, Base)
2055#define ABSTRACT_TYPE(Class, Base)
2056#define NON_CANONICAL_TYPE(Class, Base)
2057#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2058#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2059 case Type::Class: \
2060 assert(!T->isDependentType() && "should not see dependent types here"); \
2061 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2062#include "clang/AST/TypeNodes.inc"
2063 llvm_unreachable("Should not see dependent types");
2064
2065 case Type::FunctionNoProto:
2066 case Type::FunctionProto:
2067 // GCC extension: alignof(function) = 32 bits
2068 Width = 0;
2069 Align = 32;
2070 break;
2071
2072 case Type::IncompleteArray:
2073 case Type::VariableArray:
2074 case Type::ConstantArray:
2075 case Type::ArrayParameter: {
2076 // Model non-constant sized arrays as size zero, but track the alignment.
2077 uint64_t Size = 0;
2078 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2079 Size = CAT->getZExtSize();
2080
2081 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2082 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2083 "Overflow in array type bit size evaluation");
2084 Width = EltInfo.Width * Size;
2085 Align = EltInfo.Align;
2086 AlignRequirement = EltInfo.AlignRequirement;
2087 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2088 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2089 Width = llvm::alignTo(Width, Align);
2090 break;
2091 }
2092
2093 case Type::ExtVector:
2094 case Type::Vector: {
2095 const auto *VT = cast<VectorType>(T);
2096 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2097 Width = VT->isPackedVectorBoolType(*this)
2098 ? VT->getNumElements()
2099 : EltInfo.Width * VT->getNumElements();
2100 // Enforce at least byte size and alignment.
2101 Width = std::max<unsigned>(8, Width);
2102 Align = std::max<unsigned>(8, Width);
2103
2104 // If the alignment is not a power of 2, round up to the next power of 2.
2105 // This happens for non-power-of-2 length vectors.
2106 if (Align & (Align-1)) {
2107 Align = llvm::bit_ceil(Align);
2108 Width = llvm::alignTo(Width, Align);
2109 }
2110 // Adjust the alignment based on the target max.
2111 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2112 if (TargetVectorAlign && TargetVectorAlign < Align)
2113 Align = TargetVectorAlign;
2114 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2115 // Adjust the alignment for fixed-length SVE vectors. This is important
2116 // for non-power-of-2 vector lengths.
2117 Align = 128;
2118 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2119 // Adjust the alignment for fixed-length SVE predicates.
2120 Align = 16;
2121 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2122 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2123 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2124 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2125 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2126 // Adjust the alignment for fixed-length RVV vectors.
2127 Align = std::min<unsigned>(64, Width);
2128 break;
2129 }
2130
2131 case Type::ConstantMatrix: {
2132 const auto *MT = cast<ConstantMatrixType>(T);
2133 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2134 // The internal layout of a matrix value is implementation defined.
2135 // Initially be ABI compatible with arrays with respect to alignment and
2136 // size.
2137 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2138 Align = ElementInfo.Align;
2139 break;
2140 }
2141
2142 case Type::Builtin:
2143 switch (cast<BuiltinType>(T)->getKind()) {
2144 default: llvm_unreachable("Unknown builtin type!");
2145 case BuiltinType::Void:
2146 // GCC extension: alignof(void) = 8 bits.
2147 Width = 0;
2148 Align = 8;
2149 break;
2150 case BuiltinType::Bool:
2151 Width = Target->getBoolWidth();
2152 Align = Target->getBoolAlign();
2153 break;
2154 case BuiltinType::Char_S:
2155 case BuiltinType::Char_U:
2156 case BuiltinType::UChar:
2157 case BuiltinType::SChar:
2158 case BuiltinType::Char8:
2159 Width = Target->getCharWidth();
2160 Align = Target->getCharAlign();
2161 break;
2162 case BuiltinType::WChar_S:
2163 case BuiltinType::WChar_U:
2164 Width = Target->getWCharWidth();
2165 Align = Target->getWCharAlign();
2166 break;
2167 case BuiltinType::Char16:
2168 Width = Target->getChar16Width();
2169 Align = Target->getChar16Align();
2170 break;
2171 case BuiltinType::Char32:
2172 Width = Target->getChar32Width();
2173 Align = Target->getChar32Align();
2174 break;
2175 case BuiltinType::UShort:
2176 case BuiltinType::Short:
2177 Width = Target->getShortWidth();
2178 Align = Target->getShortAlign();
2179 break;
2180 case BuiltinType::UInt:
2181 case BuiltinType::Int:
2182 Width = Target->getIntWidth();
2183 Align = Target->getIntAlign();
2184 break;
2185 case BuiltinType::ULong:
2186 case BuiltinType::Long:
2187 Width = Target->getLongWidth();
2188 Align = Target->getLongAlign();
2189 break;
2190 case BuiltinType::ULongLong:
2191 case BuiltinType::LongLong:
2192 Width = Target->getLongLongWidth();
2193 Align = Target->getLongLongAlign();
2194 break;
2195 case BuiltinType::Int128:
2196 case BuiltinType::UInt128:
2197 Width = 128;
2198 Align = Target->getInt128Align();
2199 break;
2200 case BuiltinType::ShortAccum:
2201 case BuiltinType::UShortAccum:
2202 case BuiltinType::SatShortAccum:
2203 case BuiltinType::SatUShortAccum:
2204 Width = Target->getShortAccumWidth();
2205 Align = Target->getShortAccumAlign();
2206 break;
2207 case BuiltinType::Accum:
2208 case BuiltinType::UAccum:
2209 case BuiltinType::SatAccum:
2210 case BuiltinType::SatUAccum:
2211 Width = Target->getAccumWidth();
2212 Align = Target->getAccumAlign();
2213 break;
2214 case BuiltinType::LongAccum:
2215 case BuiltinType::ULongAccum:
2216 case BuiltinType::SatLongAccum:
2217 case BuiltinType::SatULongAccum:
2218 Width = Target->getLongAccumWidth();
2219 Align = Target->getLongAccumAlign();
2220 break;
2221 case BuiltinType::ShortFract:
2222 case BuiltinType::UShortFract:
2223 case BuiltinType::SatShortFract:
2224 case BuiltinType::SatUShortFract:
2225 Width = Target->getShortFractWidth();
2226 Align = Target->getShortFractAlign();
2227 break;
2228 case BuiltinType::Fract:
2229 case BuiltinType::UFract:
2230 case BuiltinType::SatFract:
2231 case BuiltinType::SatUFract:
2232 Width = Target->getFractWidth();
2233 Align = Target->getFractAlign();
2234 break;
2235 case BuiltinType::LongFract:
2236 case BuiltinType::ULongFract:
2237 case BuiltinType::SatLongFract:
2238 case BuiltinType::SatULongFract:
2239 Width = Target->getLongFractWidth();
2240 Align = Target->getLongFractAlign();
2241 break;
2242 case BuiltinType::BFloat16:
2243 if (Target->hasBFloat16Type()) {
2244 Width = Target->getBFloat16Width();
2245 Align = Target->getBFloat16Align();
2246 } else if ((getLangOpts().SYCLIsDevice ||
2247 (getLangOpts().OpenMP &&
2248 getLangOpts().OpenMPIsTargetDevice)) &&
2249 AuxTarget->hasBFloat16Type()) {
2250 Width = AuxTarget->getBFloat16Width();
2251 Align = AuxTarget->getBFloat16Align();
2252 }
2253 break;
2254 case BuiltinType::Float16:
2255 case BuiltinType::Half:
2256 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2257 !getLangOpts().OpenMPIsTargetDevice) {
2258 Width = Target->getHalfWidth();
2259 Align = Target->getHalfAlign();
2260 } else {
2261 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2262 "Expected OpenMP device compilation.");
2263 Width = AuxTarget->getHalfWidth();
2264 Align = AuxTarget->getHalfAlign();
2265 }
2266 break;
2267 case BuiltinType::Float:
2268 Width = Target->getFloatWidth();
2269 Align = Target->getFloatAlign();
2270 break;
2271 case BuiltinType::Double:
2272 Width = Target->getDoubleWidth();
2273 Align = Target->getDoubleAlign();
2274 break;
2275 case BuiltinType::Ibm128:
2276 Width = Target->getIbm128Width();
2277 Align = Target->getIbm128Align();
2278 break;
2279 case BuiltinType::LongDouble:
2280 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2281 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2282 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2283 Width = AuxTarget->getLongDoubleWidth();
2284 Align = AuxTarget->getLongDoubleAlign();
2285 } else {
2286 Width = Target->getLongDoubleWidth();
2287 Align = Target->getLongDoubleAlign();
2288 }
2289 break;
2290 case BuiltinType::Float128:
2291 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2292 !getLangOpts().OpenMPIsTargetDevice) {
2293 Width = Target->getFloat128Width();
2294 Align = Target->getFloat128Align();
2295 } else {
2296 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2297 "Expected OpenMP device compilation.");
2298 Width = AuxTarget->getFloat128Width();
2299 Align = AuxTarget->getFloat128Align();
2300 }
2301 break;
2302 case BuiltinType::NullPtr:
2303 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2304 Width = Target->getPointerWidth(LangAS::Default);
2305 Align = Target->getPointerAlign(LangAS::Default);
2306 break;
2307 case BuiltinType::ObjCId:
2308 case BuiltinType::ObjCClass:
2309 case BuiltinType::ObjCSel:
2310 Width = Target->getPointerWidth(LangAS::Default);
2311 Align = Target->getPointerAlign(LangAS::Default);
2312 break;
2313 case BuiltinType::OCLSampler:
2314 case BuiltinType::OCLEvent:
2315 case BuiltinType::OCLClkEvent:
2316 case BuiltinType::OCLQueue:
2317 case BuiltinType::OCLReserveID:
2318#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2319 case BuiltinType::Id:
2320#include "clang/Basic/OpenCLImageTypes.def"
2321#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2322 case BuiltinType::Id:
2323#include "clang/Basic/OpenCLExtensionTypes.def"
2324 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2325 Width = Target->getPointerWidth(AS);
2326 Align = Target->getPointerAlign(AS);
2327 break;
2328 // The SVE types are effectively target-specific. The length of an
2329 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2330 // of 128 bits. There is one predicate bit for each vector byte, so the
2331 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2332 //
2333 // Because the length is only known at runtime, we use a dummy value
2334 // of 0 for the static length. The alignment values are those defined
2335 // by the Procedure Call Standard for the Arm Architecture.
2336#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2337 case BuiltinType::Id: \
2338 Width = 0; \
2339 Align = 128; \
2340 break;
2341#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2342 case BuiltinType::Id: \
2343 Width = 0; \
2344 Align = 16; \
2345 break;
2346#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2347 case BuiltinType::Id: \
2348 Width = 0; \
2349 Align = 16; \
2350 break;
2351#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2352 case BuiltinType::Id: \
2353 Width = Bits; \
2354 Align = Bits; \
2355 break;
2356#include "clang/Basic/AArch64ACLETypes.def"
2357#define PPC_VECTOR_TYPE(Name, Id, Size) \
2358 case BuiltinType::Id: \
2359 Width = Size; \
2360 Align = Size; \
2361 break;
2362#include "clang/Basic/PPCTypes.def"
2363#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2364 IsFP, IsBF) \
2365 case BuiltinType::Id: \
2366 Width = 0; \
2367 Align = ElBits; \
2368 break;
2369#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2370 case BuiltinType::Id: \
2371 Width = 0; \
2372 Align = 8; \
2373 break;
2374#include "clang/Basic/RISCVVTypes.def"
2375#define WASM_TYPE(Name, Id, SingletonId) \
2376 case BuiltinType::Id: \
2377 Width = 0; \
2378 Align = 8; \
2379 break;
2380#include "clang/Basic/WebAssemblyReferenceTypes.def"
2381#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2382 case BuiltinType::ID: \
2383 Width = WIDTH; \
2384 Align = ALIGN; \
2385 break;
2386#include "clang/Basic/AMDGPUTypes.def"
2387#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2388#include "clang/Basic/HLSLIntangibleTypes.def"
2389 Width = Target->getPointerWidth(LangAS::Default);
2390 Align = Target->getPointerAlign(LangAS::Default);
2391 break;
2392 }
2393 break;
2394 case Type::ObjCObjectPointer:
2395 Width = Target->getPointerWidth(LangAS::Default);
2396 Align = Target->getPointerAlign(LangAS::Default);
2397 break;
2398 case Type::BlockPointer:
2399 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2400 Width = Target->getPointerWidth(AS);
2401 Align = Target->getPointerAlign(AS);
2402 break;
2403 case Type::LValueReference:
2404 case Type::RValueReference:
2405 // alignof and sizeof should never enter this code path here, so we go
2406 // the pointer route.
2407 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2408 Width = Target->getPointerWidth(AS);
2409 Align = Target->getPointerAlign(AS);
2410 break;
2411 case Type::Pointer:
2412 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2413 Width = Target->getPointerWidth(AS);
2414 Align = Target->getPointerAlign(AS);
2415 break;
2416 case Type::MemberPointer: {
2417 const auto *MPT = cast<MemberPointerType>(T);
2418 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2419 Width = MPI.Width;
2420 Align = MPI.Align;
2421 break;
2422 }
2423 case Type::Complex: {
2424 // Complex types have the same alignment as their elements, but twice the
2425 // size.
2426 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2427 Width = EltInfo.Width * 2;
2428 Align = EltInfo.Align;
2429 break;
2430 }
2431 case Type::ObjCObject:
2432 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2433 case Type::Adjusted:
2434 case Type::Decayed:
2435 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2436 case Type::ObjCInterface: {
2437 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2438 if (ObjCI->getDecl()->isInvalidDecl()) {
2439 Width = 8;
2440 Align = 8;
2441 break;
2442 }
2443 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2444 Width = toBits(Layout.getSize());
2445 Align = toBits(Layout.getAlignment());
2446 break;
2447 }
2448 case Type::BitInt: {
2449 const auto *EIT = cast<BitIntType>(T);
2450 Align = Target->getBitIntAlign(EIT->getNumBits());
2451 Width = Target->getBitIntWidth(EIT->getNumBits());
2452 break;
2453 }
2454 case Type::Record:
2455 case Type::Enum: {
2456 const auto *TT = cast<TagType>(T);
2457 const TagDecl *TD = TT->getOriginalDecl()->getDefinitionOrSelf();
2458
2459 if (TD->isInvalidDecl()) {
2460 Width = 8;
2461 Align = 8;
2462 break;
2463 }
2464
2465 if (isa<EnumType>(TT)) {
2466 const EnumDecl *ED = cast<EnumDecl>(TD);
2467 TypeInfo Info =
2469 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2470 Info.Align = AttrAlign;
2472 }
2473 return Info;
2474 }
2475
2476 const auto *RD = cast<RecordDecl>(TD);
2477 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2478 Width = toBits(Layout.getSize());
2479 Align = toBits(Layout.getAlignment());
2480 AlignRequirement = RD->hasAttr<AlignedAttr>()
2482 : AlignRequirementKind::None;
2483 break;
2484 }
2485
2486 case Type::SubstTemplateTypeParm:
2488 getReplacementType().getTypePtr());
2489
2490 case Type::Auto:
2491 case Type::DeducedTemplateSpecialization: {
2492 const auto *A = cast<DeducedType>(T);
2493 assert(!A->getDeducedType().isNull() &&
2494 "cannot request the size of an undeduced or dependent auto type");
2495 return getTypeInfo(A->getDeducedType().getTypePtr());
2496 }
2497
2498 case Type::Paren:
2499 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2500
2501 case Type::MacroQualified:
2502 return getTypeInfo(
2504
2505 case Type::ObjCTypeParam:
2506 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2507
2508 case Type::Using:
2509 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2510
2511 case Type::Typedef: {
2512 const auto *TT = cast<TypedefType>(T);
2513 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2514 // If the typedef has an aligned attribute on it, it overrides any computed
2515 // alignment we have. This violates the GCC documentation (which says that
2516 // attribute(aligned) can only round up) but matches its implementation.
2517 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2518 Align = AttrAlign;
2519 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2520 } else {
2521 Align = Info.Align;
2522 AlignRequirement = Info.AlignRequirement;
2523 }
2524 Width = Info.Width;
2525 break;
2526 }
2527
2528 case Type::Attributed:
2529 return getTypeInfo(
2530 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2531
2532 case Type::CountAttributed:
2533 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2534
2535 case Type::BTFTagAttributed:
2536 return getTypeInfo(
2537 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2538
2539 case Type::HLSLAttributedResource:
2540 return getTypeInfo(
2541 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2542
2543 case Type::HLSLInlineSpirv: {
2544 const auto *ST = cast<HLSLInlineSpirvType>(T);
2545 // Size is specified in bytes, convert to bits
2546 Width = ST->getSize() * 8;
2547 Align = ST->getAlignment();
2548 if (Width == 0 && Align == 0) {
2549 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2550 Width = 32;
2551 Align = 32;
2552 }
2553 break;
2554 }
2555
2556 case Type::Atomic: {
2557 // Start with the base type information.
2558 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2559 Width = Info.Width;
2560 Align = Info.Align;
2561
2562 if (!Width) {
2563 // An otherwise zero-sized type should still generate an
2564 // atomic operation.
2565 Width = Target->getCharWidth();
2566 assert(Align);
2567 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2568 // If the size of the type doesn't exceed the platform's max
2569 // atomic promotion width, make the size and alignment more
2570 // favorable to atomic operations:
2571
2572 // Round the size up to a power of 2.
2573 Width = llvm::bit_ceil(Width);
2574
2575 // Set the alignment equal to the size.
2576 Align = static_cast<unsigned>(Width);
2577 }
2578 }
2579 break;
2580
2581 case Type::PredefinedSugar:
2582 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2583
2584 case Type::Pipe:
2585 Width = Target->getPointerWidth(LangAS::opencl_global);
2586 Align = Target->getPointerAlign(LangAS::opencl_global);
2587 break;
2588 }
2589
2590 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2591 return TypeInfo(Width, Align, AlignRequirement);
2592}
2593
2595 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2596 if (I != MemoizedUnadjustedAlign.end())
2597 return I->second;
2598
2599 unsigned UnadjustedAlign;
2600 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2601 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getOriginalDecl());
2602 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2603 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2604 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2605 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2606 } else {
2607 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2608 }
2609
2610 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2611 return UnadjustedAlign;
2612}
2613
2615 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2616 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2617 return SimdAlign;
2618}
2619
2620/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2622 return CharUnits::fromQuantity(BitSize / getCharWidth());
2623}
2624
2625/// toBits - Convert a size in characters to a size in characters.
2626int64_t ASTContext::toBits(CharUnits CharSize) const {
2627 return CharSize.getQuantity() * getCharWidth();
2628}
2629
2630/// getTypeSizeInChars - Return the size of the specified type, in characters.
2631/// This method does not work on incomplete types.
2638
2639/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2640/// characters. This method does not work on incomplete types.
2647
2648/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2649/// type, in characters, before alignment adjustments. This method does
2650/// not work on incomplete types.
2657
2658/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2659/// type for the current target in bits. This can be different than the ABI
2660/// alignment in cases where it is beneficial for performance or backwards
2661/// compatibility preserving to overalign a data type. (Note: despite the name,
2662/// the preferred alignment is ABI-impacting, and not an optimization.)
2664 TypeInfo TI = getTypeInfo(T);
2665 unsigned ABIAlign = TI.Align;
2666
2667 T = T->getBaseElementTypeUnsafe();
2668
2669 // The preferred alignment of member pointers is that of a pointer.
2670 if (T->isMemberPointerType())
2671 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2672
2673 if (!Target->allowsLargerPreferedTypeAlignment())
2674 return ABIAlign;
2675
2676 if (const auto *RD = T->getAsRecordDecl()) {
2677 // When used as part of a typedef, or together with a 'packed' attribute,
2678 // the 'aligned' attribute can be used to decrease alignment. Note that the
2679 // 'packed' case is already taken into consideration when computing the
2680 // alignment, we only need to handle the typedef case here.
2682 RD->isInvalidDecl())
2683 return ABIAlign;
2684
2685 unsigned PreferredAlign = static_cast<unsigned>(
2686 toBits(getASTRecordLayout(RD).PreferredAlignment));
2687 assert(PreferredAlign >= ABIAlign &&
2688 "PreferredAlign should be at least as large as ABIAlign.");
2689 return PreferredAlign;
2690 }
2691
2692 // Double (and, for targets supporting AIX `power` alignment, long double) and
2693 // long long should be naturally aligned (despite requiring less alignment) if
2694 // possible.
2695 if (const auto *CT = T->getAs<ComplexType>())
2696 T = CT->getElementType().getTypePtr();
2697 if (const auto *ED = T->getAsEnumDecl())
2698 T = ED->getIntegerType().getTypePtr();
2699 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2700 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2701 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2702 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2703 Target->defaultsToAIXPowerAlignment()))
2704 // Don't increase the alignment if an alignment attribute was specified on a
2705 // typedef declaration.
2706 if (!TI.isAlignRequired())
2707 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2708
2709 return ABIAlign;
2710}
2711
2712/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2713/// for __attribute__((aligned)) on this target, to be used if no alignment
2714/// value is specified.
2718
2719/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2720/// to a global variable of the specified type.
2722 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2723 return std::max(getPreferredTypeAlign(T),
2724 getMinGlobalAlignOfVar(TypeSize, VD));
2725}
2726
2727/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2728/// should be given to a global variable of the specified type.
2733
2735 const VarDecl *VD) const {
2736 // Make the default handling as that of a non-weak definition in the
2737 // current translation unit.
2738 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2739 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2740}
2741
2743 CharUnits Offset = CharUnits::Zero();
2744 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2745 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2746 Offset += Layout->getBaseClassOffset(Base);
2747 Layout = &getASTRecordLayout(Base);
2748 }
2749 return Offset;
2750}
2751
2753 const ValueDecl *MPD = MP.getMemberPointerDecl();
2756 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2758 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2759 const CXXRecordDecl *Base = RD;
2760 const CXXRecordDecl *Derived = Path[I];
2761 if (DerivedMember)
2762 std::swap(Base, Derived);
2764 RD = Path[I];
2765 }
2766 if (DerivedMember)
2768 return ThisAdjustment;
2769}
2770
2771/// DeepCollectObjCIvars -
2772/// This routine first collects all declared, but not synthesized, ivars in
2773/// super class and then collects all ivars, including those synthesized for
2774/// current class. This routine is used for implementation of current class
2775/// when all ivars, declared and synthesized are known.
2777 bool leafClass,
2779 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2780 DeepCollectObjCIvars(SuperClass, false, Ivars);
2781 if (!leafClass) {
2782 llvm::append_range(Ivars, OI->ivars());
2783 } else {
2784 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2785 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2786 Iv= Iv->getNextIvar())
2787 Ivars.push_back(Iv);
2788 }
2789}
2790
2791/// CollectInheritedProtocols - Collect all protocols in current class and
2792/// those inherited by it.
2795 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2796 // We can use protocol_iterator here instead of
2797 // all_referenced_protocol_iterator since we are walking all categories.
2798 for (auto *Proto : OI->all_referenced_protocols()) {
2799 CollectInheritedProtocols(Proto, Protocols);
2800 }
2801
2802 // Categories of this Interface.
2803 for (const auto *Cat : OI->visible_categories())
2804 CollectInheritedProtocols(Cat, Protocols);
2805
2806 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2807 while (SD) {
2808 CollectInheritedProtocols(SD, Protocols);
2809 SD = SD->getSuperClass();
2810 }
2811 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2812 for (auto *Proto : OC->protocols()) {
2813 CollectInheritedProtocols(Proto, Protocols);
2814 }
2815 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2816 // Insert the protocol.
2817 if (!Protocols.insert(
2818 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2819 return;
2820
2821 for (auto *Proto : OP->protocols())
2822 CollectInheritedProtocols(Proto, Protocols);
2823 }
2824}
2825
2827 const RecordDecl *RD,
2828 bool CheckIfTriviallyCopyable) {
2829 assert(RD->isUnion() && "Must be union type");
2830 CharUnits UnionSize =
2831 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2832
2833 for (const auto *Field : RD->fields()) {
2834 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2835 CheckIfTriviallyCopyable))
2836 return false;
2837 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2838 if (FieldSize != UnionSize)
2839 return false;
2840 }
2841 return !RD->field_empty();
2842}
2843
2844static int64_t getSubobjectOffset(const FieldDecl *Field,
2845 const ASTContext &Context,
2846 const clang::ASTRecordLayout & /*Layout*/) {
2847 return Context.getFieldOffset(Field);
2848}
2849
2850static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2851 const ASTContext &Context,
2852 const clang::ASTRecordLayout &Layout) {
2853 return Context.toBits(Layout.getBaseClassOffset(RD));
2854}
2855
2856static std::optional<int64_t>
2858 const RecordDecl *RD,
2859 bool CheckIfTriviallyCopyable);
2860
2861static std::optional<int64_t>
2862getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2863 bool CheckIfTriviallyCopyable) {
2864 if (const auto *RD = Field->getType()->getAsRecordDecl();
2865 RD && !RD->isUnion())
2866 return structHasUniqueObjectRepresentations(Context, RD,
2867 CheckIfTriviallyCopyable);
2868
2869 // A _BitInt type may not be unique if it has padding bits
2870 // but if it is a bitfield the padding bits are not used.
2871 bool IsBitIntType = Field->getType()->isBitIntType();
2872 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2873 !Context.hasUniqueObjectRepresentations(Field->getType(),
2874 CheckIfTriviallyCopyable))
2875 return std::nullopt;
2876
2877 int64_t FieldSizeInBits =
2878 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2879 if (Field->isBitField()) {
2880 // If we have explicit padding bits, they don't contribute bits
2881 // to the actual object representation, so return 0.
2882 if (Field->isUnnamedBitField())
2883 return 0;
2884
2885 int64_t BitfieldSize = Field->getBitWidthValue();
2886 if (IsBitIntType) {
2887 if ((unsigned)BitfieldSize >
2888 cast<BitIntType>(Field->getType())->getNumBits())
2889 return std::nullopt;
2890 } else if (BitfieldSize > FieldSizeInBits) {
2891 return std::nullopt;
2892 }
2893 FieldSizeInBits = BitfieldSize;
2894 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2895 Field->getType(), CheckIfTriviallyCopyable)) {
2896 return std::nullopt;
2897 }
2898 return FieldSizeInBits;
2899}
2900
2901static std::optional<int64_t>
2903 bool CheckIfTriviallyCopyable) {
2904 return structHasUniqueObjectRepresentations(Context, RD,
2905 CheckIfTriviallyCopyable);
2906}
2907
2908template <typename RangeT>
2910 const RangeT &Subobjects, int64_t CurOffsetInBits,
2911 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2912 bool CheckIfTriviallyCopyable) {
2913 for (const auto *Subobject : Subobjects) {
2914 std::optional<int64_t> SizeInBits =
2915 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2916 if (!SizeInBits)
2917 return std::nullopt;
2918 if (*SizeInBits != 0) {
2919 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2920 if (Offset != CurOffsetInBits)
2921 return std::nullopt;
2922 CurOffsetInBits += *SizeInBits;
2923 }
2924 }
2925 return CurOffsetInBits;
2926}
2927
2928static std::optional<int64_t>
2930 const RecordDecl *RD,
2931 bool CheckIfTriviallyCopyable) {
2932 assert(!RD->isUnion() && "Must be struct/class type");
2933 const auto &Layout = Context.getASTRecordLayout(RD);
2934
2935 int64_t CurOffsetInBits = 0;
2936 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2937 if (ClassDecl->isDynamicClass())
2938 return std::nullopt;
2939
2941 for (const auto &Base : ClassDecl->bases()) {
2942 // Empty types can be inherited from, and non-empty types can potentially
2943 // have tail padding, so just make sure there isn't an error.
2944 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
2945 }
2946
2947 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
2948 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
2949 });
2950
2951 std::optional<int64_t> OffsetAfterBases =
2953 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
2954 if (!OffsetAfterBases)
2955 return std::nullopt;
2956 CurOffsetInBits = *OffsetAfterBases;
2957 }
2958
2959 std::optional<int64_t> OffsetAfterFields =
2961 RD->fields(), CurOffsetInBits, Context, Layout,
2962 CheckIfTriviallyCopyable);
2963 if (!OffsetAfterFields)
2964 return std::nullopt;
2965 CurOffsetInBits = *OffsetAfterFields;
2966
2967 return CurOffsetInBits;
2968}
2969
2971 QualType Ty, bool CheckIfTriviallyCopyable) const {
2972 // C++17 [meta.unary.prop]:
2973 // The predicate condition for a template specialization
2974 // has_unique_object_representations<T> shall be satisfied if and only if:
2975 // (9.1) - T is trivially copyable, and
2976 // (9.2) - any two objects of type T with the same value have the same
2977 // object representation, where:
2978 // - two objects of array or non-union class type are considered to have
2979 // the same value if their respective sequences of direct subobjects
2980 // have the same values, and
2981 // - two objects of union type are considered to have the same value if
2982 // they have the same active member and the corresponding members have
2983 // the same value.
2984 // The set of scalar types for which this condition holds is
2985 // implementation-defined. [ Note: If a type has padding bits, the condition
2986 // does not hold; otherwise, the condition holds true for unsigned integral
2987 // types. -- end note ]
2988 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2989
2990 // Arrays are unique only if their element type is unique.
2991 if (Ty->isArrayType())
2993 CheckIfTriviallyCopyable);
2994
2995 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
2996 "hasUniqueObjectRepresentations should not be called with an "
2997 "incomplete type");
2998
2999 // (9.1) - T is trivially copyable...
3000 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3001 return false;
3002
3003 // All integrals and enums are unique.
3004 if (Ty->isIntegralOrEnumerationType()) {
3005 // Address discriminated integer types are not unique.
3007 return false;
3008 // Except _BitInt types that have padding bits.
3009 if (const auto *BIT = Ty->getAs<BitIntType>())
3010 return getTypeSize(BIT) == BIT->getNumBits();
3011
3012 return true;
3013 }
3014
3015 // All other pointers are unique.
3016 if (Ty->isPointerType())
3018
3019 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3020 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3021
3022 if (const auto *Record = Ty->getAsRecordDecl()) {
3023 if (Record->isInvalidDecl())
3024 return false;
3025
3026 if (Record->isUnion())
3028 CheckIfTriviallyCopyable);
3029
3030 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3031 *this, Record, CheckIfTriviallyCopyable);
3032
3033 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3034 }
3035
3036 // FIXME: More cases to handle here (list by rsmith):
3037 // vectors (careful about, eg, vector of 3 foo)
3038 // _Complex int and friends
3039 // _Atomic T
3040 // Obj-C block pointers
3041 // Obj-C object pointers
3042 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3043 // clk_event_t, queue_t, reserve_id_t)
3044 // There're also Obj-C class types and the Obj-C selector type, but I think it
3045 // makes sense for those to return false here.
3046
3047 return false;
3048}
3049
3051 unsigned count = 0;
3052 // Count ivars declared in class extension.
3053 for (const auto *Ext : OI->known_extensions())
3054 count += Ext->ivar_size();
3055
3056 // Count ivar defined in this class's implementation. This
3057 // includes synthesized ivars.
3058 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3059 count += ImplDecl->ivar_size();
3060
3061 return count;
3062}
3063
3065 if (!E)
3066 return false;
3067
3068 // nullptr_t is always treated as null.
3069 if (E->getType()->isNullPtrType()) return true;
3070
3071 if (E->getType()->isAnyPointerType() &&
3074 return true;
3075
3076 // Unfortunately, __null has type 'int'.
3077 if (isa<GNUNullExpr>(E)) return true;
3078
3079 return false;
3080}
3081
3082/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3083/// exists.
3085 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3086 I = ObjCImpls.find(D);
3087 if (I != ObjCImpls.end())
3088 return cast<ObjCImplementationDecl>(I->second);
3089 return nullptr;
3090}
3091
3092/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3093/// exists.
3095 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3096 I = ObjCImpls.find(D);
3097 if (I != ObjCImpls.end())
3098 return cast<ObjCCategoryImplDecl>(I->second);
3099 return nullptr;
3100}
3101
3102/// Set the implementation of ObjCInterfaceDecl.
3104 ObjCImplementationDecl *ImplD) {
3105 assert(IFaceD && ImplD && "Passed null params");
3106 ObjCImpls[IFaceD] = ImplD;
3107}
3108
3109/// Set the implementation of ObjCCategoryDecl.
3111 ObjCCategoryImplDecl *ImplD) {
3112 assert(CatD && ImplD && "Passed null params");
3113 ObjCImpls[CatD] = ImplD;
3114}
3115
3116const ObjCMethodDecl *
3118 return ObjCMethodRedecls.lookup(MD);
3119}
3120
3122 const ObjCMethodDecl *Redecl) {
3123 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3124 ObjCMethodRedecls[MD] = Redecl;
3125}
3126
3128 const NamedDecl *ND) const {
3129 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3130 return ID;
3131 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3132 return CD->getClassInterface();
3133 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3134 return IMD->getClassInterface();
3135
3136 return nullptr;
3137}
3138
3139/// Get the copy initialization expression of VarDecl, or nullptr if
3140/// none exists.
3142 assert(VD && "Passed null params");
3143 assert(VD->hasAttr<BlocksAttr>() &&
3144 "getBlockVarCopyInits - not __block var");
3145 auto I = BlockVarCopyInits.find(VD);
3146 if (I != BlockVarCopyInits.end())
3147 return I->second;
3148 return {nullptr, false};
3149}
3150
3151/// Set the copy initialization expression of a block var decl.
3153 bool CanThrow) {
3154 assert(VD && CopyExpr && "Passed null params");
3155 assert(VD->hasAttr<BlocksAttr>() &&
3156 "setBlockVarCopyInits - not __block var");
3157 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3158}
3159
3161 unsigned DataSize) const {
3162 if (!DataSize)
3164 else
3165 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3166 "incorrect data size provided to CreateTypeSourceInfo!");
3167
3168 auto *TInfo =
3169 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3170 new (TInfo) TypeSourceInfo(T, DataSize);
3171 return TInfo;
3172}
3173
3175 SourceLocation L) const {
3177 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3178 return DI;
3179}
3180
3181const ASTRecordLayout &
3183 return getObjCLayout(D);
3184}
3185
3188 bool &AnyNonCanonArgs) {
3189 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3190 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3191 return CanonArgs;
3192}
3193
3196 bool AnyNonCanonArgs = false;
3197 for (auto &Arg : Args) {
3198 TemplateArgument OrigArg = Arg;
3200 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3201 }
3202 return AnyNonCanonArgs;
3203}
3204
3205//===----------------------------------------------------------------------===//
3206// Type creation/memoization methods
3207//===----------------------------------------------------------------------===//
3208
3210ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3211 unsigned fastQuals = quals.getFastQualifiers();
3212 quals.removeFastQualifiers();
3213
3214 // Check if we've already instantiated this type.
3215 llvm::FoldingSetNodeID ID;
3216 ExtQuals::Profile(ID, baseType, quals);
3217 void *insertPos = nullptr;
3218 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
3219 assert(eq->getQualifiers() == quals);
3220 return QualType(eq, fastQuals);
3221 }
3222
3223 // If the base type is not canonical, make the appropriate canonical type.
3224 QualType canon;
3225 if (!baseType->isCanonicalUnqualified()) {
3226 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3227 canonSplit.Quals.addConsistentQualifiers(quals);
3228 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3229
3230 // Re-find the insert position.
3231 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
3232 }
3233
3234 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3235 ExtQualNodes.InsertNode(eq, insertPos);
3236 return QualType(eq, fastQuals);
3237}
3238
3240 LangAS AddressSpace) const {
3241 QualType CanT = getCanonicalType(T);
3242 if (CanT.getAddressSpace() == AddressSpace)
3243 return T;
3244
3245 // If we are composing extended qualifiers together, merge together
3246 // into one ExtQuals node.
3247 QualifierCollector Quals;
3248 const Type *TypeNode = Quals.strip(T);
3249
3250 // If this type already has an address space specified, it cannot get
3251 // another one.
3252 assert(!Quals.hasAddressSpace() &&
3253 "Type cannot be in multiple addr spaces!");
3254 Quals.addAddressSpace(AddressSpace);
3255
3256 return getExtQualType(TypeNode, Quals);
3257}
3258
3260 // If the type is not qualified with an address space, just return it
3261 // immediately.
3262 if (!T.hasAddressSpace())
3263 return T;
3264
3265 QualifierCollector Quals;
3266 const Type *TypeNode;
3267 // For arrays, strip the qualifier off the element type, then reconstruct the
3268 // array type
3269 if (T.getTypePtr()->isArrayType()) {
3270 T = getUnqualifiedArrayType(T, Quals);
3271 TypeNode = T.getTypePtr();
3272 } else {
3273 // If we are composing extended qualifiers together, merge together
3274 // into one ExtQuals node.
3275 while (T.hasAddressSpace()) {
3276 TypeNode = Quals.strip(T);
3277
3278 // If the type no longer has an address space after stripping qualifiers,
3279 // jump out.
3280 if (!QualType(TypeNode, 0).hasAddressSpace())
3281 break;
3282
3283 // There might be sugar in the way. Strip it and try again.
3284 T = T.getSingleStepDesugaredType(*this);
3285 }
3286 }
3287
3288 Quals.removeAddressSpace();
3289
3290 // Removal of the address space can mean there are no longer any
3291 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3292 // or required.
3293 if (Quals.hasNonFastQualifiers())
3294 return getExtQualType(TypeNode, Quals);
3295 else
3296 return QualType(TypeNode, Quals.getFastQualifiers());
3297}
3298
3299uint16_t
3301 assert(RD->isPolymorphic() &&
3302 "Attempted to get vtable pointer discriminator on a monomorphic type");
3303 std::unique_ptr<MangleContext> MC(createMangleContext());
3304 SmallString<256> Str;
3305 llvm::raw_svector_ostream Out(Str);
3306 MC->mangleCXXVTable(RD, Out);
3307 return llvm::getPointerAuthStableSipHash(Str);
3308}
3309
3310/// Encode a function type for use in the discriminator of a function pointer
3311/// type. We can't use the itanium scheme for this since C has quite permissive
3312/// rules for type compatibility that we need to be compatible with.
3313///
3314/// Formally, this function associates every function pointer type T with an
3315/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3316/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3317/// compatibility requires equivalent treatment under the ABI, so
3318/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3319/// a subset of ~. Crucially, however, it must be a proper subset because
3320/// CCompatible is not an equivalence relation: for example, int[] is compatible
3321/// with both int[1] and int[2], but the latter are not compatible with each
3322/// other. Therefore this encoding function must be careful to only distinguish
3323/// types if there is no third type with which they are both required to be
3324/// compatible.
3326 raw_ostream &OS, QualType QT) {
3327 // FIXME: Consider address space qualifiers.
3328 const Type *T = QT.getCanonicalType().getTypePtr();
3329
3330 // FIXME: Consider using the C++ type mangling when we encounter a construct
3331 // that is incompatible with C.
3332
3333 switch (T->getTypeClass()) {
3334 case Type::Atomic:
3336 Ctx, OS, cast<AtomicType>(T)->getValueType());
3337
3338 case Type::LValueReference:
3339 OS << "R";
3342 return;
3343 case Type::RValueReference:
3344 OS << "O";
3347 return;
3348
3349 case Type::Pointer:
3350 // C11 6.7.6.1p2:
3351 // For two pointer types to be compatible, both shall be identically
3352 // qualified and both shall be pointers to compatible types.
3353 // FIXME: we should also consider pointee types.
3354 OS << "P";
3355 return;
3356
3357 case Type::ObjCObjectPointer:
3358 case Type::BlockPointer:
3359 OS << "P";
3360 return;
3361
3362 case Type::Complex:
3363 OS << "C";
3365 Ctx, OS, cast<ComplexType>(T)->getElementType());
3366
3367 case Type::VariableArray:
3368 case Type::ConstantArray:
3369 case Type::IncompleteArray:
3370 case Type::ArrayParameter:
3371 // C11 6.7.6.2p6:
3372 // For two array types to be compatible, both shall have compatible
3373 // element types, and if both size specifiers are present, and are integer
3374 // constant expressions, then both size specifiers shall have the same
3375 // constant value [...]
3376 //
3377 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3378 // width of the array.
3379 OS << "A";
3381 Ctx, OS, cast<ArrayType>(T)->getElementType());
3382
3383 case Type::ObjCInterface:
3384 case Type::ObjCObject:
3385 OS << "<objc_object>";
3386 return;
3387
3388 case Type::Enum: {
3389 // C11 6.7.2.2p4:
3390 // Each enumerated type shall be compatible with char, a signed integer
3391 // type, or an unsigned integer type.
3392 //
3393 // So we have to treat enum types as integers.
3394 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3396 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3397 }
3398
3399 case Type::FunctionNoProto:
3400 case Type::FunctionProto: {
3401 // C11 6.7.6.3p15:
3402 // For two function types to be compatible, both shall specify compatible
3403 // return types. Moreover, the parameter type lists, if both are present,
3404 // shall agree in the number of parameters and in the use of the ellipsis
3405 // terminator; corresponding parameters shall have compatible types.
3406 //
3407 // That paragraph goes on to describe how unprototyped functions are to be
3408 // handled, which we ignore here. Unprototyped function pointers are hashed
3409 // as though they were prototyped nullary functions since thats probably
3410 // what the user meant. This behavior is non-conforming.
3411 // FIXME: If we add a "custom discriminator" function type attribute we
3412 // should encode functions as their discriminators.
3413 OS << "F";
3414 const auto *FuncType = cast<FunctionType>(T);
3415 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3416 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3417 for (QualType Param : FPT->param_types()) {
3418 Param = Ctx.getSignatureParameterType(Param);
3419 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3420 }
3421 if (FPT->isVariadic())
3422 OS << "z";
3423 }
3424 OS << "E";
3425 return;
3426 }
3427
3428 case Type::MemberPointer: {
3429 OS << "M";
3430 const auto *MPT = T->castAs<MemberPointerType>();
3432 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3433 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3434 return;
3435 }
3436 case Type::ExtVector:
3437 case Type::Vector:
3438 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3439 break;
3440
3441 // Don't bother discriminating based on these types.
3442 case Type::Pipe:
3443 case Type::BitInt:
3444 case Type::ConstantMatrix:
3445 OS << "?";
3446 return;
3447
3448 case Type::Builtin: {
3449 const auto *BTy = T->castAs<BuiltinType>();
3450 switch (BTy->getKind()) {
3451#define SIGNED_TYPE(Id, SingletonId) \
3452 case BuiltinType::Id: \
3453 OS << "i"; \
3454 return;
3455#define UNSIGNED_TYPE(Id, SingletonId) \
3456 case BuiltinType::Id: \
3457 OS << "i"; \
3458 return;
3459#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3460#define BUILTIN_TYPE(Id, SingletonId)
3461#include "clang/AST/BuiltinTypes.def"
3462 llvm_unreachable("placeholder types should not appear here.");
3463
3464 case BuiltinType::Half:
3465 OS << "Dh";
3466 return;
3467 case BuiltinType::Float:
3468 OS << "f";
3469 return;
3470 case BuiltinType::Double:
3471 OS << "d";
3472 return;
3473 case BuiltinType::LongDouble:
3474 OS << "e";
3475 return;
3476 case BuiltinType::Float16:
3477 OS << "DF16_";
3478 return;
3479 case BuiltinType::Float128:
3480 OS << "g";
3481 return;
3482
3483 case BuiltinType::Void:
3484 OS << "v";
3485 return;
3486
3487 case BuiltinType::ObjCId:
3488 case BuiltinType::ObjCClass:
3489 case BuiltinType::ObjCSel:
3490 case BuiltinType::NullPtr:
3491 OS << "P";
3492 return;
3493
3494 // Don't bother discriminating based on OpenCL types.
3495 case BuiltinType::OCLSampler:
3496 case BuiltinType::OCLEvent:
3497 case BuiltinType::OCLClkEvent:
3498 case BuiltinType::OCLQueue:
3499 case BuiltinType::OCLReserveID:
3500 case BuiltinType::BFloat16:
3501 case BuiltinType::VectorQuad:
3502 case BuiltinType::VectorPair:
3503 case BuiltinType::DMR1024:
3504 OS << "?";
3505 return;
3506
3507 // Don't bother discriminating based on these seldom-used types.
3508 case BuiltinType::Ibm128:
3509 return;
3510#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3511 case BuiltinType::Id: \
3512 return;
3513#include "clang/Basic/OpenCLImageTypes.def"
3514#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3515 case BuiltinType::Id: \
3516 return;
3517#include "clang/Basic/OpenCLExtensionTypes.def"
3518#define SVE_TYPE(Name, Id, SingletonId) \
3519 case BuiltinType::Id: \
3520 return;
3521#include "clang/Basic/AArch64ACLETypes.def"
3522#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3523 case BuiltinType::Id: \
3524 return;
3525#include "clang/Basic/HLSLIntangibleTypes.def"
3526 case BuiltinType::Dependent:
3527 llvm_unreachable("should never get here");
3528#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3529#include "clang/Basic/AMDGPUTypes.def"
3530 case BuiltinType::WasmExternRef:
3531#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3532#include "clang/Basic/RISCVVTypes.def"
3533 llvm_unreachable("not yet implemented");
3534 }
3535 llvm_unreachable("should never get here");
3536 }
3537 case Type::Record: {
3538 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3539 const IdentifierInfo *II = RD->getIdentifier();
3540
3541 // In C++, an immediate typedef of an anonymous struct or union
3542 // is considered to name it for ODR purposes, but C's specification
3543 // of type compatibility does not have a similar rule. Using the typedef
3544 // name in function type discriminators anyway, as we do here,
3545 // therefore technically violates the C standard: two function pointer
3546 // types defined in terms of two typedef'd anonymous structs with
3547 // different names are formally still compatible, but we are assigning
3548 // them different discriminators and therefore incompatible ABIs.
3549 //
3550 // This is a relatively minor violation that significantly improves
3551 // discrimination in some cases and has not caused problems in
3552 // practice. Regardless, it is now part of the ABI in places where
3553 // function type discrimination is used, and it can no longer be
3554 // changed except on new platforms.
3555
3556 if (!II)
3557 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3558 II = Typedef->getDeclName().getAsIdentifierInfo();
3559
3560 if (!II) {
3561 OS << "<anonymous_record>";
3562 return;
3563 }
3564 OS << II->getLength() << II->getName();
3565 return;
3566 }
3567 case Type::HLSLAttributedResource:
3568 case Type::HLSLInlineSpirv:
3569 llvm_unreachable("should never get here");
3570 break;
3571 case Type::DeducedTemplateSpecialization:
3572 case Type::Auto:
3573#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3574#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3575#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3576#define ABSTRACT_TYPE(Class, Base)
3577#define TYPE(Class, Base)
3578#include "clang/AST/TypeNodes.inc"
3579 llvm_unreachable("unexpected non-canonical or dependent type!");
3580 return;
3581 }
3582}
3583
3585 assert(!T->isDependentType() &&
3586 "cannot compute type discriminator of a dependent type");
3587
3588 SmallString<256> Str;
3589 llvm::raw_svector_ostream Out(Str);
3590
3591 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3592 T = T->getPointeeType();
3593
3594 if (T->isFunctionType()) {
3596 } else {
3597 T = T.getUnqualifiedType();
3598 // Calls to member function pointers don't need to worry about
3599 // language interop or the laxness of the C type compatibility rules.
3600 // We just mangle the member pointer type directly, which is
3601 // implicitly much stricter about type matching. However, we do
3602 // strip any top-level exception specification before this mangling.
3603 // C++23 requires calls to work when the function type is convertible
3604 // to the pointer type by a function pointer conversion, which can
3605 // change the exception specification. This does not technically
3606 // require the exception specification to not affect representation,
3607 // because the function pointer conversion is still always a direct
3608 // value conversion and therefore an opportunity to resign the
3609 // pointer. (This is in contrast to e.g. qualification conversions,
3610 // which can be applied in nested pointer positions, effectively
3611 // requiring qualified and unqualified representations to match.)
3612 // However, it is pragmatic to ignore exception specifications
3613 // because it allows a certain amount of `noexcept` mismatching
3614 // to not become a visible ODR problem. This also leaves some
3615 // room for the committee to add laxness to function pointer
3616 // conversions in future standards.
3617 if (auto *MPT = T->getAs<MemberPointerType>())
3618 if (MPT->isMemberFunctionPointer()) {
3619 QualType PointeeType = MPT->getPointeeType();
3620 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3621 EST_None) {
3623 T = getMemberPointerType(FT, MPT->getQualifier(),
3624 MPT->getMostRecentCXXRecordDecl());
3625 }
3626 }
3627 std::unique_ptr<MangleContext> MC(createMangleContext());
3628 MC->mangleCanonicalTypeName(T, Out);
3629 }
3630
3631 return llvm::getPointerAuthStableSipHash(Str);
3632}
3633
3635 Qualifiers::GC GCAttr) const {
3636 QualType CanT = getCanonicalType(T);
3637 if (CanT.getObjCGCAttr() == GCAttr)
3638 return T;
3639
3640 if (const auto *ptr = T->getAs<PointerType>()) {
3641 QualType Pointee = ptr->getPointeeType();
3642 if (Pointee->isAnyPointerType()) {
3643 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3644 return getPointerType(ResultType);
3645 }
3646 }
3647
3648 // If we are composing extended qualifiers together, merge together
3649 // into one ExtQuals node.
3650 QualifierCollector Quals;
3651 const Type *TypeNode = Quals.strip(T);
3652
3653 // If this type already has an ObjCGC specified, it cannot get
3654 // another one.
3655 assert(!Quals.hasObjCGCAttr() &&
3656 "Type cannot have multiple ObjCGCs!");
3657 Quals.addObjCGCAttr(GCAttr);
3658
3659 return getExtQualType(TypeNode, Quals);
3660}
3661
3663 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3664 QualType Pointee = Ptr->getPointeeType();
3665 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3666 return getPointerType(removeAddrSpaceQualType(Pointee));
3667 }
3668 }
3669 return T;
3670}
3671
3673 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3674 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3675 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3676
3677 llvm::FoldingSetNodeID ID;
3678 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3679
3680 void *InsertPos = nullptr;
3681 CountAttributedType *CATy =
3682 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3683 if (CATy)
3684 return QualType(CATy, 0);
3685
3686 QualType CanonTy = getCanonicalType(WrappedTy);
3687 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3688 DependentDecls.size());
3690 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3691 OrNull, DependentDecls);
3692 Types.push_back(CATy);
3693 CountAttributedTypes.InsertNode(CATy, InsertPos);
3694
3695 return QualType(CATy, 0);
3696}
3697
3700 llvm::function_ref<QualType(QualType)> Adjust) const {
3701 switch (Orig->getTypeClass()) {
3702 case Type::Attributed: {
3703 const auto *AT = cast<AttributedType>(Orig);
3704 return getAttributedType(AT->getAttrKind(),
3705 adjustType(AT->getModifiedType(), Adjust),
3706 adjustType(AT->getEquivalentType(), Adjust),
3707 AT->getAttr());
3708 }
3709
3710 case Type::BTFTagAttributed: {
3711 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3712 return getBTFTagAttributedType(BTFT->getAttr(),
3713 adjustType(BTFT->getWrappedType(), Adjust));
3714 }
3715
3716 case Type::Paren:
3717 return getParenType(
3718 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3719
3720 case Type::Adjusted: {
3721 const auto *AT = cast<AdjustedType>(Orig);
3722 return getAdjustedType(AT->getOriginalType(),
3723 adjustType(AT->getAdjustedType(), Adjust));
3724 }
3725
3726 case Type::MacroQualified: {
3727 const auto *MQT = cast<MacroQualifiedType>(Orig);
3728 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3729 MQT->getMacroIdentifier());
3730 }
3731
3732 default:
3733 return Adjust(Orig);
3734 }
3735}
3736
3738 FunctionType::ExtInfo Info) {
3739 if (T->getExtInfo() == Info)
3740 return T;
3741
3743 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3744 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3745 } else {
3746 const auto *FPT = cast<FunctionProtoType>(T);
3747 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3748 EPI.ExtInfo = Info;
3749 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3750 }
3751
3752 return cast<FunctionType>(Result.getTypePtr());
3753}
3754
3756 QualType ResultType) {
3757 return adjustType(FunctionType, [&](QualType Orig) {
3758 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3759 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3760
3761 const auto *FPT = Orig->castAs<FunctionProtoType>();
3762 return getFunctionType(ResultType, FPT->getParamTypes(),
3763 FPT->getExtProtoInfo());
3764 });
3765}
3766
3768 QualType ResultType) {
3769 FD = FD->getMostRecentDecl();
3770 while (true) {
3771 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3772 if (FunctionDecl *Next = FD->getPreviousDecl())
3773 FD = Next;
3774 else
3775 break;
3776 }
3778 L->DeducedReturnType(FD, ResultType);
3779}
3780
3781/// Get a function type and produce the equivalent function type with the
3782/// specified exception specification. Type sugar that can be present on a
3783/// declaration of a function with an exception specification is permitted
3784/// and preserved. Other type sugar (for instance, typedefs) is not.
3786 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3787 return adjustType(Orig, [&](QualType Ty) {
3788 const auto *Proto = Ty->castAs<FunctionProtoType>();
3789 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3790 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3791 });
3792}
3793
3801
3803 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3804 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3805 SmallVector<QualType, 16> Args(Proto->param_types().size());
3806 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3807 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3808 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3809 }
3810
3811 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3812 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3813 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3814 }
3815
3816 return T;
3817}
3818
3824
3826 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3827 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3828 EPI.ExtParameterInfos = nullptr;
3829 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3830 }
3831 return T;
3832}
3833
3839
3842 bool AsWritten) {
3843 // Update the type.
3844 QualType Updated =
3846 FD->setType(Updated);
3847
3848 if (!AsWritten)
3849 return;
3850
3851 // Update the type in the type source information too.
3852 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3853 // If the type and the type-as-written differ, we may need to update
3854 // the type-as-written too.
3855 if (TSInfo->getType() != FD->getType())
3856 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3857
3858 // FIXME: When we get proper type location information for exceptions,
3859 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3860 // up the TypeSourceInfo;
3861 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3862 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3863 "TypeLoc size mismatch from updating exception specification");
3864 TSInfo->overrideType(Updated);
3865 }
3866}
3867
3868/// getComplexType - Return the uniqued reference to the type for a complex
3869/// number with the specified element type.
3871 // Unique pointers, to guarantee there is only one pointer of a particular
3872 // structure.
3873 llvm::FoldingSetNodeID ID;
3875
3876 void *InsertPos = nullptr;
3877 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3878 return QualType(CT, 0);
3879
3880 // If the pointee type isn't canonical, this won't be a canonical type either,
3881 // so fill in the canonical type field.
3882 QualType Canonical;
3883 if (!T.isCanonical()) {
3884 Canonical = getComplexType(getCanonicalType(T));
3885
3886 // Get the new insert position for the node we care about.
3887 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3888 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3889 }
3890 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3891 Types.push_back(New);
3892 ComplexTypes.InsertNode(New, InsertPos);
3893 return QualType(New, 0);
3894}
3895
3896/// getPointerType - Return the uniqued reference to the type for a pointer to
3897/// the specified type.
3899 // Unique pointers, to guarantee there is only one pointer of a particular
3900 // structure.
3901 llvm::FoldingSetNodeID ID;
3903
3904 void *InsertPos = nullptr;
3905 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3906 return QualType(PT, 0);
3907
3908 // If the pointee type isn't canonical, this won't be a canonical type either,
3909 // so fill in the canonical type field.
3910 QualType Canonical;
3911 if (!T.isCanonical()) {
3912 Canonical = getPointerType(getCanonicalType(T));
3913
3914 // Get the new insert position for the node we care about.
3915 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3916 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3917 }
3918 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3919 Types.push_back(New);
3920 PointerTypes.InsertNode(New, InsertPos);
3921 return QualType(New, 0);
3922}
3923
3925 llvm::FoldingSetNodeID ID;
3926 AdjustedType::Profile(ID, Orig, New);
3927 void *InsertPos = nullptr;
3928 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3929 if (AT)
3930 return QualType(AT, 0);
3931
3932 QualType Canonical = getCanonicalType(New);
3933
3934 // Get the new insert position for the node we care about.
3935 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3936 assert(!AT && "Shouldn't be in the map!");
3937
3938 AT = new (*this, alignof(AdjustedType))
3939 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3940 Types.push_back(AT);
3941 AdjustedTypes.InsertNode(AT, InsertPos);
3942 return QualType(AT, 0);
3943}
3944
3946 llvm::FoldingSetNodeID ID;
3947 AdjustedType::Profile(ID, Orig, Decayed);
3948 void *InsertPos = nullptr;
3949 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3950 if (AT)
3951 return QualType(AT, 0);
3952
3953 QualType Canonical = getCanonicalType(Decayed);
3954
3955 // Get the new insert position for the node we care about.
3956 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3957 assert(!AT && "Shouldn't be in the map!");
3958
3959 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3960 Types.push_back(AT);
3961 AdjustedTypes.InsertNode(AT, InsertPos);
3962 return QualType(AT, 0);
3963}
3964
3966 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3967
3968 QualType Decayed;
3969
3970 // C99 6.7.5.3p7:
3971 // A declaration of a parameter as "array of type" shall be
3972 // adjusted to "qualified pointer to type", where the type
3973 // qualifiers (if any) are those specified within the [ and ] of
3974 // the array type derivation.
3975 if (T->isArrayType())
3976 Decayed = getArrayDecayedType(T);
3977
3978 // C99 6.7.5.3p8:
3979 // A declaration of a parameter as "function returning type"
3980 // shall be adjusted to "pointer to function returning type", as
3981 // in 6.3.2.1.
3982 if (T->isFunctionType())
3983 Decayed = getPointerType(T);
3984
3985 return getDecayedType(T, Decayed);
3986}
3987
3989 if (Ty->isArrayParameterType())
3990 return Ty;
3991 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3992 QualType DTy = Ty.getDesugaredType(*this);
3993 const auto *ATy = cast<ConstantArrayType>(DTy);
3994 llvm::FoldingSetNodeID ID;
3995 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3996 ATy->getSizeExpr(), ATy->getSizeModifier(),
3997 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3998 void *InsertPos = nullptr;
3999 ArrayParameterType *AT =
4000 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4001 if (AT)
4002 return QualType(AT, 0);
4003
4004 QualType Canonical;
4005 if (!DTy.isCanonical()) {
4006 Canonical = getArrayParameterType(getCanonicalType(Ty));
4007
4008 // Get the new insert position for the node we care about.
4009 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4010 assert(!AT && "Shouldn't be in the map!");
4011 }
4012
4013 AT = new (*this, alignof(ArrayParameterType))
4014 ArrayParameterType(ATy, Canonical);
4015 Types.push_back(AT);
4016 ArrayParameterTypes.InsertNode(AT, InsertPos);
4017 return QualType(AT, 0);
4018}
4019
4020/// getBlockPointerType - Return the uniqued reference to the type for
4021/// a pointer to the specified block.
4023 assert(T->isFunctionType() && "block of function types only");
4024 // Unique pointers, to guarantee there is only one block of a particular
4025 // structure.
4026 llvm::FoldingSetNodeID ID;
4028
4029 void *InsertPos = nullptr;
4030 if (BlockPointerType *PT =
4031 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4032 return QualType(PT, 0);
4033
4034 // If the block pointee type isn't canonical, this won't be a canonical
4035 // type either so fill in the canonical type field.
4036 QualType Canonical;
4037 if (!T.isCanonical()) {
4039
4040 // Get the new insert position for the node we care about.
4041 BlockPointerType *NewIP =
4042 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4043 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4044 }
4045 auto *New =
4046 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4047 Types.push_back(New);
4048 BlockPointerTypes.InsertNode(New, InsertPos);
4049 return QualType(New, 0);
4050}
4051
4052/// getLValueReferenceType - Return the uniqued reference to the type for an
4053/// lvalue reference to the specified type.
4055ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4056 assert((!T->isPlaceholderType() ||
4057 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4058 "Unresolved placeholder type");
4059
4060 // Unique pointers, to guarantee there is only one pointer of a particular
4061 // structure.
4062 llvm::FoldingSetNodeID ID;
4063 ReferenceType::Profile(ID, T, SpelledAsLValue);
4064
4065 void *InsertPos = nullptr;
4066 if (LValueReferenceType *RT =
4067 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4068 return QualType(RT, 0);
4069
4070 const auto *InnerRef = T->getAs<ReferenceType>();
4071
4072 // If the referencee type isn't canonical, this won't be a canonical type
4073 // either, so fill in the canonical type field.
4074 QualType Canonical;
4075 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4076 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4077 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4078
4079 // Get the new insert position for the node we care about.
4080 LValueReferenceType *NewIP =
4081 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4082 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4083 }
4084
4085 auto *New = new (*this, alignof(LValueReferenceType))
4086 LValueReferenceType(T, Canonical, SpelledAsLValue);
4087 Types.push_back(New);
4088 LValueReferenceTypes.InsertNode(New, InsertPos);
4089
4090 return QualType(New, 0);
4091}
4092
4093/// getRValueReferenceType - Return the uniqued reference to the type for an
4094/// rvalue reference to the specified type.
4096 assert((!T->isPlaceholderType() ||
4097 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4098 "Unresolved placeholder type");
4099
4100 // Unique pointers, to guarantee there is only one pointer of a particular
4101 // structure.
4102 llvm::FoldingSetNodeID ID;
4103 ReferenceType::Profile(ID, T, false);
4104
4105 void *InsertPos = nullptr;
4106 if (RValueReferenceType *RT =
4107 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4108 return QualType(RT, 0);
4109
4110 const auto *InnerRef = T->getAs<ReferenceType>();
4111
4112 // If the referencee type isn't canonical, this won't be a canonical type
4113 // either, so fill in the canonical type field.
4114 QualType Canonical;
4115 if (InnerRef || !T.isCanonical()) {
4116 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4117 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4118
4119 // Get the new insert position for the node we care about.
4120 RValueReferenceType *NewIP =
4121 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4122 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4123 }
4124
4125 auto *New = new (*this, alignof(RValueReferenceType))
4126 RValueReferenceType(T, Canonical);
4127 Types.push_back(New);
4128 RValueReferenceTypes.InsertNode(New, InsertPos);
4129 return QualType(New, 0);
4130}
4131
4133 NestedNameSpecifier Qualifier,
4134 const CXXRecordDecl *Cls) const {
4135 if (!Qualifier) {
4136 assert(Cls && "At least one of Qualifier or Cls must be provided");
4137 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4138 } else if (!Cls) {
4139 Cls = Qualifier.getAsRecordDecl();
4140 }
4141 // Unique pointers, to guarantee there is only one pointer of a particular
4142 // structure.
4143 llvm::FoldingSetNodeID ID;
4144 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4145
4146 void *InsertPos = nullptr;
4147 if (MemberPointerType *PT =
4148 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4149 return QualType(PT, 0);
4150
4151 NestedNameSpecifier CanonicalQualifier = [&] {
4152 if (!Cls)
4153 return Qualifier.getCanonical();
4154 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4155 assert(R.isCanonical());
4156 return R;
4157 }();
4158 // If the pointee or class type isn't canonical, this won't be a canonical
4159 // type either, so fill in the canonical type field.
4160 QualType Canonical;
4161 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4162 Canonical =
4163 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4164 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4165 // Get the new insert position for the node we care about.
4166 [[maybe_unused]] MemberPointerType *NewIP =
4167 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4168 assert(!NewIP && "Shouldn't be in the map!");
4169 }
4170 auto *New = new (*this, alignof(MemberPointerType))
4171 MemberPointerType(T, Qualifier, Canonical);
4172 Types.push_back(New);
4173 MemberPointerTypes.InsertNode(New, InsertPos);
4174 return QualType(New, 0);
4175}
4176
4177/// getConstantArrayType - Return the unique reference to the type for an
4178/// array of the specified element type.
4180 const llvm::APInt &ArySizeIn,
4181 const Expr *SizeExpr,
4183 unsigned IndexTypeQuals) const {
4184 assert((EltTy->isDependentType() ||
4185 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4186 "Constant array of VLAs is illegal!");
4187
4188 // We only need the size as part of the type if it's instantiation-dependent.
4189 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4190 SizeExpr = nullptr;
4191
4192 // Convert the array size into a canonical width matching the pointer size for
4193 // the target.
4194 llvm::APInt ArySize(ArySizeIn);
4195 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4196
4197 llvm::FoldingSetNodeID ID;
4198 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4199 ASM, IndexTypeQuals);
4200
4201 void *InsertPos = nullptr;
4202 if (ConstantArrayType *ATP =
4203 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4204 return QualType(ATP, 0);
4205
4206 // If the element type isn't canonical or has qualifiers, or the array bound
4207 // is instantiation-dependent, this won't be a canonical type either, so fill
4208 // in the canonical type field.
4209 QualType Canon;
4210 // FIXME: Check below should look for qualifiers behind sugar.
4211 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4212 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4213 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4214 ASM, IndexTypeQuals);
4215 Canon = getQualifiedType(Canon, canonSplit.Quals);
4216
4217 // Get the new insert position for the node we care about.
4218 ConstantArrayType *NewIP =
4219 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4220 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4221 }
4222
4223 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4224 ASM, IndexTypeQuals);
4225 ConstantArrayTypes.InsertNode(New, InsertPos);
4226 Types.push_back(New);
4227 return QualType(New, 0);
4228}
4229
4230/// getVariableArrayDecayedType - Turns the given type, which may be
4231/// variably-modified, into the corresponding type with all the known
4232/// sizes replaced with [*].
4234 // Vastly most common case.
4235 if (!type->isVariablyModifiedType()) return type;
4236
4237 QualType result;
4238
4239 SplitQualType split = type.getSplitDesugaredType();
4240 const Type *ty = split.Ty;
4241 switch (ty->getTypeClass()) {
4242#define TYPE(Class, Base)
4243#define ABSTRACT_TYPE(Class, Base)
4244#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4245#include "clang/AST/TypeNodes.inc"
4246 llvm_unreachable("didn't desugar past all non-canonical types?");
4247
4248 // These types should never be variably-modified.
4249 case Type::Builtin:
4250 case Type::Complex:
4251 case Type::Vector:
4252 case Type::DependentVector:
4253 case Type::ExtVector:
4254 case Type::DependentSizedExtVector:
4255 case Type::ConstantMatrix:
4256 case Type::DependentSizedMatrix:
4257 case Type::DependentAddressSpace:
4258 case Type::ObjCObject:
4259 case Type::ObjCInterface:
4260 case Type::ObjCObjectPointer:
4261 case Type::Record:
4262 case Type::Enum:
4263 case Type::UnresolvedUsing:
4264 case Type::TypeOfExpr:
4265 case Type::TypeOf:
4266 case Type::Decltype:
4267 case Type::UnaryTransform:
4268 case Type::DependentName:
4269 case Type::InjectedClassName:
4270 case Type::TemplateSpecialization:
4271 case Type::TemplateTypeParm:
4272 case Type::SubstTemplateTypeParmPack:
4273 case Type::SubstBuiltinTemplatePack:
4274 case Type::Auto:
4275 case Type::DeducedTemplateSpecialization:
4276 case Type::PackExpansion:
4277 case Type::PackIndexing:
4278 case Type::BitInt:
4279 case Type::DependentBitInt:
4280 case Type::ArrayParameter:
4281 case Type::HLSLAttributedResource:
4282 case Type::HLSLInlineSpirv:
4283 llvm_unreachable("type should never be variably-modified");
4284
4285 // These types can be variably-modified but should never need to
4286 // further decay.
4287 case Type::FunctionNoProto:
4288 case Type::FunctionProto:
4289 case Type::BlockPointer:
4290 case Type::MemberPointer:
4291 case Type::Pipe:
4292 return type;
4293
4294 // These types can be variably-modified. All these modifications
4295 // preserve structure except as noted by comments.
4296 // TODO: if we ever care about optimizing VLAs, there are no-op
4297 // optimizations available here.
4298 case Type::Pointer:
4301 break;
4302
4303 case Type::LValueReference: {
4304 const auto *lv = cast<LValueReferenceType>(ty);
4305 result = getLValueReferenceType(
4306 getVariableArrayDecayedType(lv->getPointeeType()),
4307 lv->isSpelledAsLValue());
4308 break;
4309 }
4310
4311 case Type::RValueReference: {
4312 const auto *lv = cast<RValueReferenceType>(ty);
4313 result = getRValueReferenceType(
4314 getVariableArrayDecayedType(lv->getPointeeType()));
4315 break;
4316 }
4317
4318 case Type::Atomic: {
4319 const auto *at = cast<AtomicType>(ty);
4320 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4321 break;
4322 }
4323
4324 case Type::ConstantArray: {
4325 const auto *cat = cast<ConstantArrayType>(ty);
4326 result = getConstantArrayType(
4327 getVariableArrayDecayedType(cat->getElementType()),
4328 cat->getSize(),
4329 cat->getSizeExpr(),
4330 cat->getSizeModifier(),
4331 cat->getIndexTypeCVRQualifiers());
4332 break;
4333 }
4334
4335 case Type::DependentSizedArray: {
4336 const auto *dat = cast<DependentSizedArrayType>(ty);
4338 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4339 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4340 break;
4341 }
4342
4343 // Turn incomplete types into [*] types.
4344 case Type::IncompleteArray: {
4345 const auto *iat = cast<IncompleteArrayType>(ty);
4346 result =
4348 /*size*/ nullptr, ArraySizeModifier::Normal,
4349 iat->getIndexTypeCVRQualifiers());
4350 break;
4351 }
4352
4353 // Turn VLA types into [*] types.
4354 case Type::VariableArray: {
4355 const auto *vat = cast<VariableArrayType>(ty);
4356 result =
4358 /*size*/ nullptr, ArraySizeModifier::Star,
4359 vat->getIndexTypeCVRQualifiers());
4360 break;
4361 }
4362 }
4363
4364 // Apply the top-level qualifiers from the original.
4365 return getQualifiedType(result, split.Quals);
4366}
4367
4368/// getVariableArrayType - Returns a non-unique reference to the type for a
4369/// variable array of the specified element type.
4372 unsigned IndexTypeQuals) const {
4373 // Since we don't unique expressions, it isn't possible to unique VLA's
4374 // that have an expression provided for their size.
4375 QualType Canon;
4376
4377 // Be sure to pull qualifiers off the element type.
4378 // FIXME: Check below should look for qualifiers behind sugar.
4379 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4380 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4381 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4382 IndexTypeQuals);
4383 Canon = getQualifiedType(Canon, canonSplit.Quals);
4384 }
4385
4386 auto *New = new (*this, alignof(VariableArrayType))
4387 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4388
4389 VariableArrayTypes.push_back(New);
4390 Types.push_back(New);
4391 return QualType(New, 0);
4392}
4393
4394/// getDependentSizedArrayType - Returns a non-unique reference to
4395/// the type for a dependently-sized array of the specified element
4396/// type.
4400 unsigned elementTypeQuals) const {
4401 assert((!numElements || numElements->isTypeDependent() ||
4402 numElements->isValueDependent()) &&
4403 "Size must be type- or value-dependent!");
4404
4405 SplitQualType canonElementType = getCanonicalType(elementType).split();
4406
4407 void *insertPos = nullptr;
4408 llvm::FoldingSetNodeID ID;
4410 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4411 ASM, elementTypeQuals, numElements);
4412
4413 // Look for an existing type with these properties.
4414 DependentSizedArrayType *canonTy =
4415 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4416
4417 // Dependently-sized array types that do not have a specified number
4418 // of elements will have their sizes deduced from a dependent
4419 // initializer.
4420 if (!numElements) {
4421 if (canonTy)
4422 return QualType(canonTy, 0);
4423
4424 auto *newType = new (*this, alignof(DependentSizedArrayType))
4425 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4426 elementTypeQuals);
4427 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4428 Types.push_back(newType);
4429 return QualType(newType, 0);
4430 }
4431
4432 // If we don't have one, build one.
4433 if (!canonTy) {
4434 canonTy = new (*this, alignof(DependentSizedArrayType))
4435 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4436 numElements, ASM, elementTypeQuals);
4437 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4438 Types.push_back(canonTy);
4439 }
4440
4441 // Apply qualifiers from the element type to the array.
4442 QualType canon = getQualifiedType(QualType(canonTy,0),
4443 canonElementType.Quals);
4444
4445 // If we didn't need extra canonicalization for the element type or the size
4446 // expression, then just use that as our result.
4447 if (QualType(canonElementType.Ty, 0) == elementType &&
4448 canonTy->getSizeExpr() == numElements)
4449 return canon;
4450
4451 // Otherwise, we need to build a type which follows the spelling
4452 // of the element type.
4453 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4454 DependentSizedArrayType(elementType, canon, numElements, ASM,
4455 elementTypeQuals);
4456 Types.push_back(sugaredType);
4457 return QualType(sugaredType, 0);
4458}
4459
4462 unsigned elementTypeQuals) const {
4463 llvm::FoldingSetNodeID ID;
4464 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4465
4466 void *insertPos = nullptr;
4467 if (IncompleteArrayType *iat =
4468 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4469 return QualType(iat, 0);
4470
4471 // If the element type isn't canonical, this won't be a canonical type
4472 // either, so fill in the canonical type field. We also have to pull
4473 // qualifiers off the element type.
4474 QualType canon;
4475
4476 // FIXME: Check below should look for qualifiers behind sugar.
4477 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4478 SplitQualType canonSplit = getCanonicalType(elementType).split();
4479 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4480 ASM, elementTypeQuals);
4481 canon = getQualifiedType(canon, canonSplit.Quals);
4482
4483 // Get the new insert position for the node we care about.
4484 IncompleteArrayType *existing =
4485 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4486 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4487 }
4488
4489 auto *newType = new (*this, alignof(IncompleteArrayType))
4490 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4491
4492 IncompleteArrayTypes.InsertNode(newType, insertPos);
4493 Types.push_back(newType);
4494 return QualType(newType, 0);
4495}
4496
4499#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4500 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4501 NUMVECTORS};
4502
4503#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4504 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4505
4506 switch (Ty->getKind()) {
4507 default:
4508 llvm_unreachable("Unsupported builtin vector type");
4509
4510#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4511 ElBits, NF, IsSigned) \
4512 case BuiltinType::Id: \
4513 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4514 llvm::ElementCount::getScalable(NumEls), NF};
4515#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4516 ElBits, NF) \
4517 case BuiltinType::Id: \
4518 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4519 llvm::ElementCount::getScalable(NumEls), NF};
4520#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4521 ElBits, NF) \
4522 case BuiltinType::Id: \
4523 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4524#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4525 ElBits, NF) \
4526 case BuiltinType::Id: \
4527 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4528#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4529 case BuiltinType::Id: \
4530 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4531#include "clang/Basic/AArch64ACLETypes.def"
4532
4533#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4534 IsSigned) \
4535 case BuiltinType::Id: \
4536 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4537 llvm::ElementCount::getScalable(NumEls), NF};
4538#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4539 case BuiltinType::Id: \
4540 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4541 llvm::ElementCount::getScalable(NumEls), NF};
4542#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4543 case BuiltinType::Id: \
4544 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4545#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4546 case BuiltinType::Id: \
4547 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4548#include "clang/Basic/RISCVVTypes.def"
4549 }
4550}
4551
4552/// getExternrefType - Return a WebAssembly externref type, which represents an
4553/// opaque reference to a host value.
4555 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4556#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4557 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4558 return SingletonId;
4559#include "clang/Basic/WebAssemblyReferenceTypes.def"
4560 }
4561 llvm_unreachable(
4562 "shouldn't try to generate type externref outside WebAssembly target");
4563}
4564
4565/// getScalableVectorType - Return the unique reference to a scalable vector
4566/// type of the specified element type and size. VectorType must be a built-in
4567/// type.
4569 unsigned NumFields) const {
4570 if (Target->hasAArch64ACLETypes()) {
4571 uint64_t EltTySize = getTypeSize(EltTy);
4572
4573#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4574 ElBits, NF, IsSigned) \
4575 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4576 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4577 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4578 return SingletonId; \
4579 }
4580#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4581 ElBits, NF) \
4582 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4583 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4584 return SingletonId; \
4585 }
4586#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4587 ElBits, NF) \
4588 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4589 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4590 return SingletonId; \
4591 }
4592#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4593 ElBits, NF) \
4594 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4595 NumElts == (NumEls * NF) && NumFields == 1) { \
4596 return SingletonId; \
4597 }
4598#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4599 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4600 return SingletonId;
4601#include "clang/Basic/AArch64ACLETypes.def"
4602 } else if (Target->hasRISCVVTypes()) {
4603 uint64_t EltTySize = getTypeSize(EltTy);
4604#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4605 IsFP, IsBF) \
4606 if (!EltTy->isBooleanType() && \
4607 ((EltTy->hasIntegerRepresentation() && \
4608 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4609 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4610 IsFP && !IsBF) || \
4611 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4612 IsBF && !IsFP)) && \
4613 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4614 return SingletonId;
4615#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4616 if (EltTy->isBooleanType() && NumElts == NumEls) \
4617 return SingletonId;
4618#include "clang/Basic/RISCVVTypes.def"
4619 }
4620 return QualType();
4621}
4622
4623/// getVectorType - Return the unique reference to a vector type of
4624/// the specified element type and size. VectorType must be a built-in type.
4626 VectorKind VecKind) const {
4627 assert(vecType->isBuiltinType() ||
4628 (vecType->isBitIntType() &&
4629 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4630 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4631
4632 // Check if we've already instantiated a vector of this type.
4633 llvm::FoldingSetNodeID ID;
4634 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4635
4636 void *InsertPos = nullptr;
4637 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4638 return QualType(VTP, 0);
4639
4640 // If the element type isn't canonical, this won't be a canonical type either,
4641 // so fill in the canonical type field.
4642 QualType Canonical;
4643 if (!vecType.isCanonical()) {
4644 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4645
4646 // Get the new insert position for the node we care about.
4647 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4648 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4649 }
4650 auto *New = new (*this, alignof(VectorType))
4651 VectorType(vecType, NumElts, Canonical, VecKind);
4652 VectorTypes.InsertNode(New, InsertPos);
4653 Types.push_back(New);
4654 return QualType(New, 0);
4655}
4656
4658 SourceLocation AttrLoc,
4659 VectorKind VecKind) const {
4660 llvm::FoldingSetNodeID ID;
4661 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4662 VecKind);
4663 void *InsertPos = nullptr;
4664 DependentVectorType *Canon =
4665 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4667
4668 if (Canon) {
4669 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4670 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4671 } else {
4672 QualType CanonVecTy = getCanonicalType(VecType);
4673 if (CanonVecTy == VecType) {
4674 New = new (*this, alignof(DependentVectorType))
4675 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4676
4677 DependentVectorType *CanonCheck =
4678 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4679 assert(!CanonCheck &&
4680 "Dependent-sized vector_size canonical type broken");
4681 (void)CanonCheck;
4682 DependentVectorTypes.InsertNode(New, InsertPos);
4683 } else {
4684 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4685 SourceLocation(), VecKind);
4686 New = new (*this, alignof(DependentVectorType))
4687 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4688 }
4689 }
4690
4691 Types.push_back(New);
4692 return QualType(New, 0);
4693}
4694
4695/// getExtVectorType - Return the unique reference to an extended vector type of
4696/// the specified element type and size. VectorType must be a built-in type.
4698 unsigned NumElts) const {
4699 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4700 (vecType->isBitIntType() &&
4701 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4702 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4703
4704 // Check if we've already instantiated a vector of this type.
4705 llvm::FoldingSetNodeID ID;
4706 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4708 void *InsertPos = nullptr;
4709 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4710 return QualType(VTP, 0);
4711
4712 // If the element type isn't canonical, this won't be a canonical type either,
4713 // so fill in the canonical type field.
4714 QualType Canonical;
4715 if (!vecType.isCanonical()) {
4716 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4717
4718 // Get the new insert position for the node we care about.
4719 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4720 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4721 }
4722 auto *New = new (*this, alignof(ExtVectorType))
4723 ExtVectorType(vecType, NumElts, Canonical);
4724 VectorTypes.InsertNode(New, InsertPos);
4725 Types.push_back(New);
4726 return QualType(New, 0);
4727}
4728
4731 Expr *SizeExpr,
4732 SourceLocation AttrLoc) const {
4733 llvm::FoldingSetNodeID ID;
4735 SizeExpr);
4736
4737 void *InsertPos = nullptr;
4739 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4741 if (Canon) {
4742 // We already have a canonical version of this array type; use it as
4743 // the canonical type for a newly-built type.
4744 New = new (*this, alignof(DependentSizedExtVectorType))
4745 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4746 AttrLoc);
4747 } else {
4748 QualType CanonVecTy = getCanonicalType(vecType);
4749 if (CanonVecTy == vecType) {
4750 New = new (*this, alignof(DependentSizedExtVectorType))
4751 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4752
4753 DependentSizedExtVectorType *CanonCheck
4754 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4755 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4756 (void)CanonCheck;
4757 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4758 } else {
4759 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4760 SourceLocation());
4761 New = new (*this, alignof(DependentSizedExtVectorType))
4762 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4763 }
4764 }
4765
4766 Types.push_back(New);
4767 return QualType(New, 0);
4768}
4769
4771 unsigned NumColumns) const {
4772 llvm::FoldingSetNodeID ID;
4773 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4774 Type::ConstantMatrix);
4775
4776 assert(MatrixType::isValidElementType(ElementTy) &&
4777 "need a valid element type");
4778 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4780 "need valid matrix dimensions");
4781 void *InsertPos = nullptr;
4782 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4783 return QualType(MTP, 0);
4784
4785 QualType Canonical;
4786 if (!ElementTy.isCanonical()) {
4787 Canonical =
4788 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4789
4790 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4791 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4792 (void)NewIP;
4793 }
4794
4795 auto *New = new (*this, alignof(ConstantMatrixType))
4796 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4797 MatrixTypes.InsertNode(New, InsertPos);
4798 Types.push_back(New);
4799 return QualType(New, 0);
4800}
4801
4803 Expr *RowExpr,
4804 Expr *ColumnExpr,
4805 SourceLocation AttrLoc) const {
4806 QualType CanonElementTy = getCanonicalType(ElementTy);
4807 llvm::FoldingSetNodeID ID;
4808 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4809 ColumnExpr);
4810
4811 void *InsertPos = nullptr;
4813 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4814
4815 if (!Canon) {
4816 Canon = new (*this, alignof(DependentSizedMatrixType))
4817 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4818 ColumnExpr, AttrLoc);
4819#ifndef NDEBUG
4820 DependentSizedMatrixType *CanonCheck =
4821 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4822 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4823#endif
4824 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4825 Types.push_back(Canon);
4826 }
4827
4828 // Already have a canonical version of the matrix type
4829 //
4830 // If it exactly matches the requested type, use it directly.
4831 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4832 Canon->getRowExpr() == ColumnExpr)
4833 return QualType(Canon, 0);
4834
4835 // Use Canon as the canonical type for newly-built type.
4837 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4838 ColumnExpr, AttrLoc);
4839 Types.push_back(New);
4840 return QualType(New, 0);
4841}
4842
4844 Expr *AddrSpaceExpr,
4845 SourceLocation AttrLoc) const {
4846 assert(AddrSpaceExpr->isInstantiationDependent());
4847
4848 QualType canonPointeeType = getCanonicalType(PointeeType);
4849
4850 void *insertPos = nullptr;
4851 llvm::FoldingSetNodeID ID;
4852 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4853 AddrSpaceExpr);
4854
4855 DependentAddressSpaceType *canonTy =
4856 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4857
4858 if (!canonTy) {
4859 canonTy = new (*this, alignof(DependentAddressSpaceType))
4860 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4861 AttrLoc);
4862 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4863 Types.push_back(canonTy);
4864 }
4865
4866 if (canonPointeeType == PointeeType &&
4867 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4868 return QualType(canonTy, 0);
4869
4870 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4871 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4872 AddrSpaceExpr, AttrLoc);
4873 Types.push_back(sugaredType);
4874 return QualType(sugaredType, 0);
4875}
4876
4877/// Determine whether \p T is canonical as the result type of a function.
4879 return T.isCanonical() &&
4880 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4881 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4882}
4883
4884/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4885QualType
4887 const FunctionType::ExtInfo &Info) const {
4888 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4889 // functionality creates a function without a prototype regardless of
4890 // language mode (so it makes them even in C++). Once the rewriter has been
4891 // fixed, this assertion can be enabled again.
4892 //assert(!LangOpts.requiresStrictPrototypes() &&
4893 // "strict prototypes are disabled");
4894
4895 // Unique functions, to guarantee there is only one function of a particular
4896 // structure.
4897 llvm::FoldingSetNodeID ID;
4898 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4899
4900 void *InsertPos = nullptr;
4901 if (FunctionNoProtoType *FT =
4902 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4903 return QualType(FT, 0);
4904
4905 QualType Canonical;
4906 if (!isCanonicalResultType(ResultTy)) {
4907 Canonical =
4909
4910 // Get the new insert position for the node we care about.
4911 FunctionNoProtoType *NewIP =
4912 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4913 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4914 }
4915
4916 auto *New = new (*this, alignof(FunctionNoProtoType))
4917 FunctionNoProtoType(ResultTy, Canonical, Info);
4918 Types.push_back(New);
4919 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4920 return QualType(New, 0);
4921}
4922
4925 CanQualType CanResultType = getCanonicalType(ResultType);
4926
4927 // Canonical result types do not have ARC lifetime qualifiers.
4928 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4929 Qualifiers Qs = CanResultType.getQualifiers();
4930 Qs.removeObjCLifetime();
4932 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4933 }
4934
4935 return CanResultType;
4936}
4937
4939 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4940 if (ESI.Type == EST_None)
4941 return true;
4942 if (!NoexceptInType)
4943 return false;
4944
4945 // C++17 onwards: exception specification is part of the type, as a simple
4946 // boolean "can this function type throw".
4947 if (ESI.Type == EST_BasicNoexcept)
4948 return true;
4949
4950 // A noexcept(expr) specification is (possibly) canonical if expr is
4951 // value-dependent.
4952 if (ESI.Type == EST_DependentNoexcept)
4953 return true;
4954
4955 // A dynamic exception specification is canonical if it only contains pack
4956 // expansions (so we can't tell whether it's non-throwing) and all its
4957 // contained types are canonical.
4958 if (ESI.Type == EST_Dynamic) {
4959 bool AnyPackExpansions = false;
4960 for (QualType ET : ESI.Exceptions) {
4961 if (!ET.isCanonical())
4962 return false;
4963 if (ET->getAs<PackExpansionType>())
4964 AnyPackExpansions = true;
4965 }
4966 return AnyPackExpansions;
4967 }
4968
4969 return false;
4970}
4971
4972QualType ASTContext::getFunctionTypeInternal(
4973 QualType ResultTy, ArrayRef<QualType> ArgArray,
4974 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4975 size_t NumArgs = ArgArray.size();
4976
4977 // Unique functions, to guarantee there is only one function of a particular
4978 // structure.
4979 llvm::FoldingSetNodeID ID;
4980 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4981 *this, true);
4982
4983 QualType Canonical;
4984 bool Unique = false;
4985
4986 void *InsertPos = nullptr;
4987 if (FunctionProtoType *FPT =
4988 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4989 QualType Existing = QualType(FPT, 0);
4990
4991 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4992 // it so long as our exception specification doesn't contain a dependent
4993 // noexcept expression, or we're just looking for a canonical type.
4994 // Otherwise, we're going to need to create a type
4995 // sugar node to hold the concrete expression.
4996 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4997 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4998 return Existing;
4999
5000 // We need a new type sugar node for this one, to hold the new noexcept
5001 // expression. We do no canonicalization here, but that's OK since we don't
5002 // expect to see the same noexcept expression much more than once.
5003 Canonical = getCanonicalType(Existing);
5004 Unique = true;
5005 }
5006
5007 bool NoexceptInType = getLangOpts().CPlusPlus17;
5008 bool IsCanonicalExceptionSpec =
5010
5011 // Determine whether the type being created is already canonical or not.
5012 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5013 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5014 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5015 if (!ArgArray[i].isCanonicalAsParam())
5016 isCanonical = false;
5017
5018 if (OnlyWantCanonical)
5019 assert(isCanonical &&
5020 "given non-canonical parameters constructing canonical type");
5021
5022 // If this type isn't canonical, get the canonical version of it if we don't
5023 // already have it. The exception spec is only partially part of the
5024 // canonical type, and only in C++17 onwards.
5025 if (!isCanonical && Canonical.isNull()) {
5026 SmallVector<QualType, 16> CanonicalArgs;
5027 CanonicalArgs.reserve(NumArgs);
5028 for (unsigned i = 0; i != NumArgs; ++i)
5029 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5030
5031 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5032 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5033 CanonicalEPI.HasTrailingReturn = false;
5034
5035 if (IsCanonicalExceptionSpec) {
5036 // Exception spec is already OK.
5037 } else if (NoexceptInType) {
5038 switch (EPI.ExceptionSpec.Type) {
5040 // We don't know yet. It shouldn't matter what we pick here; no-one
5041 // should ever look at this.
5042 [[fallthrough]];
5043 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5044 CanonicalEPI.ExceptionSpec.Type = EST_None;
5045 break;
5046
5047 // A dynamic exception specification is almost always "not noexcept",
5048 // with the exception that a pack expansion might expand to no types.
5049 case EST_Dynamic: {
5050 bool AnyPacks = false;
5051 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5052 if (ET->getAs<PackExpansionType>())
5053 AnyPacks = true;
5054 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5055 }
5056 if (!AnyPacks)
5057 CanonicalEPI.ExceptionSpec.Type = EST_None;
5058 else {
5059 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5060 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5061 }
5062 break;
5063 }
5064
5065 case EST_DynamicNone:
5066 case EST_BasicNoexcept:
5067 case EST_NoexceptTrue:
5068 case EST_NoThrow:
5069 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5070 break;
5071
5073 llvm_unreachable("dependent noexcept is already canonical");
5074 }
5075 } else {
5076 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5077 }
5078
5079 // Adjust the canonical function result type.
5080 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5081 Canonical =
5082 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5083
5084 // Get the new insert position for the node we care about.
5085 FunctionProtoType *NewIP =
5086 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5087 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5088 }
5089
5090 // Compute the needed size to hold this FunctionProtoType and the
5091 // various trailing objects.
5092 auto ESH = FunctionProtoType::getExceptionSpecSize(
5093 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5094 size_t Size = FunctionProtoType::totalSizeToAlloc<
5095 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5096 FunctionType::FunctionTypeExtraAttributeInfo,
5097 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5098 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5099 FunctionEffect, EffectConditionExpr>(
5102 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5103 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5104 EPI.ExtParameterInfos ? NumArgs : 0,
5106 EPI.FunctionEffects.conditions().size());
5107
5108 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5109 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5110 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5111 Types.push_back(FTP);
5112 if (!Unique)
5113 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5114 if (!EPI.FunctionEffects.empty())
5115 AnyFunctionEffects = true;
5116 return QualType(FTP, 0);
5117}
5118
5119QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5120 llvm::FoldingSetNodeID ID;
5121 PipeType::Profile(ID, T, ReadOnly);
5122
5123 void *InsertPos = nullptr;
5124 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5125 return QualType(PT, 0);
5126
5127 // If the pipe element type isn't canonical, this won't be a canonical type
5128 // either, so fill in the canonical type field.
5129 QualType Canonical;
5130 if (!T.isCanonical()) {
5131 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5132
5133 // Get the new insert position for the node we care about.
5134 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5135 assert(!NewIP && "Shouldn't be in the map!");
5136 (void)NewIP;
5137 }
5138 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5139 Types.push_back(New);
5140 PipeTypes.InsertNode(New, InsertPos);
5141 return QualType(New, 0);
5142}
5143
5145 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5146 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5147 : Ty;
5148}
5149
5151 return getPipeType(T, true);
5152}
5153
5155 return getPipeType(T, false);
5156}
5157
5158QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5159 llvm::FoldingSetNodeID ID;
5160 BitIntType::Profile(ID, IsUnsigned, NumBits);
5161
5162 void *InsertPos = nullptr;
5163 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5164 return QualType(EIT, 0);
5165
5166 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5167 BitIntTypes.InsertNode(New, InsertPos);
5168 Types.push_back(New);
5169 return QualType(New, 0);
5170}
5171
5173 Expr *NumBitsExpr) const {
5174 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5175 llvm::FoldingSetNodeID ID;
5176 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5177
5178 void *InsertPos = nullptr;
5179 if (DependentBitIntType *Existing =
5180 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5181 return QualType(Existing, 0);
5182
5183 auto *New = new (*this, alignof(DependentBitIntType))
5184 DependentBitIntType(IsUnsigned, NumBitsExpr);
5185 DependentBitIntTypes.InsertNode(New, InsertPos);
5186
5187 Types.push_back(New);
5188 return QualType(New, 0);
5189}
5190
5193 using Kind = PredefinedSugarType::Kind;
5194
5195 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5196 Target != nullptr)
5197 return QualType(Target, 0);
5198
5199 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5200 switch (KDI) {
5201 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5202 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5203 // are part of the core language and are widely used. Using
5204 // PredefinedSugarType makes these types as named sugar types rather than
5205 // standard integer types, enabling better hints and diagnostics.
5206 case Kind::SizeT:
5207 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5208 case Kind::SignedSizeT:
5209 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5210 case Kind::PtrdiffT:
5211 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5212 }
5213 llvm_unreachable("unexpected kind");
5214 };
5215 auto *New = new (*this, alignof(PredefinedSugarType))
5216 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5217 getCanonicalType(*this, static_cast<Kind>(KD)));
5218 Types.push_back(New);
5219 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5220 return QualType(New, 0);
5221}
5222
5224 NestedNameSpecifier Qualifier,
5225 const TypeDecl *Decl) const {
5226 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5227 return getTagType(Keyword, Qualifier, Tag,
5228 /*OwnsTag=*/false);
5229 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5230 return getTypedefType(Keyword, Qualifier, Typedef);
5231 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5232 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5233
5235 assert(!Qualifier);
5236 return QualType(Decl->TypeForDecl, 0);
5237}
5238
5240 if (auto *Tag = dyn_cast<TagDecl>(TD))
5241 return getCanonicalTagType(Tag);
5242 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5243 return getCanonicalType(TN->getUnderlyingType());
5244 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5246 assert(TD->TypeForDecl);
5247 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5248}
5249
5251 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5252 return getCanonicalTagType(TD);
5253 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5254 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5256 /*Qualifier=*/std::nullopt, TD);
5257 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5258 return getCanonicalUnresolvedUsingType(Using);
5259
5260 assert(Decl->TypeForDecl);
5261 return QualType(Decl->TypeForDecl, 0);
5262}
5263
5264/// getTypedefType - Return the unique reference to the type for the
5265/// specified typedef name decl.
5268 NestedNameSpecifier Qualifier,
5269 const TypedefNameDecl *Decl, QualType UnderlyingType,
5270 std::optional<bool> TypeMatchesDeclOrNone) const {
5271 if (!TypeMatchesDeclOrNone) {
5272 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5273 assert(!DeclUnderlyingType.isNull());
5274 if (UnderlyingType.isNull())
5275 UnderlyingType = DeclUnderlyingType;
5276 else
5277 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5278 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5279 } else {
5280 // FIXME: This is a workaround for a serialization cycle: assume the decl
5281 // underlying type is not available; don't touch it.
5282 assert(!UnderlyingType.isNull());
5283 }
5284
5285 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5286 *TypeMatchesDeclOrNone) {
5287 if (Decl->TypeForDecl)
5288 return QualType(Decl->TypeForDecl, 0);
5289
5290 auto *NewType = new (*this, alignof(TypedefType))
5291 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5292 !*TypeMatchesDeclOrNone);
5293
5294 Types.push_back(NewType);
5295 Decl->TypeForDecl = NewType;
5296 return QualType(NewType, 0);
5297 }
5298
5299 llvm::FoldingSetNodeID ID;
5300 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5301 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5302
5303 void *InsertPos = nullptr;
5304 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5305 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5306 return QualType(Placeholder->getType(), 0);
5307
5308 void *Mem =
5309 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5311 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5312 alignof(TypedefType));
5313 auto *NewType =
5314 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5315 UnderlyingType, !*TypeMatchesDeclOrNone);
5316 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5318 TypedefTypes.InsertNode(Placeholder, InsertPos);
5319 Types.push_back(NewType);
5320 return QualType(NewType, 0);
5321}
5322
5324 NestedNameSpecifier Qualifier,
5325 const UsingShadowDecl *D,
5326 QualType UnderlyingType) const {
5327 // FIXME: This is expensive to compute every time!
5328 if (UnderlyingType.isNull()) {
5329 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5330 UnderlyingType =
5333 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5334 }
5335
5336 llvm::FoldingSetNodeID ID;
5337 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5338
5339 void *InsertPos = nullptr;
5340 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5341 return QualType(T, 0);
5342
5343 assert(!UnderlyingType.hasLocalQualifiers());
5344
5345 assert(
5347 UnderlyingType));
5348
5349 void *Mem =
5350 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5351 alignof(UsingType));
5352 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5353 Types.push_back(T);
5354 UsingTypes.InsertNode(T, InsertPos);
5355 return QualType(T, 0);
5356}
5357
5358TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5359 NestedNameSpecifier Qualifier,
5360 const TagDecl *TD, bool OwnsTag,
5361 bool IsInjected,
5362 const Type *CanonicalType,
5363 bool WithFoldingSetNode) const {
5364 auto [TC, Size] = [&] {
5365 switch (TD->getDeclKind()) {
5366 case Decl::Enum:
5367 static_assert(alignof(EnumType) == alignof(TagType));
5368 return std::make_tuple(Type::Enum, sizeof(EnumType));
5369 case Decl::ClassTemplatePartialSpecialization:
5370 case Decl::ClassTemplateSpecialization:
5371 case Decl::CXXRecord:
5372 static_assert(alignof(RecordType) == alignof(TagType));
5373 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5374 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5375 return std::make_tuple(Type::InjectedClassName,
5376 sizeof(InjectedClassNameType));
5377 [[fallthrough]];
5378 case Decl::Record:
5379 return std::make_tuple(Type::Record, sizeof(RecordType));
5380 default:
5381 llvm_unreachable("unexpected decl kind");
5382 }
5383 }();
5384
5385 if (Qualifier) {
5386 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5387 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5388 sizeof(NestedNameSpecifier);
5389 }
5390 void *Mem;
5391 if (WithFoldingSetNode) {
5392 // FIXME: It would be more profitable to tail allocate the folding set node
5393 // from the type, instead of the other way around, due to the greater
5394 // alignment requirements of the type. But this makes it harder to deal with
5395 // the different type node sizes. This would require either uniquing from
5396 // different folding sets, or having the folding setaccept a
5397 // contextual parameter which is not fixed at construction.
5398 Mem = Allocate(
5399 sizeof(TagTypeFoldingSetPlaceholder) +
5400 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5401 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5402 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5403 Mem = T->getTagType();
5404 } else {
5405 Mem = Allocate(Size, alignof(TagType));
5406 }
5407
5408 auto *T = [&, TC = TC]() -> TagType * {
5409 switch (TC) {
5410 case Type::Enum: {
5411 assert(isa<EnumDecl>(TD));
5412 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5413 IsInjected, CanonicalType);
5414 assert(reinterpret_cast<void *>(T) ==
5415 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5416 "TagType must be the first base of EnumType");
5417 return T;
5418 }
5419 case Type::Record: {
5420 assert(isa<RecordDecl>(TD));
5421 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5422 IsInjected, CanonicalType);
5423 assert(reinterpret_cast<void *>(T) ==
5424 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5425 "TagType must be the first base of RecordType");
5426 return T;
5427 }
5428 case Type::InjectedClassName: {
5429 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5430 IsInjected, CanonicalType);
5431 assert(reinterpret_cast<void *>(T) ==
5432 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5433 "TagType must be the first base of InjectedClassNameType");
5434 return T;
5435 }
5436 default:
5437 llvm_unreachable("unexpected type class");
5438 }
5439 }();
5440 assert(T->getKeyword() == Keyword);
5441 assert(T->getQualifier() == Qualifier);
5442 assert(T->getOriginalDecl() == TD);
5443 assert(T->isInjected() == IsInjected);
5444 assert(T->isTagOwned() == OwnsTag);
5445 assert((T->isCanonicalUnqualified()
5446 ? QualType()
5447 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5448 Types.push_back(T);
5449 return T;
5450}
5451
5452static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5453 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5454 RD && RD->isInjectedClassName())
5455 return cast<TagDecl>(RD->getDeclContext());
5456 return TD;
5457}
5458
5461 if (TD->TypeForDecl)
5462 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5463
5464 const Type *CanonicalType = getTagTypeInternal(
5466 /*Qualifier=*/std::nullopt, TD,
5467 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5468 /*WithFoldingSetNode=*/false);
5469 TD->TypeForDecl = CanonicalType;
5470 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5471}
5472
5474 NestedNameSpecifier Qualifier,
5475 const TagDecl *TD, bool OwnsTag) const {
5476
5477 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5478 bool IsInjected = TD != NonInjectedTD;
5479
5480 ElaboratedTypeKeyword PreferredKeyword =
5483 NonInjectedTD->getTagKind());
5484
5485 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5486 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5487 return QualType(T, 0);
5488
5489 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5490 const Type *T =
5491 getTagTypeInternal(Keyword,
5492 /*Qualifier=*/std::nullopt, NonInjectedTD,
5493 /*OwnsTag=*/false, IsInjected, CanonicalType,
5494 /*WithFoldingSetNode=*/false);
5495 TD->TypeForDecl = T;
5496 return QualType(T, 0);
5497 }
5498
5499 llvm::FoldingSetNodeID ID;
5500 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5501 OwnsTag, IsInjected);
5502
5503 void *InsertPos = nullptr;
5504 if (TagTypeFoldingSetPlaceholder *T =
5505 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5506 return QualType(T->getTagType(), 0);
5507
5508 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5509 TagType *T =
5510 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5511 CanonicalType, /*WithFoldingSetNode=*/true);
5512 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5513 return QualType(T, 0);
5514}
5515
5516bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5517 unsigned NumPositiveBits,
5518 QualType &BestType,
5519 QualType &BestPromotionType) {
5520 unsigned IntWidth = Target->getIntWidth();
5521 unsigned CharWidth = Target->getCharWidth();
5522 unsigned ShortWidth = Target->getShortWidth();
5523 bool EnumTooLarge = false;
5524 unsigned BestWidth;
5525 if (NumNegativeBits) {
5526 // If there is a negative value, figure out the smallest integer type (of
5527 // int/long/longlong) that fits.
5528 // If it's packed, check also if it fits a char or a short.
5529 if (IsPacked && NumNegativeBits <= CharWidth &&
5530 NumPositiveBits < CharWidth) {
5531 BestType = SignedCharTy;
5532 BestWidth = CharWidth;
5533 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5534 NumPositiveBits < ShortWidth) {
5535 BestType = ShortTy;
5536 BestWidth = ShortWidth;
5537 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5538 BestType = IntTy;
5539 BestWidth = IntWidth;
5540 } else {
5541 BestWidth = Target->getLongWidth();
5542
5543 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5544 BestType = LongTy;
5545 } else {
5546 BestWidth = Target->getLongLongWidth();
5547
5548 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5549 EnumTooLarge = true;
5550 BestType = LongLongTy;
5551 }
5552 }
5553 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5554 } else {
5555 // If there is no negative value, figure out the smallest type that fits
5556 // all of the enumerator values.
5557 // If it's packed, check also if it fits a char or a short.
5558 if (IsPacked && NumPositiveBits <= CharWidth) {
5559 BestType = UnsignedCharTy;
5560 BestPromotionType = IntTy;
5561 BestWidth = CharWidth;
5562 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5563 BestType = UnsignedShortTy;
5564 BestPromotionType = IntTy;
5565 BestWidth = ShortWidth;
5566 } else if (NumPositiveBits <= IntWidth) {
5567 BestType = UnsignedIntTy;
5568 BestWidth = IntWidth;
5569 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5571 : IntTy;
5572 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5573 BestType = UnsignedLongTy;
5574 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5576 : LongTy;
5577 } else {
5578 BestWidth = Target->getLongLongWidth();
5579 if (NumPositiveBits > BestWidth) {
5580 // This can happen with bit-precise integer types, but those are not
5581 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5582 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5583 // a 128-bit integer, we should consider doing the same.
5584 EnumTooLarge = true;
5585 }
5586 BestType = UnsignedLongLongTy;
5587 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5589 : LongLongTy;
5590 }
5591 }
5592 return EnumTooLarge;
5593}
5594
5596 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5597 "Integral type required!");
5598 unsigned BitWidth = getIntWidth(T);
5599
5600 if (Value.isUnsigned() || Value.isNonNegative()) {
5601 if (T->isSignedIntegerOrEnumerationType())
5602 --BitWidth;
5603 return Value.getActiveBits() <= BitWidth;
5604 }
5605 return Value.getSignificantBits() <= BitWidth;
5606}
5607
5608UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5610 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5611 const Type *CanonicalType) const {
5612 void *Mem = Allocate(
5613 UnresolvedUsingType::totalSizeToAlloc<
5615 !!InsertPos, !!Qualifier),
5616 alignof(UnresolvedUsingType));
5617 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5618 if (InsertPos) {
5619 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5621 TypedefTypes.InsertNode(Placeholder, InsertPos);
5622 }
5623 Types.push_back(T);
5624 return T;
5625}
5626
5628 const UnresolvedUsingTypenameDecl *D) const {
5629 D = D->getCanonicalDecl();
5630 if (D->TypeForDecl)
5631 return D->TypeForDecl->getCanonicalTypeUnqualified();
5632
5633 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5635 /*Qualifier=*/std::nullopt, D,
5636 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5637 D->TypeForDecl = CanonicalType;
5638 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5639}
5640
5643 NestedNameSpecifier Qualifier,
5644 const UnresolvedUsingTypenameDecl *D) const {
5645 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5646 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5647 return QualType(T, 0);
5648
5649 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5650 const Type *T =
5651 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5652 /*Qualifier=*/std::nullopt, D,
5653 /*InsertPos=*/nullptr, CanonicalType);
5654 D->TypeForDecl = T;
5655 return QualType(T, 0);
5656 }
5657
5658 llvm::FoldingSetNodeID ID;
5659 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5660
5661 void *InsertPos = nullptr;
5663 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5664 return QualType(Placeholder->getType(), 0);
5665 assert(InsertPos);
5666
5667 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5668 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5669 InsertPos, CanonicalType);
5670 return QualType(T, 0);
5671}
5672
5674 QualType modifiedType,
5675 QualType equivalentType,
5676 const Attr *attr) const {
5677 llvm::FoldingSetNodeID id;
5678 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5679
5680 void *insertPos = nullptr;
5681 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5682 if (type) return QualType(type, 0);
5683
5684 assert(!attr || attr->getKind() == attrKind);
5685
5686 QualType canon = getCanonicalType(equivalentType);
5687 type = new (*this, alignof(AttributedType))
5688 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5689
5690 Types.push_back(type);
5691 AttributedTypes.InsertNode(type, insertPos);
5692
5693 return QualType(type, 0);
5694}
5695
5697 QualType equivalentType) const {
5698 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5699}
5700
5702 QualType modifiedType,
5703 QualType equivalentType) {
5704 switch (nullability) {
5706 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5707
5709 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5710
5712 return getAttributedType(attr::TypeNullableResult, modifiedType,
5713 equivalentType);
5714
5716 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5717 equivalentType);
5718 }
5719
5720 llvm_unreachable("Unknown nullability kind");
5721}
5722
5723QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5724 QualType Wrapped) const {
5725 llvm::FoldingSetNodeID ID;
5726 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5727
5728 void *InsertPos = nullptr;
5729 BTFTagAttributedType *Ty =
5730 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5731 if (Ty)
5732 return QualType(Ty, 0);
5733
5734 QualType Canon = getCanonicalType(Wrapped);
5735 Ty = new (*this, alignof(BTFTagAttributedType))
5736 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5737
5738 Types.push_back(Ty);
5739 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5740
5741 return QualType(Ty, 0);
5742}
5743
5745 QualType Wrapped, QualType Contained,
5746 const HLSLAttributedResourceType::Attributes &Attrs) {
5747
5748 llvm::FoldingSetNodeID ID;
5749 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5750
5751 void *InsertPos = nullptr;
5752 HLSLAttributedResourceType *Ty =
5753 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5754 if (Ty)
5755 return QualType(Ty, 0);
5756
5757 Ty = new (*this, alignof(HLSLAttributedResourceType))
5758 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5759
5760 Types.push_back(Ty);
5761 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5762
5763 return QualType(Ty, 0);
5764}
5765
5766QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5767 uint32_t Alignment,
5768 ArrayRef<SpirvOperand> Operands) {
5769 llvm::FoldingSetNodeID ID;
5770 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5771
5772 void *InsertPos = nullptr;
5773 HLSLInlineSpirvType *Ty =
5774 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5775 if (Ty)
5776 return QualType(Ty, 0);
5777
5778 void *Mem = Allocate(
5779 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5780 alignof(HLSLInlineSpirvType));
5781
5782 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5783
5784 Types.push_back(Ty);
5785 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5786
5787 return QualType(Ty, 0);
5788}
5789
5790/// Retrieve a substitution-result type.
5792 Decl *AssociatedDecl,
5793 unsigned Index,
5794 UnsignedOrNone PackIndex,
5795 bool Final) const {
5796 llvm::FoldingSetNodeID ID;
5797 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5798 PackIndex, Final);
5799 void *InsertPos = nullptr;
5800 SubstTemplateTypeParmType *SubstParm =
5801 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5802
5803 if (!SubstParm) {
5804 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5805 !Replacement.isCanonical()),
5806 alignof(SubstTemplateTypeParmType));
5807 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5808 Index, PackIndex, Final);
5809 Types.push_back(SubstParm);
5810 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5811 }
5812
5813 return QualType(SubstParm, 0);
5814}
5815
5818 unsigned Index, bool Final,
5819 const TemplateArgument &ArgPack) {
5820#ifndef NDEBUG
5821 for (const auto &P : ArgPack.pack_elements())
5822 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5823#endif
5824
5825 llvm::FoldingSetNodeID ID;
5826 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5827 ArgPack);
5828 void *InsertPos = nullptr;
5829 if (SubstTemplateTypeParmPackType *SubstParm =
5830 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5831 return QualType(SubstParm, 0);
5832
5833 QualType Canon;
5834 {
5835 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5836 if (!AssociatedDecl->isCanonicalDecl() ||
5837 !CanonArgPack.structurallyEquals(ArgPack)) {
5839 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5840 [[maybe_unused]] const auto *Nothing =
5841 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5842 assert(!Nothing);
5843 }
5844 }
5845
5846 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5847 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5848 ArgPack);
5849 Types.push_back(SubstParm);
5850 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5851 return QualType(SubstParm, 0);
5852}
5853
5856 assert(llvm::all_of(ArgPack.pack_elements(),
5857 [](const auto &P) {
5858 return P.getKind() == TemplateArgument::Type;
5859 }) &&
5860 "Pack contains a non-type");
5861
5862 llvm::FoldingSetNodeID ID;
5863 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5864
5865 void *InsertPos = nullptr;
5866 if (auto *T =
5867 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5868 return QualType(T, 0);
5869
5870 QualType Canon;
5871 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5872 if (!CanonArgPack.structurallyEquals(ArgPack))
5873 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5874
5875 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5876 SubstBuiltinTemplatePackType(Canon, ArgPack);
5877 Types.push_back(PackType);
5878 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5879 return QualType(PackType, 0);
5880}
5881
5882/// Retrieve the template type parameter type for a template
5883/// parameter or parameter pack with the given depth, index, and (optionally)
5884/// name.
5885QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5886 bool ParameterPack,
5887 TemplateTypeParmDecl *TTPDecl) const {
5888 llvm::FoldingSetNodeID ID;
5889 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5890 void *InsertPos = nullptr;
5891 TemplateTypeParmType *TypeParm
5892 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5893
5894 if (TypeParm)
5895 return QualType(TypeParm, 0);
5896
5897 if (TTPDecl) {
5898 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5899 TypeParm = new (*this, alignof(TemplateTypeParmType))
5900 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5901
5902 TemplateTypeParmType *TypeCheck
5903 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5904 assert(!TypeCheck && "Template type parameter canonical type broken");
5905 (void)TypeCheck;
5906 } else
5907 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5908 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5909
5910 Types.push_back(TypeParm);
5911 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5912
5913 return QualType(TypeParm, 0);
5914}
5915
5918 switch (Keyword) {
5919 // These are just themselves.
5925 return Keyword;
5926
5927 // These are equivalent.
5930
5931 // These are functionally equivalent, so relying on their equivalence is
5932 // IFNDR. By making them equivalent, we disallow overloading, which at least
5933 // can produce a diagnostic.
5936 }
5937 llvm_unreachable("unexpected keyword kind");
5938}
5939
5941 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5942 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5943 TemplateName Name, SourceLocation NameLoc,
5944 const TemplateArgumentListInfo &SpecifiedArgs,
5945 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5947 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5948
5951 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5952 SpecifiedArgs);
5953 return DI;
5954}
5955
5958 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5959 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5960 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5961 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5962 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5963 SpecifiedArgVec.push_back(Arg.getArgument());
5964
5965 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5966 CanonicalArgs, Underlying);
5967}
5968
5969[[maybe_unused]] static bool
5971 for (const TemplateArgument &Arg : Args)
5972 if (Arg.isPackExpansion())
5973 return true;
5974 return false;
5975}
5976
5979 ArrayRef<TemplateArgument> Args) const {
5980 assert(Template ==
5981 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5983 Template.getAsDependentTemplateName()));
5984#ifndef NDEBUG
5985 for (const auto &Arg : Args)
5986 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5987#endif
5988
5989 llvm::FoldingSetNodeID ID;
5990 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
5991 *this);
5992 void *InsertPos = nullptr;
5993 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5994 return QualType(T, 0);
5995
5996 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
5997 sizeof(TemplateArgument) * Args.size(),
5998 alignof(TemplateSpecializationType));
5999 auto *Spec =
6000 new (Mem) TemplateSpecializationType(Keyword, Template,
6001 /*IsAlias=*/false, Args, QualType());
6002 assert(Spec->isDependentType() &&
6003 "canonical template specialization must be dependent");
6004 Types.push_back(Spec);
6005 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6006 return QualType(Spec, 0);
6007}
6008
6011 ArrayRef<TemplateArgument> SpecifiedArgs,
6012 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6013 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6014 bool IsTypeAlias = TD && TD->isTypeAlias();
6015 if (Underlying.isNull()) {
6016 TemplateName CanonTemplate =
6017 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6018 ElaboratedTypeKeyword CanonKeyword =
6019 CanonTemplate.getAsDependentTemplateName()
6022 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6024 if (CanonicalArgs.empty()) {
6025 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6026 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6027 CanonicalArgs = CanonArgsVec;
6028 } else {
6029 NonCanonical |= !llvm::equal(
6030 SpecifiedArgs, CanonicalArgs,
6031 [](const TemplateArgument &A, const TemplateArgument &B) {
6032 return A.structurallyEquals(B);
6033 });
6034 }
6035
6036 // We can get here with an alias template when the specialization
6037 // contains a pack expansion that does not match up with a parameter
6038 // pack, or a builtin template which cannot be resolved due to dependency.
6039 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6040 hasAnyPackExpansions(CanonicalArgs)) &&
6041 "Caller must compute aliased type");
6042 IsTypeAlias = false;
6043
6045 CanonKeyword, CanonTemplate, CanonicalArgs);
6046 if (!NonCanonical)
6047 return Underlying;
6048 }
6049 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6050 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6051 (IsTypeAlias ? sizeof(QualType) : 0),
6052 alignof(TemplateSpecializationType));
6053 auto *Spec = new (Mem) TemplateSpecializationType(
6054 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6055 Types.push_back(Spec);
6056 return QualType(Spec, 0);
6057}
6058
6061 llvm::FoldingSetNodeID ID;
6062 ParenType::Profile(ID, InnerType);
6063
6064 void *InsertPos = nullptr;
6065 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6066 if (T)
6067 return QualType(T, 0);
6068
6069 QualType Canon = InnerType;
6070 if (!Canon.isCanonical()) {
6071 Canon = getCanonicalType(InnerType);
6072 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6073 assert(!CheckT && "Paren canonical type broken");
6074 (void)CheckT;
6075 }
6076
6077 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6078 Types.push_back(T);
6079 ParenTypes.InsertNode(T, InsertPos);
6080 return QualType(T, 0);
6081}
6082
6085 const IdentifierInfo *MacroII) const {
6086 QualType Canon = UnderlyingTy;
6087 if (!Canon.isCanonical())
6088 Canon = getCanonicalType(UnderlyingTy);
6089
6090 auto *newType = new (*this, alignof(MacroQualifiedType))
6091 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6092 Types.push_back(newType);
6093 return QualType(newType, 0);
6094}
6095
6098 const IdentifierInfo *Name) const {
6099 llvm::FoldingSetNodeID ID;
6100 DependentNameType::Profile(ID, Keyword, NNS, Name);
6101
6102 void *InsertPos = nullptr;
6103 if (DependentNameType *T =
6104 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6105 return QualType(T, 0);
6106
6107 ElaboratedTypeKeyword CanonKeyword =
6109 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6110
6111 QualType Canon;
6112 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6113 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6114 [[maybe_unused]] DependentNameType *T =
6115 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6116 assert(!T && "broken canonicalization");
6117 assert(Canon.isCanonical());
6118 }
6119
6120 DependentNameType *T = new (*this, alignof(DependentNameType))
6121 DependentNameType(Keyword, NNS, Name, Canon);
6122 Types.push_back(T);
6123 DependentNameTypes.InsertNode(T, InsertPos);
6124 return QualType(T, 0);
6125}
6126
6128 TemplateArgument Arg;
6129 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6131 if (TTP->isParameterPack())
6132 ArgType = getPackExpansionType(ArgType, std::nullopt);
6133
6135 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6136 QualType T =
6137 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6138 // For class NTTPs, ensure we include the 'const' so the type matches that
6139 // of a real template argument.
6140 // FIXME: It would be more faithful to model this as something like an
6141 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6143 if (T->isRecordType()) {
6144 // C++ [temp.param]p8: An id-expression naming a non-type
6145 // template-parameter of class type T denotes a static storage duration
6146 // object of type const T.
6147 T.addConst();
6148 VK = VK_LValue;
6149 } else {
6150 VK = Expr::getValueKindForType(NTTP->getType());
6151 }
6152 Expr *E = new (*this)
6153 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6154 T, VK, NTTP->getLocation());
6155
6156 if (NTTP->isParameterPack())
6157 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6158 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6159 } else {
6160 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6162 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6163 TemplateName(TTP));
6164 if (TTP->isParameterPack())
6165 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6166 else
6167 Arg = TemplateArgument(Name);
6168 }
6169
6170 if (Param->isTemplateParameterPack())
6171 Arg =
6172 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6173
6174 return Arg;
6175}
6176
6178 UnsignedOrNone NumExpansions,
6179 bool ExpectPackInType) const {
6180 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6181 "Pack expansions must expand one or more parameter packs");
6182
6183 llvm::FoldingSetNodeID ID;
6184 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6185
6186 void *InsertPos = nullptr;
6187 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6188 if (T)
6189 return QualType(T, 0);
6190
6191 QualType Canon;
6192 if (!Pattern.isCanonical()) {
6193 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6194 /*ExpectPackInType=*/false);
6195
6196 // Find the insert position again, in case we inserted an element into
6197 // PackExpansionTypes and invalidated our insert position.
6198 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6199 }
6200
6201 T = new (*this, alignof(PackExpansionType))
6202 PackExpansionType(Pattern, Canon, NumExpansions);
6203 Types.push_back(T);
6204 PackExpansionTypes.InsertNode(T, InsertPos);
6205 return QualType(T, 0);
6206}
6207
6208/// CmpProtocolNames - Comparison predicate for sorting protocols
6209/// alphabetically.
6210static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6211 ObjCProtocolDecl *const *RHS) {
6212 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6213}
6214
6216 if (Protocols.empty()) return true;
6217
6218 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6219 return false;
6220
6221 for (unsigned i = 1; i != Protocols.size(); ++i)
6222 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6223 Protocols[i]->getCanonicalDecl() != Protocols[i])
6224 return false;
6225 return true;
6226}
6227
6228static void
6230 // Sort protocols, keyed by name.
6231 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6232
6233 // Canonicalize.
6234 for (ObjCProtocolDecl *&P : Protocols)
6235 P = P->getCanonicalDecl();
6236
6237 // Remove duplicates.
6238 auto ProtocolsEnd = llvm::unique(Protocols);
6239 Protocols.erase(ProtocolsEnd, Protocols.end());
6240}
6241
6243 ObjCProtocolDecl * const *Protocols,
6244 unsigned NumProtocols) const {
6245 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6246 /*isKindOf=*/false);
6247}
6248
6250 QualType baseType,
6251 ArrayRef<QualType> typeArgs,
6253 bool isKindOf) const {
6254 // If the base type is an interface and there aren't any protocols or
6255 // type arguments to add, then the interface type will do just fine.
6256 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6257 isa<ObjCInterfaceType>(baseType))
6258 return baseType;
6259
6260 // Look in the folding set for an existing type.
6261 llvm::FoldingSetNodeID ID;
6262 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6263 void *InsertPos = nullptr;
6264 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6265 return QualType(QT, 0);
6266
6267 // Determine the type arguments to be used for canonicalization,
6268 // which may be explicitly specified here or written on the base
6269 // type.
6270 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6271 if (effectiveTypeArgs.empty()) {
6272 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6273 effectiveTypeArgs = baseObject->getTypeArgs();
6274 }
6275
6276 // Build the canonical type, which has the canonical base type and a
6277 // sorted-and-uniqued list of protocols and the type arguments
6278 // canonicalized.
6279 QualType canonical;
6280 bool typeArgsAreCanonical = llvm::all_of(
6281 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6282 bool protocolsSorted = areSortedAndUniqued(protocols);
6283 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6284 // Determine the canonical type arguments.
6285 ArrayRef<QualType> canonTypeArgs;
6286 SmallVector<QualType, 4> canonTypeArgsVec;
6287 if (!typeArgsAreCanonical) {
6288 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6289 for (auto typeArg : effectiveTypeArgs)
6290 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6291 canonTypeArgs = canonTypeArgsVec;
6292 } else {
6293 canonTypeArgs = effectiveTypeArgs;
6294 }
6295
6296 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6297 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6298 if (!protocolsSorted) {
6299 canonProtocolsVec.append(protocols.begin(), protocols.end());
6300 SortAndUniqueProtocols(canonProtocolsVec);
6301 canonProtocols = canonProtocolsVec;
6302 } else {
6303 canonProtocols = protocols;
6304 }
6305
6306 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6307 canonProtocols, isKindOf);
6308
6309 // Regenerate InsertPos.
6310 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6311 }
6312
6313 unsigned size = sizeof(ObjCObjectTypeImpl);
6314 size += typeArgs.size() * sizeof(QualType);
6315 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6316 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6317 auto *T =
6318 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6319 isKindOf);
6320
6321 Types.push_back(T);
6322 ObjCObjectTypes.InsertNode(T, InsertPos);
6323 return QualType(T, 0);
6324}
6325
6326/// Apply Objective-C protocol qualifiers to the given type.
6327/// If this is for the canonical type of a type parameter, we can apply
6328/// protocol qualifiers on the ObjCObjectPointerType.
6331 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6332 bool allowOnPointerType) const {
6333 hasError = false;
6334
6335 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6336 return getObjCTypeParamType(objT->getDecl(), protocols);
6337 }
6338
6339 // Apply protocol qualifiers to ObjCObjectPointerType.
6340 if (allowOnPointerType) {
6341 if (const auto *objPtr =
6342 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6343 const ObjCObjectType *objT = objPtr->getObjectType();
6344 // Merge protocol lists and construct ObjCObjectType.
6346 protocolsVec.append(objT->qual_begin(),
6347 objT->qual_end());
6348 protocolsVec.append(protocols.begin(), protocols.end());
6349 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6351 objT->getBaseType(),
6352 objT->getTypeArgsAsWritten(),
6353 protocols,
6354 objT->isKindOfTypeAsWritten());
6356 }
6357 }
6358
6359 // Apply protocol qualifiers to ObjCObjectType.
6360 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6361 // FIXME: Check for protocols to which the class type is already
6362 // known to conform.
6363
6364 return getObjCObjectType(objT->getBaseType(),
6365 objT->getTypeArgsAsWritten(),
6366 protocols,
6367 objT->isKindOfTypeAsWritten());
6368 }
6369
6370 // If the canonical type is ObjCObjectType, ...
6371 if (type->isObjCObjectType()) {
6372 // Silently overwrite any existing protocol qualifiers.
6373 // TODO: determine whether that's the right thing to do.
6374
6375 // FIXME: Check for protocols to which the class type is already
6376 // known to conform.
6377 return getObjCObjectType(type, {}, protocols, false);
6378 }
6379
6380 // id<protocol-list>
6381 if (type->isObjCIdType()) {
6382 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6383 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6384 objPtr->isKindOfType());
6386 }
6387
6388 // Class<protocol-list>
6389 if (type->isObjCClassType()) {
6390 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6391 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6392 objPtr->isKindOfType());
6394 }
6395
6396 hasError = true;
6397 return type;
6398}
6399
6402 ArrayRef<ObjCProtocolDecl *> protocols) const {
6403 // Look in the folding set for an existing type.
6404 llvm::FoldingSetNodeID ID;
6405 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6406 void *InsertPos = nullptr;
6407 if (ObjCTypeParamType *TypeParam =
6408 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6409 return QualType(TypeParam, 0);
6410
6411 // We canonicalize to the underlying type.
6412 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6413 if (!protocols.empty()) {
6414 // Apply the protocol qualifers.
6415 bool hasError;
6417 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6418 assert(!hasError && "Error when apply protocol qualifier to bound type");
6419 }
6420
6421 unsigned size = sizeof(ObjCTypeParamType);
6422 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6423 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6424 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6425
6426 Types.push_back(newType);
6427 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6428 return QualType(newType, 0);
6429}
6430
6432 ObjCTypeParamDecl *New) const {
6433 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6434 // Update TypeForDecl after updating TypeSourceInfo.
6435 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6437 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6438 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6439 New->TypeForDecl = UpdatedTy.getTypePtr();
6440}
6441
6442/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6443/// protocol list adopt all protocols in QT's qualified-id protocol
6444/// list.
6446 ObjCInterfaceDecl *IC) {
6447 if (!QT->isObjCQualifiedIdType())
6448 return false;
6449
6450 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6451 // If both the right and left sides have qualifiers.
6452 for (auto *Proto : OPT->quals()) {
6453 if (!IC->ClassImplementsProtocol(Proto, false))
6454 return false;
6455 }
6456 return true;
6457 }
6458 return false;
6459}
6460
6461/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6462/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6463/// of protocols.
6465 ObjCInterfaceDecl *IDecl) {
6466 if (!QT->isObjCQualifiedIdType())
6467 return false;
6468 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6469 if (!OPT)
6470 return false;
6471 if (!IDecl->hasDefinition())
6472 return false;
6474 CollectInheritedProtocols(IDecl, InheritedProtocols);
6475 if (InheritedProtocols.empty())
6476 return false;
6477 // Check that if every protocol in list of id<plist> conforms to a protocol
6478 // of IDecl's, then bridge casting is ok.
6479 bool Conforms = false;
6480 for (auto *Proto : OPT->quals()) {
6481 Conforms = false;
6482 for (auto *PI : InheritedProtocols) {
6483 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6484 Conforms = true;
6485 break;
6486 }
6487 }
6488 if (!Conforms)
6489 break;
6490 }
6491 if (Conforms)
6492 return true;
6493
6494 for (auto *PI : InheritedProtocols) {
6495 // If both the right and left sides have qualifiers.
6496 bool Adopts = false;
6497 for (auto *Proto : OPT->quals()) {
6498 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6499 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6500 break;
6501 }
6502 if (!Adopts)
6503 return false;
6504 }
6505 return true;
6506}
6507
6508/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6509/// the given object type.
6511 llvm::FoldingSetNodeID ID;
6512 ObjCObjectPointerType::Profile(ID, ObjectT);
6513
6514 void *InsertPos = nullptr;
6515 if (ObjCObjectPointerType *QT =
6516 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6517 return QualType(QT, 0);
6518
6519 // Find the canonical object type.
6520 QualType Canonical;
6521 if (!ObjectT.isCanonical()) {
6522 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6523
6524 // Regenerate InsertPos.
6525 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6526 }
6527
6528 // No match.
6529 void *Mem =
6531 auto *QType =
6532 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6533
6534 Types.push_back(QType);
6535 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6536 return QualType(QType, 0);
6537}
6538
6539/// getObjCInterfaceType - Return the unique reference to the type for the
6540/// specified ObjC interface decl. The list of protocols is optional.
6542 ObjCInterfaceDecl *PrevDecl) const {
6543 if (Decl->TypeForDecl)
6544 return QualType(Decl->TypeForDecl, 0);
6545
6546 if (PrevDecl) {
6547 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6548 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6549 return QualType(PrevDecl->TypeForDecl, 0);
6550 }
6551
6552 // Prefer the definition, if there is one.
6553 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6554 Decl = Def;
6555
6556 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6557 auto *T = new (Mem) ObjCInterfaceType(Decl);
6558 Decl->TypeForDecl = T;
6559 Types.push_back(T);
6560 return QualType(T, 0);
6561}
6562
6563/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6564/// TypeOfExprType AST's (since expression's are never shared). For example,
6565/// multiple declarations that refer to "typeof(x)" all contain different
6566/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6567/// on canonical type's (which are always unique).
6569 TypeOfExprType *toe;
6570 if (tofExpr->isTypeDependent()) {
6571 llvm::FoldingSetNodeID ID;
6572 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6573 Kind == TypeOfKind::Unqualified);
6574
6575 void *InsertPos = nullptr;
6577 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6578 if (Canon) {
6579 // We already have a "canonical" version of an identical, dependent
6580 // typeof(expr) type. Use that as our canonical type.
6581 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6582 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6583 } else {
6584 // Build a new, canonical typeof(expr) type.
6585 Canon = new (*this, alignof(DependentTypeOfExprType))
6586 DependentTypeOfExprType(*this, tofExpr, Kind);
6587 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6588 toe = Canon;
6589 }
6590 } else {
6591 QualType Canonical = getCanonicalType(tofExpr->getType());
6592 toe = new (*this, alignof(TypeOfExprType))
6593 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6594 }
6595 Types.push_back(toe);
6596 return QualType(toe, 0);
6597}
6598
6599/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6600/// TypeOfType nodes. The only motivation to unique these nodes would be
6601/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6602/// an issue. This doesn't affect the type checker, since it operates
6603/// on canonical types (which are always unique).
6605 QualType Canonical = getCanonicalType(tofType);
6606 auto *tot = new (*this, alignof(TypeOfType))
6607 TypeOfType(*this, tofType, Canonical, Kind);
6608 Types.push_back(tot);
6609 return QualType(tot, 0);
6610}
6611
6612/// getReferenceQualifiedType - Given an expr, will return the type for
6613/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6614/// and class member access into account.
6616 // C++11 [dcl.type.simple]p4:
6617 // [...]
6618 QualType T = E->getType();
6619 switch (E->getValueKind()) {
6620 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6621 // type of e;
6622 case VK_XValue:
6623 return getRValueReferenceType(T);
6624 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6625 // type of e;
6626 case VK_LValue:
6627 return getLValueReferenceType(T);
6628 // - otherwise, decltype(e) is the type of e.
6629 case VK_PRValue:
6630 return T;
6631 }
6632 llvm_unreachable("Unknown value kind");
6633}
6634
6635/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6636/// nodes. This would never be helpful, since each such type has its own
6637/// expression, and would not give a significant memory saving, since there
6638/// is an Expr tree under each such type.
6640 // C++11 [temp.type]p2:
6641 // If an expression e involves a template parameter, decltype(e) denotes a
6642 // unique dependent type. Two such decltype-specifiers refer to the same
6643 // type only if their expressions are equivalent (14.5.6.1).
6644 QualType CanonType;
6645 if (!E->isInstantiationDependent()) {
6646 CanonType = getCanonicalType(UnderlyingType);
6647 } else if (!UnderlyingType.isNull()) {
6648 CanonType = getDecltypeType(E, QualType());
6649 } else {
6650 llvm::FoldingSetNodeID ID;
6651 DependentDecltypeType::Profile(ID, *this, E);
6652
6653 void *InsertPos = nullptr;
6654 if (DependentDecltypeType *Canon =
6655 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6656 return QualType(Canon, 0);
6657
6658 // Build a new, canonical decltype(expr) type.
6659 auto *DT =
6660 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6661 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6662 Types.push_back(DT);
6663 return QualType(DT, 0);
6664 }
6665 auto *DT = new (*this, alignof(DecltypeType))
6666 DecltypeType(E, UnderlyingType, CanonType);
6667 Types.push_back(DT);
6668 return QualType(DT, 0);
6669}
6670
6672 bool FullySubstituted,
6673 ArrayRef<QualType> Expansions,
6674 UnsignedOrNone Index) const {
6675 QualType Canonical;
6676 if (FullySubstituted && Index) {
6677 Canonical = getCanonicalType(Expansions[*Index]);
6678 } else {
6679 llvm::FoldingSetNodeID ID;
6680 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6681 FullySubstituted, Expansions);
6682 void *InsertPos = nullptr;
6683 PackIndexingType *Canon =
6684 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6685 if (!Canon) {
6686 void *Mem = Allocate(
6687 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6689 Canon =
6690 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6691 IndexExpr, FullySubstituted, Expansions);
6692 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6693 }
6694 Canonical = QualType(Canon, 0);
6695 }
6696
6697 void *Mem =
6698 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6700 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6701 FullySubstituted, Expansions);
6702 Types.push_back(T);
6703 return QualType(T, 0);
6704}
6705
6706/// getUnaryTransformationType - We don't unique these, since the memory
6707/// savings are minimal and these are rare.
6710 UnaryTransformType::UTTKind Kind) const {
6711
6712 llvm::FoldingSetNodeID ID;
6713 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6714
6715 void *InsertPos = nullptr;
6716 if (UnaryTransformType *UT =
6717 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6718 return QualType(UT, 0);
6719
6720 QualType CanonType;
6721 if (!BaseType->isDependentType()) {
6722 CanonType = UnderlyingType.getCanonicalType();
6723 } else {
6724 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6725 UnderlyingType = QualType();
6726 if (QualType CanonBase = BaseType.getCanonicalType();
6727 BaseType != CanonBase) {
6728 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6729 assert(CanonType.isCanonical());
6730
6731 // Find the insertion position again.
6732 [[maybe_unused]] UnaryTransformType *UT =
6733 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6734 assert(!UT && "broken canonicalization");
6735 }
6736 }
6737
6738 auto *UT = new (*this, alignof(UnaryTransformType))
6739 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6740 UnaryTransformTypes.InsertNode(UT, InsertPos);
6741 Types.push_back(UT);
6742 return QualType(UT, 0);
6743}
6744
6745QualType ASTContext::getAutoTypeInternal(
6746 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6747 bool IsPack, TemplateDecl *TypeConstraintConcept,
6748 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6749 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6750 !TypeConstraintConcept && !IsDependent)
6751 return getAutoDeductType();
6752
6753 // Look in the folding set for an existing type.
6754 llvm::FoldingSetNodeID ID;
6755 bool IsDeducedDependent =
6756 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6757 (!DeducedType.isNull() && DeducedType->isDependentType());
6758 AutoType::Profile(ID, *this, DeducedType, Keyword,
6759 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6760 TypeConstraintArgs);
6761 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6762 return QualType(AT_iter->getSecond(), 0);
6763
6764 QualType Canon;
6765 if (!IsCanon) {
6766 if (!DeducedType.isNull()) {
6767 Canon = DeducedType.getCanonicalType();
6768 } else if (TypeConstraintConcept) {
6769 bool AnyNonCanonArgs = false;
6770 auto *CanonicalConcept =
6771 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6772 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6773 *this, TypeConstraintArgs, AnyNonCanonArgs);
6774 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6775 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6776 CanonicalConcept, CanonicalConceptArgs,
6777 /*IsCanon=*/true);
6778 }
6779 }
6780 }
6781
6782 void *Mem = Allocate(sizeof(AutoType) +
6783 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6784 alignof(AutoType));
6785 auto *AT = new (Mem) AutoType(
6786 DeducedType, Keyword,
6787 (IsDependent ? TypeDependence::DependentInstantiation
6788 : TypeDependence::None) |
6789 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6790 Canon, TypeConstraintConcept, TypeConstraintArgs);
6791#ifndef NDEBUG
6792 llvm::FoldingSetNodeID InsertedID;
6793 AT->Profile(InsertedID, *this);
6794 assert(InsertedID == ID && "ID does not match");
6795#endif
6796 Types.push_back(AT);
6797 AutoTypes.try_emplace(ID, AT);
6798 return QualType(AT, 0);
6799}
6800
6801/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6802/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6803/// canonical deduced-but-dependent 'auto' type.
6804QualType
6806 bool IsDependent, bool IsPack,
6807 TemplateDecl *TypeConstraintConcept,
6808 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6809 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6810 assert((!IsDependent || DeducedType.isNull()) &&
6811 "A dependent auto should be undeduced");
6812 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6813 TypeConstraintConcept, TypeConstraintArgs);
6814}
6815
6817 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6818
6819 // Remove a type-constraint from a top-level auto or decltype(auto).
6820 if (auto *AT = CanonT->getAs<AutoType>()) {
6821 if (!AT->isConstrained())
6822 return T;
6823 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6824 AT->isDependentType(),
6825 AT->containsUnexpandedParameterPack()),
6826 T.getQualifiers());
6827 }
6828
6829 // FIXME: We only support constrained auto at the top level in the type of a
6830 // non-type template parameter at the moment. Once we lift that restriction,
6831 // we'll need to recursively build types containing auto here.
6832 assert(!CanonT->getContainedAutoType() ||
6833 !CanonT->getContainedAutoType()->isConstrained());
6834 return T;
6835}
6836
6837QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6839 bool IsDependent, QualType Canon) const {
6840 // Look in the folding set for an existing type.
6841 void *InsertPos = nullptr;
6842 llvm::FoldingSetNodeID ID;
6843 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6844 IsDependent);
6845 if (DeducedTemplateSpecializationType *DTST =
6846 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6847 return QualType(DTST, 0);
6848
6849 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6850 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6851 IsDependent, Canon);
6852
6853#ifndef NDEBUG
6854 llvm::FoldingSetNodeID TempID;
6855 DTST->Profile(TempID);
6856 assert(ID == TempID && "ID does not match");
6857#endif
6858 Types.push_back(DTST);
6859 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6860 return QualType(DTST, 0);
6861}
6862
6863/// Return the uniqued reference to the deduced template specialization type
6864/// which has been deduced to the given type, or to the canonical undeduced
6865/// such type, or the canonical deduced-but-dependent such type.
6868 bool IsDependent) const {
6869 // FIXME: This could save an extra hash table lookup if it handled all the
6870 // parameters already being canonical.
6871 // FIXME: Can this be formed from a DependentTemplateName, such that the
6872 // keyword should be part of the canonical type?
6873 QualType Canon =
6874 DeducedType.isNull()
6875 ? getDeducedTemplateSpecializationTypeInternal(
6877 QualType(), IsDependent, QualType())
6878 : DeducedType.getCanonicalType();
6879 return getDeducedTemplateSpecializationTypeInternal(
6880 Keyword, Template, DeducedType, IsDependent, Canon);
6881}
6882
6883/// getAtomicType - Return the uniqued reference to the atomic type for
6884/// the given value type.
6886 // Unique pointers, to guarantee there is only one pointer of a particular
6887 // structure.
6888 llvm::FoldingSetNodeID ID;
6890
6891 void *InsertPos = nullptr;
6892 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6893 return QualType(AT, 0);
6894
6895 // If the atomic value type isn't canonical, this won't be a canonical type
6896 // either, so fill in the canonical type field.
6897 QualType Canonical;
6898 if (!T.isCanonical()) {
6899 Canonical = getAtomicType(getCanonicalType(T));
6900
6901 // Get the new insert position for the node we care about.
6902 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6903 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6904 }
6905 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6906 Types.push_back(New);
6907 AtomicTypes.InsertNode(New, InsertPos);
6908 return QualType(New, 0);
6909}
6910
6911/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6913 if (AutoDeductTy.isNull())
6914 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6915 AutoType(QualType(), AutoTypeKeyword::Auto,
6916 TypeDependence::None, QualType(),
6917 /*concept*/ nullptr, /*args*/ {}),
6918 0);
6919 return AutoDeductTy;
6920}
6921
6922/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6924 if (AutoRRefDeductTy.isNull())
6926 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6927 return AutoRRefDeductTy;
6928}
6929
6930/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6931/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6932/// needs to agree with the definition in <stddef.h>.
6936
6938 return getFromTargetType(Target->getSizeType());
6939}
6940
6941/// Return the unique signed counterpart of the integer type
6942/// corresponding to size_t.
6946
6947/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6948/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6952
6953/// Return the unique unsigned counterpart of "ptrdiff_t"
6954/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6955/// in the definition of %tu format specifier.
6957 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6958}
6959
6960/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6962 return getFromTargetType(Target->getIntMaxType());
6963}
6964
6965/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6967 return getFromTargetType(Target->getUIntMaxType());
6968}
6969
6970/// getSignedWCharType - Return the type of "signed wchar_t".
6971/// Used when in C++, as a GCC extension.
6973 // FIXME: derive from "Target" ?
6974 return WCharTy;
6975}
6976
6977/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6978/// Used when in C++, as a GCC extension.
6980 // FIXME: derive from "Target" ?
6981 return UnsignedIntTy;
6982}
6983
6985 return getFromTargetType(Target->getIntPtrType());
6986}
6987
6991
6992/// Return the unique type for "pid_t" defined in
6993/// <sys/types.h>. We need this to compute the correct type for vfork().
6995 return getFromTargetType(Target->getProcessIDType());
6996}
6997
6998//===----------------------------------------------------------------------===//
6999// Type Operators
7000//===----------------------------------------------------------------------===//
7001
7003 // Push qualifiers into arrays, and then discard any remaining
7004 // qualifiers.
7005 T = getCanonicalType(T);
7007 const Type *Ty = T.getTypePtr();
7011 } else if (isa<ArrayType>(Ty)) {
7013 } else if (isa<FunctionType>(Ty)) {
7014 Result = getPointerType(QualType(Ty, 0));
7015 } else {
7016 Result = QualType(Ty, 0);
7017 }
7018
7020}
7021
7023 Qualifiers &quals) const {
7024 SplitQualType splitType = type.getSplitUnqualifiedType();
7025
7026 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7027 // the unqualified desugared type and then drops it on the floor.
7028 // We then have to strip that sugar back off with
7029 // getUnqualifiedDesugaredType(), which is silly.
7030 const auto *AT =
7031 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7032
7033 // If we don't have an array, just use the results in splitType.
7034 if (!AT) {
7035 quals = splitType.Quals;
7036 return QualType(splitType.Ty, 0);
7037 }
7038
7039 // Otherwise, recurse on the array's element type.
7040 QualType elementType = AT->getElementType();
7041 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7042
7043 // If that didn't change the element type, AT has no qualifiers, so we
7044 // can just use the results in splitType.
7045 if (elementType == unqualElementType) {
7046 assert(quals.empty()); // from the recursive call
7047 quals = splitType.Quals;
7048 return QualType(splitType.Ty, 0);
7049 }
7050
7051 // Otherwise, add in the qualifiers from the outermost type, then
7052 // build the type back up.
7053 quals.addConsistentQualifiers(splitType.Quals);
7054
7055 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7056 return getConstantArrayType(unqualElementType, CAT->getSize(),
7057 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7058 }
7059
7060 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7061 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7062 }
7063
7064 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7065 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7066 VAT->getSizeModifier(),
7067 VAT->getIndexTypeCVRQualifiers());
7068 }
7069
7070 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7071 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7072 DSAT->getSizeModifier(), 0);
7073}
7074
7075/// Attempt to unwrap two types that may both be array types with the same bound
7076/// (or both be array types of unknown bound) for the purpose of comparing the
7077/// cv-decomposition of two types per C++ [conv.qual].
7078///
7079/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7080/// C++20 [conv.qual], if permitted by the current language mode.
7082 bool AllowPiMismatch) const {
7083 while (true) {
7084 auto *AT1 = getAsArrayType(T1);
7085 if (!AT1)
7086 return;
7087
7088 auto *AT2 = getAsArrayType(T2);
7089 if (!AT2)
7090 return;
7091
7092 // If we don't have two array types with the same constant bound nor two
7093 // incomplete array types, we've unwrapped everything we can.
7094 // C++20 also permits one type to be a constant array type and the other
7095 // to be an incomplete array type.
7096 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7097 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7098 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7099 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7100 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7102 return;
7103 } else if (isa<IncompleteArrayType>(AT1)) {
7104 if (!(isa<IncompleteArrayType>(AT2) ||
7105 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7107 return;
7108 } else {
7109 return;
7110 }
7111
7112 T1 = AT1->getElementType();
7113 T2 = AT2->getElementType();
7114 }
7115}
7116
7117/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7118///
7119/// If T1 and T2 are both pointer types of the same kind, or both array types
7120/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7121/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7122///
7123/// This function will typically be called in a loop that successively
7124/// "unwraps" pointer and pointer-to-member types to compare them at each
7125/// level.
7126///
7127/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7128/// C++20 [conv.qual], if permitted by the current language mode.
7129///
7130/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7131/// pair of types that can't be unwrapped further.
7133 bool AllowPiMismatch) const {
7134 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7135
7136 const auto *T1PtrType = T1->getAs<PointerType>();
7137 const auto *T2PtrType = T2->getAs<PointerType>();
7138 if (T1PtrType && T2PtrType) {
7139 T1 = T1PtrType->getPointeeType();
7140 T2 = T2PtrType->getPointeeType();
7141 return true;
7142 }
7143
7144 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7145 *T2MPType = T2->getAs<MemberPointerType>();
7146 T1MPType && T2MPType) {
7147 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7148 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7149 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7150 return false;
7151 if (T1MPType->getQualifier().getCanonical() !=
7152 T2MPType->getQualifier().getCanonical())
7153 return false;
7154 T1 = T1MPType->getPointeeType();
7155 T2 = T2MPType->getPointeeType();
7156 return true;
7157 }
7158
7159 if (getLangOpts().ObjC) {
7160 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7161 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7162 if (T1OPType && T2OPType) {
7163 T1 = T1OPType->getPointeeType();
7164 T2 = T2OPType->getPointeeType();
7165 return true;
7166 }
7167 }
7168
7169 // FIXME: Block pointers, too?
7170
7171 return false;
7172}
7173
7175 while (true) {
7176 Qualifiers Quals;
7177 T1 = getUnqualifiedArrayType(T1, Quals);
7178 T2 = getUnqualifiedArrayType(T2, Quals);
7179 if (hasSameType(T1, T2))
7180 return true;
7181 if (!UnwrapSimilarTypes(T1, T2))
7182 return false;
7183 }
7184}
7185
7187 while (true) {
7188 Qualifiers Quals1, Quals2;
7189 T1 = getUnqualifiedArrayType(T1, Quals1);
7190 T2 = getUnqualifiedArrayType(T2, Quals2);
7191
7192 Quals1.removeCVRQualifiers();
7193 Quals2.removeCVRQualifiers();
7194 if (Quals1 != Quals2)
7195 return false;
7196
7197 if (hasSameType(T1, T2))
7198 return true;
7199
7200 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7201 return false;
7202 }
7203}
7204
7207 SourceLocation NameLoc) const {
7208 switch (Name.getKind()) {
7211 // DNInfo work in progress: CHECKME: what about DNLoc?
7213 NameLoc);
7214
7217 // DNInfo work in progress: CHECKME: what about DNLoc?
7218 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7219 }
7220
7223 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7224 }
7225
7229 DeclarationName DName;
7230 if (const IdentifierInfo *II = TN.getIdentifier()) {
7231 DName = DeclarationNames.getIdentifier(II);
7232 return DeclarationNameInfo(DName, NameLoc);
7233 } else {
7234 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7235 // DNInfo work in progress: FIXME: source locations?
7236 DeclarationNameLoc DNLoc =
7238 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7239 }
7240 }
7241
7245 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7246 NameLoc);
7247 }
7248
7253 NameLoc);
7254 }
7257 NameLoc);
7260 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7261 }
7262 }
7263
7264 llvm_unreachable("bad template name kind!");
7265}
7266
7267static const TemplateArgument *
7269 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7270 if (!TP->hasDefaultArgument())
7271 return nullptr;
7272 return &TP->getDefaultArgument().getArgument();
7273 };
7274 switch (P->getKind()) {
7275 case NamedDecl::TemplateTypeParm:
7276 return handleParam(cast<TemplateTypeParmDecl>(P));
7277 case NamedDecl::NonTypeTemplateParm:
7278 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7279 case NamedDecl::TemplateTemplateParm:
7280 return handleParam(cast<TemplateTemplateParmDecl>(P));
7281 default:
7282 llvm_unreachable("Unexpected template parameter kind");
7283 }
7284}
7285
7287 bool IgnoreDeduced) const {
7288 while (std::optional<TemplateName> UnderlyingOrNone =
7289 Name.desugar(IgnoreDeduced))
7290 Name = *UnderlyingOrNone;
7291
7292 switch (Name.getKind()) {
7295 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7297
7298 // The canonical template name is the canonical template declaration.
7299 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7300 }
7301
7304 llvm_unreachable("cannot canonicalize unresolved template");
7305
7308 assert(DTN && "Non-dependent template names must refer to template decls.");
7309 NestedNameSpecifier Qualifier = DTN->getQualifier();
7310 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7311 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7312 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7313 /*HasTemplateKeyword=*/true});
7314 return Name;
7315 }
7316
7320 TemplateArgument canonArgPack =
7323 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7324 subst->getIndex(), subst->getFinal());
7325 }
7327 assert(IgnoreDeduced == false);
7329 DefaultArguments DefArgs = DTS->getDefaultArguments();
7330 TemplateName Underlying = DTS->getUnderlying();
7331
7332 TemplateName CanonUnderlying =
7333 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7334 bool NonCanonical = CanonUnderlying != Underlying;
7335 auto CanonArgs =
7336 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7337
7338 ArrayRef<NamedDecl *> Params =
7339 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7340 assert(CanonArgs.size() <= Params.size());
7341 // A deduced template name which deduces the same default arguments already
7342 // declared in the underlying template is the same template as the
7343 // underlying template. We need need to note any arguments which differ from
7344 // the corresponding declaration. If any argument differs, we must build a
7345 // deduced template name.
7346 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7348 if (!A)
7349 break;
7350 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7351 TemplateArgument &CanonDefArg = CanonArgs[I];
7352 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7353 continue;
7354 // Keep popping from the back any deault arguments which are the same.
7355 if (I == int(CanonArgs.size() - 1))
7356 CanonArgs.pop_back();
7357 NonCanonical = true;
7358 }
7359 return NonCanonical ? getDeducedTemplateName(
7360 CanonUnderlying,
7361 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7362 : Name;
7363 }
7367 llvm_unreachable("always sugar node");
7368 }
7369
7370 llvm_unreachable("bad template name!");
7371}
7372
7374 const TemplateName &Y,
7375 bool IgnoreDeduced) const {
7376 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7377 getCanonicalTemplateName(Y, IgnoreDeduced);
7378}
7379
7381 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7382 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7383 return false;
7385 return false;
7386 return true;
7387}
7388
7389bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7390 if (!XCE != !YCE)
7391 return false;
7392
7393 if (!XCE)
7394 return true;
7395
7396 llvm::FoldingSetNodeID XCEID, YCEID;
7397 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7398 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7399 return XCEID == YCEID;
7400}
7401
7403 const TypeConstraint *YTC) const {
7404 if (!XTC != !YTC)
7405 return false;
7406
7407 if (!XTC)
7408 return true;
7409
7410 auto *NCX = XTC->getNamedConcept();
7411 auto *NCY = YTC->getNamedConcept();
7412 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7413 return false;
7416 return false;
7418 if (XTC->getConceptReference()
7420 ->NumTemplateArgs !=
7422 return false;
7423
7424 // Compare slowly by profiling.
7425 //
7426 // We couldn't compare the profiling result for the template
7427 // args here. Consider the following example in different modules:
7428 //
7429 // template <__integer_like _Tp, C<_Tp> Sentinel>
7430 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7431 // return __t;
7432 // }
7433 //
7434 // When we compare the profiling result for `C<_Tp>` in different
7435 // modules, it will compare the type of `_Tp` in different modules.
7436 // However, the type of `_Tp` in different modules refer to different
7437 // types here naturally. So we couldn't compare the profiling result
7438 // for the template args directly.
7441}
7442
7444 const NamedDecl *Y) const {
7445 if (X->getKind() != Y->getKind())
7446 return false;
7447
7448 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7449 auto *TY = cast<TemplateTypeParmDecl>(Y);
7450 if (TX->isParameterPack() != TY->isParameterPack())
7451 return false;
7452 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7453 return false;
7454 return isSameTypeConstraint(TX->getTypeConstraint(),
7455 TY->getTypeConstraint());
7456 }
7457
7458 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7459 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7460 return TX->isParameterPack() == TY->isParameterPack() &&
7461 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7462 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7463 TY->getPlaceholderTypeConstraint());
7464 }
7465
7467 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7468 return TX->isParameterPack() == TY->isParameterPack() &&
7469 isSameTemplateParameterList(TX->getTemplateParameters(),
7470 TY->getTemplateParameters());
7471}
7472
7474 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7475 if (X->size() != Y->size())
7476 return false;
7477
7478 for (unsigned I = 0, N = X->size(); I != N; ++I)
7479 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7480 return false;
7481
7482 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7483}
7484
7486 const NamedDecl *Y) const {
7487 // If the type parameter isn't the same already, we don't need to check the
7488 // default argument further.
7489 if (!isSameTemplateParameter(X, Y))
7490 return false;
7491
7492 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7493 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7494 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7495 return false;
7496
7497 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7498 TTPY->getDefaultArgument().getArgument().getAsType());
7499 }
7500
7501 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7502 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7503 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7504 return false;
7505
7506 Expr *DefaultArgumentX =
7507 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7508 Expr *DefaultArgumentY =
7509 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7510 llvm::FoldingSetNodeID XID, YID;
7511 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7512 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7513 return XID == YID;
7514 }
7515
7516 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7517 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7518
7519 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7520 return false;
7521
7522 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7523 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7524 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7525}
7526
7528 const NestedNameSpecifier Y) {
7529 if (X == Y)
7530 return true;
7531 if (!X || !Y)
7532 return false;
7533
7534 auto Kind = X.getKind();
7535 if (Kind != Y.getKind())
7536 return false;
7537
7538 // FIXME: For namespaces and types, we're permitted to check that the entity
7539 // is named via the same tokens. We should probably do so.
7540 switch (Kind) {
7542 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7543 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7544 if (!declaresSameEntity(NamespaceX->getNamespace(),
7545 NamespaceY->getNamespace()))
7546 return false;
7547 return isSameQualifier(PrefixX, PrefixY);
7548 }
7550 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7551 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7552 return false;
7553 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7554 }
7558 return true;
7559 }
7560 llvm_unreachable("unhandled qualifier kind");
7561}
7562
7563static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7564 if (!A->getASTContext().getLangOpts().CUDA)
7565 return true; // Target attributes are overloadable in CUDA compilation only.
7566 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7567 return false;
7568 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7569 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7570 return true; // unattributed and __host__ functions are the same.
7571}
7572
7573/// Determine whether the attributes we can overload on are identical for A and
7574/// B. Will ignore any overloadable attrs represented in the type of A and B.
7576 const FunctionDecl *B) {
7577 // Note that pass_object_size attributes are represented in the function's
7578 // ExtParameterInfo, so we don't need to check them here.
7579
7580 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7581 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7582 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7583
7584 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7585 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7586 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7587
7588 // Return false if the number of enable_if attributes is different.
7589 if (!Cand1A || !Cand2A)
7590 return false;
7591
7592 Cand1ID.clear();
7593 Cand2ID.clear();
7594
7595 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7596 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7597
7598 // Return false if any of the enable_if expressions of A and B are
7599 // different.
7600 if (Cand1ID != Cand2ID)
7601 return false;
7602 }
7603 return hasSameCudaAttrs(A, B);
7604}
7605
7606bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7607 // Caution: this function is called by the AST reader during deserialization,
7608 // so it cannot rely on AST invariants being met. Non-trivial accessors
7609 // should be avoided, along with any traversal of redeclaration chains.
7610
7611 if (X == Y)
7612 return true;
7613
7614 if (X->getDeclName() != Y->getDeclName())
7615 return false;
7616
7617 // Must be in the same context.
7618 //
7619 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7620 // could be two different declarations of the same function. (We will fix the
7621 // semantic DC to refer to the primary definition after merging.)
7622 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7624 return false;
7625
7626 // If either X or Y are local to the owning module, they are only possible to
7627 // be the same entity if they are in the same module.
7628 if (X->isModuleLocal() || Y->isModuleLocal())
7629 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7630 return false;
7631
7632 // Two typedefs refer to the same entity if they have the same underlying
7633 // type.
7634 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7635 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7636 return hasSameType(TypedefX->getUnderlyingType(),
7637 TypedefY->getUnderlyingType());
7638
7639 // Must have the same kind.
7640 if (X->getKind() != Y->getKind())
7641 return false;
7642
7643 // Objective-C classes and protocols with the same name always match.
7645 return true;
7646
7648 // No need to handle these here: we merge them when adding them to the
7649 // template.
7650 return false;
7651 }
7652
7653 // Compatible tags match.
7654 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7655 const auto *TagY = cast<TagDecl>(Y);
7656 return (TagX->getTagKind() == TagY->getTagKind()) ||
7657 ((TagX->getTagKind() == TagTypeKind::Struct ||
7658 TagX->getTagKind() == TagTypeKind::Class ||
7659 TagX->getTagKind() == TagTypeKind::Interface) &&
7660 (TagY->getTagKind() == TagTypeKind::Struct ||
7661 TagY->getTagKind() == TagTypeKind::Class ||
7662 TagY->getTagKind() == TagTypeKind::Interface));
7663 }
7664
7665 // Functions with the same type and linkage match.
7666 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7667 // functions, etc.
7668 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7669 const auto *FuncY = cast<FunctionDecl>(Y);
7670 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7671 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7672 if (CtorX->getInheritedConstructor() &&
7673 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7674 CtorY->getInheritedConstructor().getConstructor()))
7675 return false;
7676 }
7677
7678 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7679 return false;
7680
7681 // Multiversioned functions with different feature strings are represented
7682 // as separate declarations.
7683 if (FuncX->isMultiVersion()) {
7684 const auto *TAX = FuncX->getAttr<TargetAttr>();
7685 const auto *TAY = FuncY->getAttr<TargetAttr>();
7686 assert(TAX && TAY && "Multiversion Function without target attribute");
7687
7688 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7689 return false;
7690 }
7691
7692 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7693 // not the same entity if they are constrained.
7694 if ((FuncX->isMemberLikeConstrainedFriend() ||
7695 FuncY->isMemberLikeConstrainedFriend()) &&
7696 !FuncX->getLexicalDeclContext()->Equals(
7697 FuncY->getLexicalDeclContext())) {
7698 return false;
7699 }
7700
7701 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7702 FuncY->getTrailingRequiresClause()))
7703 return false;
7704
7705 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7706 // Map to the first declaration that we've already merged into this one.
7707 // The TSI of redeclarations might not match (due to calling conventions
7708 // being inherited onto the type but not the TSI), but the TSI type of
7709 // the first declaration of the function should match across modules.
7710 FD = FD->getCanonicalDecl();
7711 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7712 : FD->getType();
7713 };
7714 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7715 if (!hasSameType(XT, YT)) {
7716 // We can get functions with different types on the redecl chain in C++17
7717 // if they have differing exception specifications and at least one of
7718 // the excpetion specs is unresolved.
7719 auto *XFPT = XT->getAs<FunctionProtoType>();
7720 auto *YFPT = YT->getAs<FunctionProtoType>();
7721 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7722 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7725 return true;
7726 return false;
7727 }
7728
7729 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7730 hasSameOverloadableAttrs(FuncX, FuncY);
7731 }
7732
7733 // Variables with the same type and linkage match.
7734 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7735 const auto *VarY = cast<VarDecl>(Y);
7736 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7737 // During deserialization, we might compare variables before we load
7738 // their types. Assume the types will end up being the same.
7739 if (VarX->getType().isNull() || VarY->getType().isNull())
7740 return true;
7741
7742 if (hasSameType(VarX->getType(), VarY->getType()))
7743 return true;
7744
7745 // We can get decls with different types on the redecl chain. Eg.
7746 // template <typename T> struct S { static T Var[]; }; // #1
7747 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7748 // Only? happens when completing an incomplete array type. In this case
7749 // when comparing #1 and #2 we should go through their element type.
7750 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7751 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7752 if (!VarXTy || !VarYTy)
7753 return false;
7754 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7755 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7756 }
7757 return false;
7758 }
7759
7760 // Namespaces with the same name and inlinedness match.
7761 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7762 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7763 return NamespaceX->isInline() == NamespaceY->isInline();
7764 }
7765
7766 // Identical template names and kinds match if their template parameter lists
7767 // and patterns match.
7768 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7769 const auto *TemplateY = cast<TemplateDecl>(Y);
7770
7771 // ConceptDecl wouldn't be the same if their constraint expression differs.
7772 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7773 const auto *ConceptY = cast<ConceptDecl>(Y);
7774 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7775 ConceptY->getConstraintExpr()))
7776 return false;
7777 }
7778
7779 return isSameEntity(TemplateX->getTemplatedDecl(),
7780 TemplateY->getTemplatedDecl()) &&
7781 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7782 TemplateY->getTemplateParameters());
7783 }
7784
7785 // Fields with the same name and the same type match.
7786 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7787 const auto *FDY = cast<FieldDecl>(Y);
7788 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7789 return hasSameType(FDX->getType(), FDY->getType());
7790 }
7791
7792 // Indirect fields with the same target field match.
7793 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7794 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7795 return IFDX->getAnonField()->getCanonicalDecl() ==
7796 IFDY->getAnonField()->getCanonicalDecl();
7797 }
7798
7799 // Enumerators with the same name match.
7801 // FIXME: Also check the value is odr-equivalent.
7802 return true;
7803
7804 // Using shadow declarations with the same target match.
7805 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7806 const auto *USY = cast<UsingShadowDecl>(Y);
7807 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7808 }
7809
7810 // Using declarations with the same qualifier match. (We already know that
7811 // the name matches.)
7812 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7813 const auto *UY = cast<UsingDecl>(Y);
7814 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7815 UX->hasTypename() == UY->hasTypename() &&
7816 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7817 }
7818 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7819 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7820 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7821 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7822 }
7823 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7824 return isSameQualifier(
7825 UX->getQualifier(),
7826 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7827 }
7828
7829 // Using-pack declarations are only created by instantiation, and match if
7830 // they're instantiated from matching UnresolvedUsing...Decls.
7831 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7832 return declaresSameEntity(
7833 UX->getInstantiatedFromUsingDecl(),
7834 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7835 }
7836
7837 // Namespace alias definitions with the same target match.
7838 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7839 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7840 return NAX->getNamespace()->Equals(NAY->getNamespace());
7841 }
7842
7843 return false;
7844}
7845
7848 switch (Arg.getKind()) {
7850 return Arg;
7851
7853 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7854 Arg.getIsDefaulted());
7855
7857 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7859 Arg.getIsDefaulted());
7860 }
7861
7864 /*isNullPtr*/ true, Arg.getIsDefaulted());
7865
7868 Arg.getIsDefaulted());
7869
7871 return TemplateArgument(
7874
7877
7879 return TemplateArgument(*this,
7882
7885 /*isNullPtr*/ false, Arg.getIsDefaulted());
7886
7888 bool AnyNonCanonArgs = false;
7889 auto CanonArgs = ::getCanonicalTemplateArguments(
7890 *this, Arg.pack_elements(), AnyNonCanonArgs);
7891 if (!AnyNonCanonArgs)
7892 return Arg;
7894 const_cast<ASTContext &>(*this), CanonArgs);
7895 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7896 return NewArg;
7897 }
7898 }
7899
7900 // Silence GCC warning
7901 llvm_unreachable("Unhandled template argument kind");
7902}
7903
7905 const TemplateArgument &Arg2) const {
7906 if (Arg1.getKind() != Arg2.getKind())
7907 return false;
7908
7909 switch (Arg1.getKind()) {
7911 llvm_unreachable("Comparing NULL template argument");
7912
7914 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7915
7917 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7919
7921 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7922
7927
7929 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7930 Arg2.getAsIntegral());
7931
7933 return Arg1.structurallyEquals(Arg2);
7934
7936 llvm::FoldingSetNodeID ID1, ID2;
7937 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7938 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7939 return ID1 == ID2;
7940 }
7941
7943 return llvm::equal(
7944 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7945 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7946 return isSameTemplateArgument(Arg1, Arg2);
7947 });
7948 }
7949
7950 llvm_unreachable("Unhandled template argument kind");
7951}
7952
7954 // Handle the non-qualified case efficiently.
7955 if (!T.hasLocalQualifiers()) {
7956 // Handle the common positive case fast.
7957 if (const auto *AT = dyn_cast<ArrayType>(T))
7958 return AT;
7959 }
7960
7961 // Handle the common negative case fast.
7962 if (!isa<ArrayType>(T.getCanonicalType()))
7963 return nullptr;
7964
7965 // Apply any qualifiers from the array type to the element type. This
7966 // implements C99 6.7.3p8: "If the specification of an array type includes
7967 // any type qualifiers, the element type is so qualified, not the array type."
7968
7969 // If we get here, we either have type qualifiers on the type, or we have
7970 // sugar such as a typedef in the way. If we have type qualifiers on the type
7971 // we must propagate them down into the element type.
7972
7973 SplitQualType split = T.getSplitDesugaredType();
7974 Qualifiers qs = split.Quals;
7975
7976 // If we have a simple case, just return now.
7977 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7978 if (!ATy || qs.empty())
7979 return ATy;
7980
7981 // Otherwise, we have an array and we have qualifiers on it. Push the
7982 // qualifiers into the array element type and return a new array type.
7983 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7984
7985 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7986 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7987 CAT->getSizeExpr(),
7988 CAT->getSizeModifier(),
7989 CAT->getIndexTypeCVRQualifiers()));
7990 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
7992 IAT->getSizeModifier(),
7993 IAT->getIndexTypeCVRQualifiers()));
7994
7995 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
7997 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
7998 DSAT->getIndexTypeCVRQualifiers()));
7999
8000 const auto *VAT = cast<VariableArrayType>(ATy);
8001 return cast<ArrayType>(
8002 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8003 VAT->getIndexTypeCVRQualifiers()));
8004}
8005
8007 if (getLangOpts().HLSL && T->isConstantArrayType())
8008 return getArrayParameterType(T);
8009 if (T->isArrayType() || T->isFunctionType())
8010 return getDecayedType(T);
8011 return T;
8012}
8013
8017 return T.getUnqualifiedType();
8018}
8019
8021 // C++ [except.throw]p3:
8022 // A throw-expression initializes a temporary object, called the exception
8023 // object, the type of which is determined by removing any top-level
8024 // cv-qualifiers from the static type of the operand of throw and adjusting
8025 // the type from "array of T" or "function returning T" to "pointer to T"
8026 // or "pointer to function returning T", [...]
8028 if (T->isArrayType() || T->isFunctionType())
8029 T = getDecayedType(T);
8030 return T.getUnqualifiedType();
8031}
8032
8033/// getArrayDecayedType - Return the properly qualified result of decaying the
8034/// specified array type to a pointer. This operation is non-trivial when
8035/// handling typedefs etc. The canonical type of "T" must be an array type,
8036/// this returns a pointer to a properly qualified element of the array.
8037///
8038/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8040 // Get the element type with 'getAsArrayType' so that we don't lose any
8041 // typedefs in the element type of the array. This also handles propagation
8042 // of type qualifiers from the array type into the element type if present
8043 // (C99 6.7.3p8).
8044 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8045 assert(PrettyArrayType && "Not an array type!");
8046
8047 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8048
8049 // int x[restrict 4] -> int *restrict
8051 PrettyArrayType->getIndexTypeQualifiers());
8052
8053 // int x[_Nullable] -> int * _Nullable
8054 if (auto Nullability = Ty->getNullability()) {
8055 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8056 Result, Result);
8057 }
8058 return Result;
8059}
8060
8062 return getBaseElementType(array->getElementType());
8063}
8064
8066 Qualifiers qs;
8067 while (true) {
8068 SplitQualType split = type.getSplitDesugaredType();
8069 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8070 if (!array) break;
8071
8072 type = array->getElementType();
8074 }
8075
8076 return getQualifiedType(type, qs);
8077}
8078
8079/// getConstantArrayElementCount - Returns number of constant array elements.
8080uint64_t
8082 uint64_t ElementCount = 1;
8083 do {
8084 ElementCount *= CA->getZExtSize();
8085 CA = dyn_cast_or_null<ConstantArrayType>(
8087 } while (CA);
8088 return ElementCount;
8089}
8090
8092 const ArrayInitLoopExpr *AILE) const {
8093 if (!AILE)
8094 return 0;
8095
8096 uint64_t ElementCount = 1;
8097
8098 do {
8099 ElementCount *= AILE->getArraySize().getZExtValue();
8100 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8101 } while (AILE);
8102
8103 return ElementCount;
8104}
8105
8106/// getFloatingRank - Return a relative rank for floating point types.
8107/// This routine will assert if passed a built-in type that isn't a float.
8109 if (const auto *CT = T->getAs<ComplexType>())
8110 return getFloatingRank(CT->getElementType());
8111
8112 switch (T->castAs<BuiltinType>()->getKind()) {
8113 default: llvm_unreachable("getFloatingRank(): not a floating type");
8114 case BuiltinType::Float16: return Float16Rank;
8115 case BuiltinType::Half: return HalfRank;
8116 case BuiltinType::Float: return FloatRank;
8117 case BuiltinType::Double: return DoubleRank;
8118 case BuiltinType::LongDouble: return LongDoubleRank;
8119 case BuiltinType::Float128: return Float128Rank;
8120 case BuiltinType::BFloat16: return BFloat16Rank;
8121 case BuiltinType::Ibm128: return Ibm128Rank;
8122 }
8123}
8124
8125/// getFloatingTypeOrder - Compare the rank of the two specified floating
8126/// point types, ignoring the domain of the type (i.e. 'double' ==
8127/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8128/// LHS < RHS, return -1.
8130 FloatingRank LHSR = getFloatingRank(LHS);
8131 FloatingRank RHSR = getFloatingRank(RHS);
8132
8133 if (LHSR == RHSR)
8134 return 0;
8135 if (LHSR > RHSR)
8136 return 1;
8137 return -1;
8138}
8139
8142 return 0;
8143 return getFloatingTypeOrder(LHS, RHS);
8144}
8145
8146/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8147/// routine will assert if passed a built-in type that isn't an integer or enum,
8148/// or if it is not canonicalized.
8149unsigned ASTContext::getIntegerRank(const Type *T) const {
8150 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8151
8152 // Results in this 'losing' to any type of the same size, but winning if
8153 // larger.
8154 if (const auto *EIT = dyn_cast<BitIntType>(T))
8155 return 0 + (EIT->getNumBits() << 3);
8156
8157 switch (cast<BuiltinType>(T)->getKind()) {
8158 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8159 case BuiltinType::Bool:
8160 return 1 + (getIntWidth(BoolTy) << 3);
8161 case BuiltinType::Char_S:
8162 case BuiltinType::Char_U:
8163 case BuiltinType::SChar:
8164 case BuiltinType::UChar:
8165 return 2 + (getIntWidth(CharTy) << 3);
8166 case BuiltinType::Short:
8167 case BuiltinType::UShort:
8168 return 3 + (getIntWidth(ShortTy) << 3);
8169 case BuiltinType::Int:
8170 case BuiltinType::UInt:
8171 return 4 + (getIntWidth(IntTy) << 3);
8172 case BuiltinType::Long:
8173 case BuiltinType::ULong:
8174 return 5 + (getIntWidth(LongTy) << 3);
8175 case BuiltinType::LongLong:
8176 case BuiltinType::ULongLong:
8177 return 6 + (getIntWidth(LongLongTy) << 3);
8178 case BuiltinType::Int128:
8179 case BuiltinType::UInt128:
8180 return 7 + (getIntWidth(Int128Ty) << 3);
8181
8182 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8183 // their underlying types" [c++20 conv.rank]
8184 case BuiltinType::Char8:
8185 return getIntegerRank(UnsignedCharTy.getTypePtr());
8186 case BuiltinType::Char16:
8187 return getIntegerRank(
8188 getFromTargetType(Target->getChar16Type()).getTypePtr());
8189 case BuiltinType::Char32:
8190 return getIntegerRank(
8191 getFromTargetType(Target->getChar32Type()).getTypePtr());
8192 case BuiltinType::WChar_S:
8193 case BuiltinType::WChar_U:
8194 return getIntegerRank(
8195 getFromTargetType(Target->getWCharType()).getTypePtr());
8196 }
8197}
8198
8199/// Whether this is a promotable bitfield reference according
8200/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8201///
8202/// \returns the type this bit-field will promote to, or NULL if no
8203/// promotion occurs.
8205 if (E->isTypeDependent() || E->isValueDependent())
8206 return {};
8207
8208 // C++ [conv.prom]p5:
8209 // If the bit-field has an enumerated type, it is treated as any other
8210 // value of that type for promotion purposes.
8212 return {};
8213
8214 // FIXME: We should not do this unless E->refersToBitField() is true. This
8215 // matters in C where getSourceBitField() will find bit-fields for various
8216 // cases where the source expression is not a bit-field designator.
8217
8218 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8219 if (!Field)
8220 return {};
8221
8222 QualType FT = Field->getType();
8223
8224 uint64_t BitWidth = Field->getBitWidthValue();
8225 uint64_t IntSize = getTypeSize(IntTy);
8226 // C++ [conv.prom]p5:
8227 // A prvalue for an integral bit-field can be converted to a prvalue of type
8228 // int if int can represent all the values of the bit-field; otherwise, it
8229 // can be converted to unsigned int if unsigned int can represent all the
8230 // values of the bit-field. If the bit-field is larger yet, no integral
8231 // promotion applies to it.
8232 // C11 6.3.1.1/2:
8233 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8234 // If an int can represent all values of the original type (as restricted by
8235 // the width, for a bit-field), the value is converted to an int; otherwise,
8236 // it is converted to an unsigned int.
8237 //
8238 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8239 // We perform that promotion here to match GCC and C++.
8240 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8241 // greater than that of 'int'. We perform that promotion to match GCC.
8242 //
8243 // C23 6.3.1.1p2:
8244 // The value from a bit-field of a bit-precise integer type is converted to
8245 // the corresponding bit-precise integer type. (The rest is the same as in
8246 // C11.)
8247 if (QualType QT = Field->getType(); QT->isBitIntType())
8248 return QT;
8249
8250 if (BitWidth < IntSize)
8251 return IntTy;
8252
8253 if (BitWidth == IntSize)
8254 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8255
8256 // Bit-fields wider than int are not subject to promotions, and therefore act
8257 // like the base type. GCC has some weird bugs in this area that we
8258 // deliberately do not follow (GCC follows a pre-standard resolution to
8259 // C's DR315 which treats bit-width as being part of the type, and this leaks
8260 // into their semantics in some cases).
8261 return {};
8262}
8263
8264/// getPromotedIntegerType - Returns the type that Promotable will
8265/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8266/// integer type.
8268 assert(!Promotable.isNull());
8269 assert(isPromotableIntegerType(Promotable));
8270 if (const auto *ED = Promotable->getAsEnumDecl())
8271 return ED->getPromotionType();
8272
8273 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8274 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8275 // (3.9.1) can be converted to a prvalue of the first of the following
8276 // types that can represent all the values of its underlying type:
8277 // int, unsigned int, long int, unsigned long int, long long int, or
8278 // unsigned long long int [...]
8279 // FIXME: Is there some better way to compute this?
8280 if (BT->getKind() == BuiltinType::WChar_S ||
8281 BT->getKind() == BuiltinType::WChar_U ||
8282 BT->getKind() == BuiltinType::Char8 ||
8283 BT->getKind() == BuiltinType::Char16 ||
8284 BT->getKind() == BuiltinType::Char32) {
8285 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8286 uint64_t FromSize = getTypeSize(BT);
8287 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8289 for (const auto &PT : PromoteTypes) {
8290 uint64_t ToSize = getTypeSize(PT);
8291 if (FromSize < ToSize ||
8292 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8293 return PT;
8294 }
8295 llvm_unreachable("char type should fit into long long");
8296 }
8297 }
8298
8299 // At this point, we should have a signed or unsigned integer type.
8300 if (Promotable->isSignedIntegerType())
8301 return IntTy;
8302 uint64_t PromotableSize = getIntWidth(Promotable);
8303 uint64_t IntSize = getIntWidth(IntTy);
8304 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8305 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8306}
8307
8308/// Recurses in pointer/array types until it finds an objc retainable
8309/// type and returns its ownership.
8311 while (!T.isNull()) {
8312 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8313 return T.getObjCLifetime();
8314 if (T->isArrayType())
8316 else if (const auto *PT = T->getAs<PointerType>())
8317 T = PT->getPointeeType();
8318 else if (const auto *RT = T->getAs<ReferenceType>())
8319 T = RT->getPointeeType();
8320 else
8321 break;
8322 }
8323
8324 return Qualifiers::OCL_None;
8325}
8326
8327static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8328 // Incomplete enum types are not treated as integer types.
8329 // FIXME: In C++, enum types are never integer types.
8330 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8331 if (ED->isComplete() && !ED->isScoped())
8332 return ED->getIntegerType().getTypePtr();
8333 return nullptr;
8334}
8335
8336/// getIntegerTypeOrder - Returns the highest ranked integer type:
8337/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8338/// LHS < RHS, return -1.
8340 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8341 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8342
8343 // Unwrap enums to their underlying type.
8344 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8345 LHSC = getIntegerTypeForEnum(ET);
8346 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8347 RHSC = getIntegerTypeForEnum(ET);
8348
8349 if (LHSC == RHSC) return 0;
8350
8351 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8352 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8353
8354 unsigned LHSRank = getIntegerRank(LHSC);
8355 unsigned RHSRank = getIntegerRank(RHSC);
8356
8357 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8358 if (LHSRank == RHSRank) return 0;
8359 return LHSRank > RHSRank ? 1 : -1;
8360 }
8361
8362 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8363 if (LHSUnsigned) {
8364 // If the unsigned [LHS] type is larger, return it.
8365 if (LHSRank >= RHSRank)
8366 return 1;
8367
8368 // If the signed type can represent all values of the unsigned type, it
8369 // wins. Because we are dealing with 2's complement and types that are
8370 // powers of two larger than each other, this is always safe.
8371 return -1;
8372 }
8373
8374 // If the unsigned [RHS] type is larger, return it.
8375 if (RHSRank >= LHSRank)
8376 return -1;
8377
8378 // If the signed type can represent all values of the unsigned type, it
8379 // wins. Because we are dealing with 2's complement and types that are
8380 // powers of two larger than each other, this is always safe.
8381 return 1;
8382}
8383
8385 if (CFConstantStringTypeDecl)
8386 return CFConstantStringTypeDecl;
8387
8388 assert(!CFConstantStringTagDecl &&
8389 "tag and typedef should be initialized together");
8390 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8391 CFConstantStringTagDecl->startDefinition();
8392
8393 struct {
8394 QualType Type;
8395 const char *Name;
8396 } Fields[5];
8397 unsigned Count = 0;
8398
8399 /// Objective-C ABI
8400 ///
8401 /// typedef struct __NSConstantString_tag {
8402 /// const int *isa;
8403 /// int flags;
8404 /// const char *str;
8405 /// long length;
8406 /// } __NSConstantString;
8407 ///
8408 /// Swift ABI (4.1, 4.2)
8409 ///
8410 /// typedef struct __NSConstantString_tag {
8411 /// uintptr_t _cfisa;
8412 /// uintptr_t _swift_rc;
8413 /// _Atomic(uint64_t) _cfinfoa;
8414 /// const char *_ptr;
8415 /// uint32_t _length;
8416 /// } __NSConstantString;
8417 ///
8418 /// Swift ABI (5.0)
8419 ///
8420 /// typedef struct __NSConstantString_tag {
8421 /// uintptr_t _cfisa;
8422 /// uintptr_t _swift_rc;
8423 /// _Atomic(uint64_t) _cfinfoa;
8424 /// const char *_ptr;
8425 /// uintptr_t _length;
8426 /// } __NSConstantString;
8427
8428 const auto CFRuntime = getLangOpts().CFRuntime;
8429 if (static_cast<unsigned>(CFRuntime) <
8430 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8431 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8432 Fields[Count++] = { IntTy, "flags" };
8433 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8434 Fields[Count++] = { LongTy, "length" };
8435 } else {
8436 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8437 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8438 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8439 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8442 Fields[Count++] = { IntTy, "_ptr" };
8443 else
8444 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8445 }
8446
8447 // Create fields
8448 for (unsigned i = 0; i < Count; ++i) {
8449 FieldDecl *Field =
8450 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8451 SourceLocation(), &Idents.get(Fields[i].Name),
8452 Fields[i].Type, /*TInfo=*/nullptr,
8453 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8454 Field->setAccess(AS_public);
8455 CFConstantStringTagDecl->addDecl(Field);
8456 }
8457
8458 CFConstantStringTagDecl->completeDefinition();
8459 // This type is designed to be compatible with NSConstantString, but cannot
8460 // use the same name, since NSConstantString is an interface.
8461 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8462 CFConstantStringTypeDecl =
8463 buildImplicitTypedef(tagType, "__NSConstantString");
8464
8465 return CFConstantStringTypeDecl;
8466}
8467
8469 if (!CFConstantStringTagDecl)
8470 getCFConstantStringDecl(); // Build the tag and the typedef.
8471 return CFConstantStringTagDecl;
8472}
8473
8474// getCFConstantStringType - Return the type used for constant CFStrings.
8479
8481 if (ObjCSuperType.isNull()) {
8482 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8483 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8484 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8485 }
8486 return ObjCSuperType;
8487}
8488
8490 const auto *TT = T->castAs<TypedefType>();
8491 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8492 CFConstantStringTagDecl = TT->castAsRecordDecl();
8493}
8494
8496 if (BlockDescriptorType)
8497 return getCanonicalTagType(BlockDescriptorType);
8498
8499 RecordDecl *RD;
8500 // FIXME: Needs the FlagAppleBlock bit.
8501 RD = buildImplicitRecord("__block_descriptor");
8502 RD->startDefinition();
8503
8504 QualType FieldTypes[] = {
8507 };
8508
8509 static const char *const FieldNames[] = {
8510 "reserved",
8511 "Size"
8512 };
8513
8514 for (size_t i = 0; i < 2; ++i) {
8516 *this, RD, SourceLocation(), SourceLocation(),
8517 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8518 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8519 Field->setAccess(AS_public);
8520 RD->addDecl(Field);
8521 }
8522
8523 RD->completeDefinition();
8524
8525 BlockDescriptorType = RD;
8526
8527 return getCanonicalTagType(BlockDescriptorType);
8528}
8529
8531 if (BlockDescriptorExtendedType)
8532 return getCanonicalTagType(BlockDescriptorExtendedType);
8533
8534 RecordDecl *RD;
8535 // FIXME: Needs the FlagAppleBlock bit.
8536 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8537 RD->startDefinition();
8538
8539 QualType FieldTypes[] = {
8544 };
8545
8546 static const char *const FieldNames[] = {
8547 "reserved",
8548 "Size",
8549 "CopyFuncPtr",
8550 "DestroyFuncPtr"
8551 };
8552
8553 for (size_t i = 0; i < 4; ++i) {
8555 *this, RD, SourceLocation(), SourceLocation(),
8556 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8557 /*BitWidth=*/nullptr,
8558 /*Mutable=*/false, ICIS_NoInit);
8559 Field->setAccess(AS_public);
8560 RD->addDecl(Field);
8561 }
8562
8563 RD->completeDefinition();
8564
8565 BlockDescriptorExtendedType = RD;
8566 return getCanonicalTagType(BlockDescriptorExtendedType);
8567}
8568
8570 const auto *BT = dyn_cast<BuiltinType>(T);
8571
8572 if (!BT) {
8573 if (isa<PipeType>(T))
8574 return OCLTK_Pipe;
8575
8576 return OCLTK_Default;
8577 }
8578
8579 switch (BT->getKind()) {
8580#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8581 case BuiltinType::Id: \
8582 return OCLTK_Image;
8583#include "clang/Basic/OpenCLImageTypes.def"
8584
8585 case BuiltinType::OCLClkEvent:
8586 return OCLTK_ClkEvent;
8587
8588 case BuiltinType::OCLEvent:
8589 return OCLTK_Event;
8590
8591 case BuiltinType::OCLQueue:
8592 return OCLTK_Queue;
8593
8594 case BuiltinType::OCLReserveID:
8595 return OCLTK_ReserveID;
8596
8597 case BuiltinType::OCLSampler:
8598 return OCLTK_Sampler;
8599
8600 default:
8601 return OCLTK_Default;
8602 }
8603}
8604
8606 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8607}
8608
8609/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8610/// requires copy/dispose. Note that this must match the logic
8611/// in buildByrefHelpers.
8613 const VarDecl *D) {
8614 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8615 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8616 if (!copyExpr && record->hasTrivialDestructor()) return false;
8617
8618 return true;
8619 }
8620
8622 return true;
8623
8624 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8625 // move or destroy.
8627 return true;
8628
8629 if (!Ty->isObjCRetainableType()) return false;
8630
8631 Qualifiers qs = Ty.getQualifiers();
8632
8633 // If we have lifetime, that dominates.
8634 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8635 switch (lifetime) {
8636 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8637
8638 // These are just bits as far as the runtime is concerned.
8641 return false;
8642
8643 // These cases should have been taken care of when checking the type's
8644 // non-triviality.
8647 llvm_unreachable("impossible");
8648 }
8649 llvm_unreachable("fell out of lifetime switch!");
8650 }
8651 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8653}
8654
8656 Qualifiers::ObjCLifetime &LifeTime,
8657 bool &HasByrefExtendedLayout) const {
8658 if (!getLangOpts().ObjC ||
8659 getLangOpts().getGC() != LangOptions::NonGC)
8660 return false;
8661
8662 HasByrefExtendedLayout = false;
8663 if (Ty->isRecordType()) {
8664 HasByrefExtendedLayout = true;
8665 LifeTime = Qualifiers::OCL_None;
8666 } else if ((LifeTime = Ty.getObjCLifetime())) {
8667 // Honor the ARC qualifiers.
8668 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8669 // The MRR rule.
8671 } else {
8672 LifeTime = Qualifiers::OCL_None;
8673 }
8674 return true;
8675}
8676
8678 assert(Target && "Expected target to be initialized");
8679 const llvm::Triple &T = Target->getTriple();
8680 // Windows is LLP64 rather than LP64
8681 if (T.isOSWindows() && T.isArch64Bit())
8682 return UnsignedLongLongTy;
8683 return UnsignedLongTy;
8684}
8685
8687 assert(Target && "Expected target to be initialized");
8688 const llvm::Triple &T = Target->getTriple();
8689 // Windows is LLP64 rather than LP64
8690 if (T.isOSWindows() && T.isArch64Bit())
8691 return LongLongTy;
8692 return LongTy;
8693}
8694
8696 if (!ObjCInstanceTypeDecl)
8697 ObjCInstanceTypeDecl =
8698 buildImplicitTypedef(getObjCIdType(), "instancetype");
8699 return ObjCInstanceTypeDecl;
8700}
8701
8702// This returns true if a type has been typedefed to BOOL:
8703// typedef <type> BOOL;
8705 if (const auto *TT = dyn_cast<TypedefType>(T))
8706 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8707 return II->isStr("BOOL");
8708
8709 return false;
8710}
8711
8712/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8713/// purpose.
8715 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8716 return CharUnits::Zero();
8717
8719
8720 // Make all integer and enum types at least as large as an int
8721 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8722 sz = std::max(sz, getTypeSizeInChars(IntTy));
8723 // Treat arrays as pointers, since that's how they're passed in.
8724 else if (type->isArrayType())
8726 return sz;
8727}
8728
8735
8738 if (!VD->isInline())
8740
8741 // In almost all cases, it's a weak definition.
8742 auto *First = VD->getFirstDecl();
8743 if (First->isInlineSpecified() || !First->isStaticDataMember())
8745
8746 // If there's a file-context declaration in this translation unit, it's a
8747 // non-discardable definition.
8748 for (auto *D : VD->redecls())
8750 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8752
8753 // If we've not seen one yet, we don't know.
8755}
8756
8757static std::string charUnitsToString(const CharUnits &CU) {
8758 return llvm::itostr(CU.getQuantity());
8759}
8760
8761/// getObjCEncodingForBlock - Return the encoded type for this block
8762/// declaration.
8764 std::string S;
8765
8766 const BlockDecl *Decl = Expr->getBlockDecl();
8767 QualType BlockTy =
8769 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8770 // Encode result type.
8771 if (getLangOpts().EncodeExtendedBlockSig)
8773 true /*Extended*/);
8774 else
8775 getObjCEncodingForType(BlockReturnTy, S);
8776 // Compute size of all parameters.
8777 // Start with computing size of a pointer in number of bytes.
8778 // FIXME: There might(should) be a better way of doing this computation!
8780 CharUnits ParmOffset = PtrSize;
8781 for (auto *PI : Decl->parameters()) {
8782 QualType PType = PI->getType();
8784 if (sz.isZero())
8785 continue;
8786 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8787 ParmOffset += sz;
8788 }
8789 // Size of the argument frame
8790 S += charUnitsToString(ParmOffset);
8791 // Block pointer and offset.
8792 S += "@?0";
8793
8794 // Argument types.
8795 ParmOffset = PtrSize;
8796 for (auto *PVDecl : Decl->parameters()) {
8797 QualType PType = PVDecl->getOriginalType();
8798 if (const auto *AT =
8799 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8800 // Use array's original type only if it has known number of
8801 // elements.
8802 if (!isa<ConstantArrayType>(AT))
8803 PType = PVDecl->getType();
8804 } else if (PType->isFunctionType())
8805 PType = PVDecl->getType();
8806 if (getLangOpts().EncodeExtendedBlockSig)
8808 S, true /*Extended*/);
8809 else
8810 getObjCEncodingForType(PType, S);
8811 S += charUnitsToString(ParmOffset);
8812 ParmOffset += getObjCEncodingTypeSize(PType);
8813 }
8814
8815 return S;
8816}
8817
8818std::string
8820 std::string S;
8821 // Encode result type.
8822 getObjCEncodingForType(Decl->getReturnType(), S);
8823 CharUnits ParmOffset;
8824 // Compute size of all parameters.
8825 for (auto *PI : Decl->parameters()) {
8826 QualType PType = PI->getType();
8828 if (sz.isZero())
8829 continue;
8830
8831 assert(sz.isPositive() &&
8832 "getObjCEncodingForFunctionDecl - Incomplete param type");
8833 ParmOffset += sz;
8834 }
8835 S += charUnitsToString(ParmOffset);
8836 ParmOffset = CharUnits::Zero();
8837
8838 // Argument types.
8839 for (auto *PVDecl : Decl->parameters()) {
8840 QualType PType = PVDecl->getOriginalType();
8841 if (const auto *AT =
8842 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8843 // Use array's original type only if it has known number of
8844 // elements.
8845 if (!isa<ConstantArrayType>(AT))
8846 PType = PVDecl->getType();
8847 } else if (PType->isFunctionType())
8848 PType = PVDecl->getType();
8849 getObjCEncodingForType(PType, S);
8850 S += charUnitsToString(ParmOffset);
8851 ParmOffset += getObjCEncodingTypeSize(PType);
8852 }
8853
8854 return S;
8855}
8856
8857/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8858/// method parameter or return type. If Extended, include class names and
8859/// block object types.
8861 QualType T, std::string& S,
8862 bool Extended) const {
8863 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8865 // Encode parameter type.
8866 ObjCEncOptions Options = ObjCEncOptions()
8867 .setExpandPointedToStructures()
8868 .setExpandStructures()
8869 .setIsOutermostType();
8870 if (Extended)
8871 Options.setEncodeBlockParameters().setEncodeClassNames();
8872 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8873}
8874
8875/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8876/// declaration.
8878 bool Extended) const {
8879 // FIXME: This is not very efficient.
8880 // Encode return type.
8881 std::string S;
8882 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8883 Decl->getReturnType(), S, Extended);
8884 // Compute size of all parameters.
8885 // Start with computing size of a pointer in number of bytes.
8886 // FIXME: There might(should) be a better way of doing this computation!
8888 // The first two arguments (self and _cmd) are pointers; account for
8889 // their size.
8890 CharUnits ParmOffset = 2 * PtrSize;
8891 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8892 E = Decl->sel_param_end(); PI != E; ++PI) {
8893 QualType PType = (*PI)->getType();
8895 if (sz.isZero())
8896 continue;
8897
8898 assert(sz.isPositive() &&
8899 "getObjCEncodingForMethodDecl - Incomplete param type");
8900 ParmOffset += sz;
8901 }
8902 S += charUnitsToString(ParmOffset);
8903 S += "@0:";
8904 S += charUnitsToString(PtrSize);
8905
8906 // Argument types.
8907 ParmOffset = 2 * PtrSize;
8908 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8909 E = Decl->sel_param_end(); PI != E; ++PI) {
8910 const ParmVarDecl *PVDecl = *PI;
8911 QualType PType = PVDecl->getOriginalType();
8912 if (const auto *AT =
8913 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8914 // Use array's original type only if it has known number of
8915 // elements.
8916 if (!isa<ConstantArrayType>(AT))
8917 PType = PVDecl->getType();
8918 } else if (PType->isFunctionType())
8919 PType = PVDecl->getType();
8921 PType, S, Extended);
8922 S += charUnitsToString(ParmOffset);
8923 ParmOffset += getObjCEncodingTypeSize(PType);
8924 }
8925
8926 return S;
8927}
8928
8931 const ObjCPropertyDecl *PD,
8932 const Decl *Container) const {
8933 if (!Container)
8934 return nullptr;
8935 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8936 for (auto *PID : CID->property_impls())
8937 if (PID->getPropertyDecl() == PD)
8938 return PID;
8939 } else {
8940 const auto *OID = cast<ObjCImplementationDecl>(Container);
8941 for (auto *PID : OID->property_impls())
8942 if (PID->getPropertyDecl() == PD)
8943 return PID;
8944 }
8945 return nullptr;
8946}
8947
8948/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8949/// property declaration. If non-NULL, Container must be either an
8950/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8951/// NULL when getting encodings for protocol properties.
8952/// Property attributes are stored as a comma-delimited C string. The simple
8953/// attributes readonly and bycopy are encoded as single characters. The
8954/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8955/// encoded as single characters, followed by an identifier. Property types
8956/// are also encoded as a parametrized attribute. The characters used to encode
8957/// these attributes are defined by the following enumeration:
8958/// @code
8959/// enum PropertyAttributes {
8960/// kPropertyReadOnly = 'R', // property is read-only.
8961/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8962/// kPropertyByref = '&', // property is a reference to the value last assigned
8963/// kPropertyDynamic = 'D', // property is dynamic
8964/// kPropertyGetter = 'G', // followed by getter selector name
8965/// kPropertySetter = 'S', // followed by setter selector name
8966/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8967/// kPropertyType = 'T' // followed by old-style type encoding.
8968/// kPropertyWeak = 'W' // 'weak' property
8969/// kPropertyStrong = 'P' // property GC'able
8970/// kPropertyNonAtomic = 'N' // property non-atomic
8971/// kPropertyOptional = '?' // property optional
8972/// };
8973/// @endcode
8974std::string
8976 const Decl *Container) const {
8977 // Collect information from the property implementation decl(s).
8978 bool Dynamic = false;
8979 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8980
8981 if (ObjCPropertyImplDecl *PropertyImpDecl =
8983 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8984 Dynamic = true;
8985 else
8986 SynthesizePID = PropertyImpDecl;
8987 }
8988
8989 // FIXME: This is not very efficient.
8990 std::string S = "T";
8991
8992 // Encode result type.
8993 // GCC has some special rules regarding encoding of properties which
8994 // closely resembles encoding of ivars.
8996
8997 if (PD->isOptional())
8998 S += ",?";
8999
9000 if (PD->isReadOnly()) {
9001 S += ",R";
9003 S += ",C";
9005 S += ",&";
9007 S += ",W";
9008 } else {
9009 switch (PD->getSetterKind()) {
9010 case ObjCPropertyDecl::Assign: break;
9011 case ObjCPropertyDecl::Copy: S += ",C"; break;
9012 case ObjCPropertyDecl::Retain: S += ",&"; break;
9013 case ObjCPropertyDecl::Weak: S += ",W"; break;
9014 }
9015 }
9016
9017 // It really isn't clear at all what this means, since properties
9018 // are "dynamic by default".
9019 if (Dynamic)
9020 S += ",D";
9021
9023 S += ",N";
9024
9026 S += ",G";
9027 S += PD->getGetterName().getAsString();
9028 }
9029
9031 S += ",S";
9032 S += PD->getSetterName().getAsString();
9033 }
9034
9035 if (SynthesizePID) {
9036 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9037 S += ",V";
9038 S += OID->getNameAsString();
9039 }
9040
9041 // FIXME: OBJCGC: weak & strong
9042 return S;
9043}
9044
9045/// getLegacyIntegralTypeEncoding -
9046/// Another legacy compatibility encoding: 32-bit longs are encoded as
9047/// 'l' or 'L' , but not always. For typedefs, we need to use
9048/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9050 if (PointeeTy->getAs<TypedefType>()) {
9051 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9052 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9053 PointeeTy = UnsignedIntTy;
9054 else
9055 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9056 PointeeTy = IntTy;
9057 }
9058 }
9059}
9060
9062 const FieldDecl *Field,
9063 QualType *NotEncodedT) const {
9064 // We follow the behavior of gcc, expanding structures which are
9065 // directly pointed to, and expanding embedded structures. Note that
9066 // these rules are sufficient to prevent recursive encoding of the
9067 // same type.
9068 getObjCEncodingForTypeImpl(T, S,
9069 ObjCEncOptions()
9070 .setExpandPointedToStructures()
9071 .setExpandStructures()
9072 .setIsOutermostType(),
9073 Field, NotEncodedT);
9074}
9075
9077 std::string& S) const {
9078 // Encode result type.
9079 // GCC has some special rules regarding encoding of properties which
9080 // closely resembles encoding of ivars.
9081 getObjCEncodingForTypeImpl(T, S,
9082 ObjCEncOptions()
9083 .setExpandPointedToStructures()
9084 .setExpandStructures()
9085 .setIsOutermostType()
9086 .setEncodingProperty(),
9087 /*Field=*/nullptr);
9088}
9089
9091 const BuiltinType *BT) {
9092 BuiltinType::Kind kind = BT->getKind();
9093 switch (kind) {
9094 case BuiltinType::Void: return 'v';
9095 case BuiltinType::Bool: return 'B';
9096 case BuiltinType::Char8:
9097 case BuiltinType::Char_U:
9098 case BuiltinType::UChar: return 'C';
9099 case BuiltinType::Char16:
9100 case BuiltinType::UShort: return 'S';
9101 case BuiltinType::Char32:
9102 case BuiltinType::UInt: return 'I';
9103 case BuiltinType::ULong:
9104 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9105 case BuiltinType::UInt128: return 'T';
9106 case BuiltinType::ULongLong: return 'Q';
9107 case BuiltinType::Char_S:
9108 case BuiltinType::SChar: return 'c';
9109 case BuiltinType::Short: return 's';
9110 case BuiltinType::WChar_S:
9111 case BuiltinType::WChar_U:
9112 case BuiltinType::Int: return 'i';
9113 case BuiltinType::Long:
9114 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9115 case BuiltinType::LongLong: return 'q';
9116 case BuiltinType::Int128: return 't';
9117 case BuiltinType::Float: return 'f';
9118 case BuiltinType::Double: return 'd';
9119 case BuiltinType::LongDouble: return 'D';
9120 case BuiltinType::NullPtr: return '*'; // like char*
9121
9122 case BuiltinType::BFloat16:
9123 case BuiltinType::Float16:
9124 case BuiltinType::Float128:
9125 case BuiltinType::Ibm128:
9126 case BuiltinType::Half:
9127 case BuiltinType::ShortAccum:
9128 case BuiltinType::Accum:
9129 case BuiltinType::LongAccum:
9130 case BuiltinType::UShortAccum:
9131 case BuiltinType::UAccum:
9132 case BuiltinType::ULongAccum:
9133 case BuiltinType::ShortFract:
9134 case BuiltinType::Fract:
9135 case BuiltinType::LongFract:
9136 case BuiltinType::UShortFract:
9137 case BuiltinType::UFract:
9138 case BuiltinType::ULongFract:
9139 case BuiltinType::SatShortAccum:
9140 case BuiltinType::SatAccum:
9141 case BuiltinType::SatLongAccum:
9142 case BuiltinType::SatUShortAccum:
9143 case BuiltinType::SatUAccum:
9144 case BuiltinType::SatULongAccum:
9145 case BuiltinType::SatShortFract:
9146 case BuiltinType::SatFract:
9147 case BuiltinType::SatLongFract:
9148 case BuiltinType::SatUShortFract:
9149 case BuiltinType::SatUFract:
9150 case BuiltinType::SatULongFract:
9151 // FIXME: potentially need @encodes for these!
9152 return ' ';
9153
9154#define SVE_TYPE(Name, Id, SingletonId) \
9155 case BuiltinType::Id:
9156#include "clang/Basic/AArch64ACLETypes.def"
9157#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9158#include "clang/Basic/RISCVVTypes.def"
9159#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9160#include "clang/Basic/WebAssemblyReferenceTypes.def"
9161#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9162#include "clang/Basic/AMDGPUTypes.def"
9163 {
9164 DiagnosticsEngine &Diags = C->getDiagnostics();
9165 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9166 "cannot yet @encode type %0");
9167 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9168 return ' ';
9169 }
9170
9171 case BuiltinType::ObjCId:
9172 case BuiltinType::ObjCClass:
9173 case BuiltinType::ObjCSel:
9174 llvm_unreachable("@encoding ObjC primitive type");
9175
9176 // OpenCL and placeholder types don't need @encodings.
9177#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9178 case BuiltinType::Id:
9179#include "clang/Basic/OpenCLImageTypes.def"
9180#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9181 case BuiltinType::Id:
9182#include "clang/Basic/OpenCLExtensionTypes.def"
9183 case BuiltinType::OCLEvent:
9184 case BuiltinType::OCLClkEvent:
9185 case BuiltinType::OCLQueue:
9186 case BuiltinType::OCLReserveID:
9187 case BuiltinType::OCLSampler:
9188 case BuiltinType::Dependent:
9189#define PPC_VECTOR_TYPE(Name, Id, Size) \
9190 case BuiltinType::Id:
9191#include "clang/Basic/PPCTypes.def"
9192#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9193#include "clang/Basic/HLSLIntangibleTypes.def"
9194#define BUILTIN_TYPE(KIND, ID)
9195#define PLACEHOLDER_TYPE(KIND, ID) \
9196 case BuiltinType::KIND:
9197#include "clang/AST/BuiltinTypes.def"
9198 llvm_unreachable("invalid builtin type for @encode");
9199 }
9200 llvm_unreachable("invalid BuiltinType::Kind value");
9201}
9202
9203static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9205
9206 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9207 if (!Enum->isFixed())
9208 return 'i';
9209
9210 // The encoding of a fixed enum type matches its fixed underlying type.
9211 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9213}
9214
9215static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9216 QualType T, const FieldDecl *FD) {
9217 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9218 S += 'b';
9219 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9220 // The GNU runtime requires more information; bitfields are encoded as b,
9221 // then the offset (in bits) of the first element, then the type of the
9222 // bitfield, then the size in bits. For example, in this structure:
9223 //
9224 // struct
9225 // {
9226 // int integer;
9227 // int flags:2;
9228 // };
9229 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9230 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9231 // information is not especially sensible, but we're stuck with it for
9232 // compatibility with GCC, although providing it breaks anything that
9233 // actually uses runtime introspection and wants to work on both runtimes...
9234 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9235 uint64_t Offset;
9236
9237 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9238 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9239 } else {
9240 const RecordDecl *RD = FD->getParent();
9241 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9242 Offset = RL.getFieldOffset(FD->getFieldIndex());
9243 }
9244
9245 S += llvm::utostr(Offset);
9246
9247 if (const auto *ET = T->getAsCanonical<EnumType>())
9248 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9249 else {
9250 const auto *BT = T->castAs<BuiltinType>();
9251 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9252 }
9253 }
9254 S += llvm::utostr(FD->getBitWidthValue());
9255}
9256
9257// Helper function for determining whether the encoded type string would include
9258// a template specialization type.
9260 bool VisitBasesAndFields) {
9261 T = T->getBaseElementTypeUnsafe();
9262
9263 if (auto *PT = T->getAs<PointerType>())
9265 PT->getPointeeType().getTypePtr(), false);
9266
9267 auto *CXXRD = T->getAsCXXRecordDecl();
9268
9269 if (!CXXRD)
9270 return false;
9271
9273 return true;
9274
9275 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9276 return false;
9277
9278 for (const auto &B : CXXRD->bases())
9279 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9280 true))
9281 return true;
9282
9283 for (auto *FD : CXXRD->fields())
9284 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9285 true))
9286 return true;
9287
9288 return false;
9289}
9290
9291// FIXME: Use SmallString for accumulating string.
9292void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9293 const ObjCEncOptions Options,
9294 const FieldDecl *FD,
9295 QualType *NotEncodedT) const {
9297 switch (CT->getTypeClass()) {
9298 case Type::Builtin:
9299 case Type::Enum:
9300 if (FD && FD->isBitField())
9301 return EncodeBitField(this, S, T, FD);
9302 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9303 S += getObjCEncodingForPrimitiveType(this, BT);
9304 else
9305 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9306 return;
9307
9308 case Type::Complex:
9309 S += 'j';
9310 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9311 ObjCEncOptions(),
9312 /*Field=*/nullptr);
9313 return;
9314
9315 case Type::Atomic:
9316 S += 'A';
9317 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9318 ObjCEncOptions(),
9319 /*Field=*/nullptr);
9320 return;
9321
9322 // encoding for pointer or reference types.
9323 case Type::Pointer:
9324 case Type::LValueReference:
9325 case Type::RValueReference: {
9326 QualType PointeeTy;
9327 if (isa<PointerType>(CT)) {
9328 const auto *PT = T->castAs<PointerType>();
9329 if (PT->isObjCSelType()) {
9330 S += ':';
9331 return;
9332 }
9333 PointeeTy = PT->getPointeeType();
9334 } else {
9335 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9336 }
9337
9338 bool isReadOnly = false;
9339 // For historical/compatibility reasons, the read-only qualifier of the
9340 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9341 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9342 // Also, do not emit the 'r' for anything but the outermost type!
9343 if (T->getAs<TypedefType>()) {
9344 if (Options.IsOutermostType() && T.isConstQualified()) {
9345 isReadOnly = true;
9346 S += 'r';
9347 }
9348 } else if (Options.IsOutermostType()) {
9349 QualType P = PointeeTy;
9350 while (auto PT = P->getAs<PointerType>())
9351 P = PT->getPointeeType();
9352 if (P.isConstQualified()) {
9353 isReadOnly = true;
9354 S += 'r';
9355 }
9356 }
9357 if (isReadOnly) {
9358 // Another legacy compatibility encoding. Some ObjC qualifier and type
9359 // combinations need to be rearranged.
9360 // Rewrite "in const" from "nr" to "rn"
9361 if (StringRef(S).ends_with("nr"))
9362 S.replace(S.end()-2, S.end(), "rn");
9363 }
9364
9365 if (PointeeTy->isCharType()) {
9366 // char pointer types should be encoded as '*' unless it is a
9367 // type that has been typedef'd to 'BOOL'.
9368 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9369 S += '*';
9370 return;
9371 }
9372 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9373 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9374 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9375 if (II == &Idents.get("objc_class")) {
9376 S += '#';
9377 return;
9378 }
9379 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9380 if (II == &Idents.get("objc_object")) {
9381 S += '@';
9382 return;
9383 }
9384 // If the encoded string for the class includes template names, just emit
9385 // "^v" for pointers to the class.
9386 if (getLangOpts().CPlusPlus &&
9387 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9389 RTy, Options.ExpandPointedToStructures()))) {
9390 S += "^v";
9391 return;
9392 }
9393 // fall through...
9394 }
9395 S += '^';
9397
9398 ObjCEncOptions NewOptions;
9399 if (Options.ExpandPointedToStructures())
9400 NewOptions.setExpandStructures();
9401 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9402 /*Field=*/nullptr, NotEncodedT);
9403 return;
9404 }
9405
9406 case Type::ConstantArray:
9407 case Type::IncompleteArray:
9408 case Type::VariableArray: {
9409 const auto *AT = cast<ArrayType>(CT);
9410
9411 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9412 // Incomplete arrays are encoded as a pointer to the array element.
9413 S += '^';
9414
9415 getObjCEncodingForTypeImpl(
9416 AT->getElementType(), S,
9417 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9418 } else {
9419 S += '[';
9420
9421 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9422 S += llvm::utostr(CAT->getZExtSize());
9423 else {
9424 //Variable length arrays are encoded as a regular array with 0 elements.
9426 "Unknown array type!");
9427 S += '0';
9428 }
9429
9430 getObjCEncodingForTypeImpl(
9431 AT->getElementType(), S,
9432 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9433 NotEncodedT);
9434 S += ']';
9435 }
9436 return;
9437 }
9438
9439 case Type::FunctionNoProto:
9440 case Type::FunctionProto:
9441 S += '?';
9442 return;
9443
9444 case Type::Record: {
9445 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9446 S += RDecl->isUnion() ? '(' : '{';
9447 // Anonymous structures print as '?'
9448 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9449 S += II->getName();
9450 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9451 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9452 llvm::raw_string_ostream OS(S);
9453 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9455 }
9456 } else {
9457 S += '?';
9458 }
9459 if (Options.ExpandStructures()) {
9460 S += '=';
9461 if (!RDecl->isUnion()) {
9462 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9463 } else {
9464 for (const auto *Field : RDecl->fields()) {
9465 if (FD) {
9466 S += '"';
9467 S += Field->getNameAsString();
9468 S += '"';
9469 }
9470
9471 // Special case bit-fields.
9472 if (Field->isBitField()) {
9473 getObjCEncodingForTypeImpl(Field->getType(), S,
9474 ObjCEncOptions().setExpandStructures(),
9475 Field);
9476 } else {
9477 QualType qt = Field->getType();
9479 getObjCEncodingForTypeImpl(
9480 qt, S,
9481 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9482 NotEncodedT);
9483 }
9484 }
9485 }
9486 }
9487 S += RDecl->isUnion() ? ')' : '}';
9488 return;
9489 }
9490
9491 case Type::BlockPointer: {
9492 const auto *BT = T->castAs<BlockPointerType>();
9493 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9494 if (Options.EncodeBlockParameters()) {
9495 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9496
9497 S += '<';
9498 // Block return type
9499 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9500 Options.forComponentType(), FD, NotEncodedT);
9501 // Block self
9502 S += "@?";
9503 // Block parameters
9504 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9505 for (const auto &I : FPT->param_types())
9506 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9507 NotEncodedT);
9508 }
9509 S += '>';
9510 }
9511 return;
9512 }
9513
9514 case Type::ObjCObject: {
9515 // hack to match legacy encoding of *id and *Class
9516 QualType Ty = getObjCObjectPointerType(CT);
9517 if (Ty->isObjCIdType()) {
9518 S += "{objc_object=}";
9519 return;
9520 }
9521 else if (Ty->isObjCClassType()) {
9522 S += "{objc_class=}";
9523 return;
9524 }
9525 // TODO: Double check to make sure this intentionally falls through.
9526 [[fallthrough]];
9527 }
9528
9529 case Type::ObjCInterface: {
9530 // Ignore protocol qualifiers when mangling at this level.
9531 // @encode(class_name)
9532 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9533 S += '{';
9534 S += OI->getObjCRuntimeNameAsString();
9535 if (Options.ExpandStructures()) {
9536 S += '=';
9537 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9538 DeepCollectObjCIvars(OI, true, Ivars);
9539 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9540 const FieldDecl *Field = Ivars[i];
9541 if (Field->isBitField())
9542 getObjCEncodingForTypeImpl(Field->getType(), S,
9543 ObjCEncOptions().setExpandStructures(),
9544 Field);
9545 else
9546 getObjCEncodingForTypeImpl(Field->getType(), S,
9547 ObjCEncOptions().setExpandStructures(), FD,
9548 NotEncodedT);
9549 }
9550 }
9551 S += '}';
9552 return;
9553 }
9554
9555 case Type::ObjCObjectPointer: {
9556 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9557 if (OPT->isObjCIdType()) {
9558 S += '@';
9559 return;
9560 }
9561
9562 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9563 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9564 // Since this is a binary compatibility issue, need to consult with
9565 // runtime folks. Fortunately, this is a *very* obscure construct.
9566 S += '#';
9567 return;
9568 }
9569
9570 if (OPT->isObjCQualifiedIdType()) {
9571 getObjCEncodingForTypeImpl(
9572 getObjCIdType(), S,
9573 Options.keepingOnly(ObjCEncOptions()
9574 .setExpandPointedToStructures()
9575 .setExpandStructures()),
9576 FD);
9577 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9578 // Note that we do extended encoding of protocol qualifier list
9579 // Only when doing ivar or property encoding.
9580 S += '"';
9581 for (const auto *I : OPT->quals()) {
9582 S += '<';
9583 S += I->getObjCRuntimeNameAsString();
9584 S += '>';
9585 }
9586 S += '"';
9587 }
9588 return;
9589 }
9590
9591 S += '@';
9592 if (OPT->getInterfaceDecl() &&
9593 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9594 S += '"';
9595 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9596 for (const auto *I : OPT->quals()) {
9597 S += '<';
9598 S += I->getObjCRuntimeNameAsString();
9599 S += '>';
9600 }
9601 S += '"';
9602 }
9603 return;
9604 }
9605
9606 // gcc just blithely ignores member pointers.
9607 // FIXME: we should do better than that. 'M' is available.
9608 case Type::MemberPointer:
9609 // This matches gcc's encoding, even though technically it is insufficient.
9610 //FIXME. We should do a better job than gcc.
9611 case Type::Vector:
9612 case Type::ExtVector:
9613 // Until we have a coherent encoding of these three types, issue warning.
9614 if (NotEncodedT)
9615 *NotEncodedT = T;
9616 return;
9617
9618 case Type::ConstantMatrix:
9619 if (NotEncodedT)
9620 *NotEncodedT = T;
9621 return;
9622
9623 case Type::BitInt:
9624 if (NotEncodedT)
9625 *NotEncodedT = T;
9626 return;
9627
9628 // We could see an undeduced auto type here during error recovery.
9629 // Just ignore it.
9630 case Type::Auto:
9631 case Type::DeducedTemplateSpecialization:
9632 return;
9633
9634 case Type::HLSLAttributedResource:
9635 case Type::HLSLInlineSpirv:
9636 llvm_unreachable("unexpected type");
9637
9638 case Type::ArrayParameter:
9639 case Type::Pipe:
9640#define ABSTRACT_TYPE(KIND, BASE)
9641#define TYPE(KIND, BASE)
9642#define DEPENDENT_TYPE(KIND, BASE) \
9643 case Type::KIND:
9644#define NON_CANONICAL_TYPE(KIND, BASE) \
9645 case Type::KIND:
9646#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9647 case Type::KIND:
9648#include "clang/AST/TypeNodes.inc"
9649 llvm_unreachable("@encode for dependent type!");
9650 }
9651 llvm_unreachable("bad type kind!");
9652}
9653
9654void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9655 std::string &S,
9656 const FieldDecl *FD,
9657 bool includeVBases,
9658 QualType *NotEncodedT) const {
9659 assert(RDecl && "Expected non-null RecordDecl");
9660 assert(!RDecl->isUnion() && "Should not be called for unions");
9661 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9662 return;
9663
9664 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9665 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9666 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9667
9668 if (CXXRec) {
9669 for (const auto &BI : CXXRec->bases()) {
9670 if (!BI.isVirtual()) {
9671 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9672 if (base->isEmpty())
9673 continue;
9674 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9675 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9676 std::make_pair(offs, base));
9677 }
9678 }
9679 }
9680
9681 for (FieldDecl *Field : RDecl->fields()) {
9682 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9683 continue;
9684 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9685 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9686 std::make_pair(offs, Field));
9687 }
9688
9689 if (CXXRec && includeVBases) {
9690 for (const auto &BI : CXXRec->vbases()) {
9691 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9692 if (base->isEmpty())
9693 continue;
9694 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9695 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9696 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9697 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9698 std::make_pair(offs, base));
9699 }
9700 }
9701
9702 CharUnits size;
9703 if (CXXRec) {
9704 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9705 } else {
9706 size = layout.getSize();
9707 }
9708
9709#ifndef NDEBUG
9710 uint64_t CurOffs = 0;
9711#endif
9712 std::multimap<uint64_t, NamedDecl *>::iterator
9713 CurLayObj = FieldOrBaseOffsets.begin();
9714
9715 if (CXXRec && CXXRec->isDynamicClass() &&
9716 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9717 if (FD) {
9718 S += "\"_vptr$";
9719 std::string recname = CXXRec->getNameAsString();
9720 if (recname.empty()) recname = "?";
9721 S += recname;
9722 S += '"';
9723 }
9724 S += "^^?";
9725#ifndef NDEBUG
9726 CurOffs += getTypeSize(VoidPtrTy);
9727#endif
9728 }
9729
9730 if (!RDecl->hasFlexibleArrayMember()) {
9731 // Mark the end of the structure.
9732 uint64_t offs = toBits(size);
9733 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9734 std::make_pair(offs, nullptr));
9735 }
9736
9737 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9738#ifndef NDEBUG
9739 assert(CurOffs <= CurLayObj->first);
9740 if (CurOffs < CurLayObj->first) {
9741 uint64_t padding = CurLayObj->first - CurOffs;
9742 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9743 // packing/alignment of members is different that normal, in which case
9744 // the encoding will be out-of-sync with the real layout.
9745 // If the runtime switches to just consider the size of types without
9746 // taking into account alignment, we could make padding explicit in the
9747 // encoding (e.g. using arrays of chars). The encoding strings would be
9748 // longer then though.
9749 CurOffs += padding;
9750 }
9751#endif
9752
9753 NamedDecl *dcl = CurLayObj->second;
9754 if (!dcl)
9755 break; // reached end of structure.
9756
9757 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9758 // We expand the bases without their virtual bases since those are going
9759 // in the initial structure. Note that this differs from gcc which
9760 // expands virtual bases each time one is encountered in the hierarchy,
9761 // making the encoding type bigger than it really is.
9762 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9763 NotEncodedT);
9764 assert(!base->isEmpty());
9765#ifndef NDEBUG
9766 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9767#endif
9768 } else {
9769 const auto *field = cast<FieldDecl>(dcl);
9770 if (FD) {
9771 S += '"';
9772 S += field->getNameAsString();
9773 S += '"';
9774 }
9775
9776 if (field->isBitField()) {
9777 EncodeBitField(this, S, field->getType(), field);
9778#ifndef NDEBUG
9779 CurOffs += field->getBitWidthValue();
9780#endif
9781 } else {
9782 QualType qt = field->getType();
9784 getObjCEncodingForTypeImpl(
9785 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9786 FD, NotEncodedT);
9787#ifndef NDEBUG
9788 CurOffs += getTypeSize(field->getType());
9789#endif
9790 }
9791 }
9792 }
9793}
9794
9796 std::string& S) const {
9797 if (QT & Decl::OBJC_TQ_In)
9798 S += 'n';
9799 if (QT & Decl::OBJC_TQ_Inout)
9800 S += 'N';
9801 if (QT & Decl::OBJC_TQ_Out)
9802 S += 'o';
9803 if (QT & Decl::OBJC_TQ_Bycopy)
9804 S += 'O';
9805 if (QT & Decl::OBJC_TQ_Byref)
9806 S += 'R';
9807 if (QT & Decl::OBJC_TQ_Oneway)
9808 S += 'V';
9809}
9810
9812 if (!ObjCIdDecl) {
9815 ObjCIdDecl = buildImplicitTypedef(T, "id");
9816 }
9817 return ObjCIdDecl;
9818}
9819
9821 if (!ObjCSelDecl) {
9823 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9824 }
9825 return ObjCSelDecl;
9826}
9827
9829 if (!ObjCClassDecl) {
9832 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9833 }
9834 return ObjCClassDecl;
9835}
9836
9838 if (!ObjCProtocolClassDecl) {
9839 ObjCProtocolClassDecl
9842 &Idents.get("Protocol"),
9843 /*typeParamList=*/nullptr,
9844 /*PrevDecl=*/nullptr,
9845 SourceLocation(), true);
9846 }
9847
9848 return ObjCProtocolClassDecl;
9849}
9850
9852 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9853 return PointerAuthQualifier();
9855 getLangOpts().PointerAuthObjcInterfaceSelKey,
9856 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9858 /*isIsaPointer=*/false,
9859 /*authenticatesNullValues=*/false);
9860}
9861
9862//===----------------------------------------------------------------------===//
9863// __builtin_va_list Construction Functions
9864//===----------------------------------------------------------------------===//
9865
9867 StringRef Name) {
9868 // typedef char* __builtin[_ms]_va_list;
9869 QualType T = Context->getPointerType(Context->CharTy);
9870 return Context->buildImplicitTypedef(T, Name);
9871}
9872
9874 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9875}
9876
9878 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9879}
9880
9882 // typedef void* __builtin_va_list;
9883 QualType T = Context->getPointerType(Context->VoidTy);
9884 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9885}
9886
9887static TypedefDecl *
9889 // struct __va_list
9890 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9891 if (Context->getLangOpts().CPlusPlus) {
9892 // namespace std { struct __va_list {
9893 auto *NS = NamespaceDecl::Create(
9894 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9895 /*Inline=*/false, SourceLocation(), SourceLocation(),
9896 &Context->Idents.get("std"),
9897 /*PrevDecl=*/nullptr, /*Nested=*/false);
9898 NS->setImplicit();
9900 }
9901
9902 VaListTagDecl->startDefinition();
9903
9904 const size_t NumFields = 5;
9905 QualType FieldTypes[NumFields];
9906 const char *FieldNames[NumFields];
9907
9908 // void *__stack;
9909 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9910 FieldNames[0] = "__stack";
9911
9912 // void *__gr_top;
9913 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9914 FieldNames[1] = "__gr_top";
9915
9916 // void *__vr_top;
9917 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9918 FieldNames[2] = "__vr_top";
9919
9920 // int __gr_offs;
9921 FieldTypes[3] = Context->IntTy;
9922 FieldNames[3] = "__gr_offs";
9923
9924 // int __vr_offs;
9925 FieldTypes[4] = Context->IntTy;
9926 FieldNames[4] = "__vr_offs";
9927
9928 // Create fields
9929 for (unsigned i = 0; i < NumFields; ++i) {
9930 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9934 &Context->Idents.get(FieldNames[i]),
9935 FieldTypes[i], /*TInfo=*/nullptr,
9936 /*BitWidth=*/nullptr,
9937 /*Mutable=*/false,
9938 ICIS_NoInit);
9939 Field->setAccess(AS_public);
9940 VaListTagDecl->addDecl(Field);
9941 }
9942 VaListTagDecl->completeDefinition();
9943 Context->VaListTagDecl = VaListTagDecl;
9944 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9945
9946 // } __builtin_va_list;
9947 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9948}
9949
9951 // typedef struct __va_list_tag {
9953
9954 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9955 VaListTagDecl->startDefinition();
9956
9957 const size_t NumFields = 5;
9958 QualType FieldTypes[NumFields];
9959 const char *FieldNames[NumFields];
9960
9961 // unsigned char gpr;
9962 FieldTypes[0] = Context->UnsignedCharTy;
9963 FieldNames[0] = "gpr";
9964
9965 // unsigned char fpr;
9966 FieldTypes[1] = Context->UnsignedCharTy;
9967 FieldNames[1] = "fpr";
9968
9969 // unsigned short reserved;
9970 FieldTypes[2] = Context->UnsignedShortTy;
9971 FieldNames[2] = "reserved";
9972
9973 // void* overflow_arg_area;
9974 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9975 FieldNames[3] = "overflow_arg_area";
9976
9977 // void* reg_save_area;
9978 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9979 FieldNames[4] = "reg_save_area";
9980
9981 // Create fields
9982 for (unsigned i = 0; i < NumFields; ++i) {
9983 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9986 &Context->Idents.get(FieldNames[i]),
9987 FieldTypes[i], /*TInfo=*/nullptr,
9988 /*BitWidth=*/nullptr,
9989 /*Mutable=*/false,
9990 ICIS_NoInit);
9991 Field->setAccess(AS_public);
9992 VaListTagDecl->addDecl(Field);
9993 }
9994 VaListTagDecl->completeDefinition();
9995 Context->VaListTagDecl = VaListTagDecl;
9996 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9997
9998 // } __va_list_tag;
9999 TypedefDecl *VaListTagTypedefDecl =
10000 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10001
10002 QualType VaListTagTypedefType =
10003 Context->getTypedefType(ElaboratedTypeKeyword::None,
10004 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10005
10006 // typedef __va_list_tag __builtin_va_list[1];
10007 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10008 QualType VaListTagArrayType = Context->getConstantArrayType(
10009 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10010 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10011}
10012
10013static TypedefDecl *
10015 // struct __va_list_tag {
10017 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10018 VaListTagDecl->startDefinition();
10019
10020 const size_t NumFields = 4;
10021 QualType FieldTypes[NumFields];
10022 const char *FieldNames[NumFields];
10023
10024 // unsigned gp_offset;
10025 FieldTypes[0] = Context->UnsignedIntTy;
10026 FieldNames[0] = "gp_offset";
10027
10028 // unsigned fp_offset;
10029 FieldTypes[1] = Context->UnsignedIntTy;
10030 FieldNames[1] = "fp_offset";
10031
10032 // void* overflow_arg_area;
10033 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10034 FieldNames[2] = "overflow_arg_area";
10035
10036 // void* reg_save_area;
10037 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10038 FieldNames[3] = "reg_save_area";
10039
10040 // Create fields
10041 for (unsigned i = 0; i < NumFields; ++i) {
10042 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10046 &Context->Idents.get(FieldNames[i]),
10047 FieldTypes[i], /*TInfo=*/nullptr,
10048 /*BitWidth=*/nullptr,
10049 /*Mutable=*/false,
10050 ICIS_NoInit);
10051 Field->setAccess(AS_public);
10052 VaListTagDecl->addDecl(Field);
10053 }
10054 VaListTagDecl->completeDefinition();
10055 Context->VaListTagDecl = VaListTagDecl;
10056 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10057
10058 // };
10059
10060 // typedef struct __va_list_tag __builtin_va_list[1];
10061 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10062 QualType VaListTagArrayType = Context->getConstantArrayType(
10063 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10064 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10065}
10066
10067static TypedefDecl *
10069 // struct __va_list
10070 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10071 if (Context->getLangOpts().CPlusPlus) {
10072 // namespace std { struct __va_list {
10073 NamespaceDecl *NS;
10074 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10075 Context->getTranslationUnitDecl(),
10076 /*Inline=*/false, SourceLocation(),
10077 SourceLocation(), &Context->Idents.get("std"),
10078 /*PrevDecl=*/nullptr, /*Nested=*/false);
10079 NS->setImplicit();
10080 VaListDecl->setDeclContext(NS);
10081 }
10082
10083 VaListDecl->startDefinition();
10084
10085 // void * __ap;
10086 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10087 VaListDecl,
10090 &Context->Idents.get("__ap"),
10091 Context->getPointerType(Context->VoidTy),
10092 /*TInfo=*/nullptr,
10093 /*BitWidth=*/nullptr,
10094 /*Mutable=*/false,
10095 ICIS_NoInit);
10096 Field->setAccess(AS_public);
10097 VaListDecl->addDecl(Field);
10098
10099 // };
10100 VaListDecl->completeDefinition();
10101 Context->VaListTagDecl = VaListDecl;
10102
10103 // typedef struct __va_list __builtin_va_list;
10104 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10105 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10106}
10107
10108static TypedefDecl *
10110 // struct __va_list_tag {
10112 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10113 VaListTagDecl->startDefinition();
10114
10115 const size_t NumFields = 4;
10116 QualType FieldTypes[NumFields];
10117 const char *FieldNames[NumFields];
10118
10119 // long __gpr;
10120 FieldTypes[0] = Context->LongTy;
10121 FieldNames[0] = "__gpr";
10122
10123 // long __fpr;
10124 FieldTypes[1] = Context->LongTy;
10125 FieldNames[1] = "__fpr";
10126
10127 // void *__overflow_arg_area;
10128 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10129 FieldNames[2] = "__overflow_arg_area";
10130
10131 // void *__reg_save_area;
10132 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10133 FieldNames[3] = "__reg_save_area";
10134
10135 // Create fields
10136 for (unsigned i = 0; i < NumFields; ++i) {
10137 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10141 &Context->Idents.get(FieldNames[i]),
10142 FieldTypes[i], /*TInfo=*/nullptr,
10143 /*BitWidth=*/nullptr,
10144 /*Mutable=*/false,
10145 ICIS_NoInit);
10146 Field->setAccess(AS_public);
10147 VaListTagDecl->addDecl(Field);
10148 }
10149 VaListTagDecl->completeDefinition();
10150 Context->VaListTagDecl = VaListTagDecl;
10151 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10152
10153 // };
10154
10155 // typedef __va_list_tag __builtin_va_list[1];
10156 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10157 QualType VaListTagArrayType = Context->getConstantArrayType(
10158 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10159
10160 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10161}
10162
10164 // typedef struct __va_list_tag {
10166 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10167 VaListTagDecl->startDefinition();
10168
10169 const size_t NumFields = 3;
10170 QualType FieldTypes[NumFields];
10171 const char *FieldNames[NumFields];
10172
10173 // void *CurrentSavedRegisterArea;
10174 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10175 FieldNames[0] = "__current_saved_reg_area_pointer";
10176
10177 // void *SavedRegAreaEnd;
10178 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10179 FieldNames[1] = "__saved_reg_area_end_pointer";
10180
10181 // void *OverflowArea;
10182 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10183 FieldNames[2] = "__overflow_area_pointer";
10184
10185 // Create fields
10186 for (unsigned i = 0; i < NumFields; ++i) {
10188 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10189 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10190 /*TInfo=*/nullptr,
10191 /*BitWidth=*/nullptr,
10192 /*Mutable=*/false, ICIS_NoInit);
10193 Field->setAccess(AS_public);
10194 VaListTagDecl->addDecl(Field);
10195 }
10196 VaListTagDecl->completeDefinition();
10197 Context->VaListTagDecl = VaListTagDecl;
10198 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10199
10200 // } __va_list_tag;
10201 TypedefDecl *VaListTagTypedefDecl =
10202 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10203
10204 QualType VaListTagTypedefType =
10205 Context->getTypedefType(ElaboratedTypeKeyword::None,
10206 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10207
10208 // typedef __va_list_tag __builtin_va_list[1];
10209 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10210 QualType VaListTagArrayType = Context->getConstantArrayType(
10211 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10212
10213 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10214}
10215
10216static TypedefDecl *
10218 // typedef struct __va_list_tag {
10219 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10220
10221 VaListTagDecl->startDefinition();
10222
10223 // int* __va_stk;
10224 // int* __va_reg;
10225 // int __va_ndx;
10226 constexpr size_t NumFields = 3;
10227 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10228 Context->getPointerType(Context->IntTy),
10229 Context->IntTy};
10230 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10231
10232 // Create fields
10233 for (unsigned i = 0; i < NumFields; ++i) {
10236 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10237 /*BitWidth=*/nullptr,
10238 /*Mutable=*/false, ICIS_NoInit);
10239 Field->setAccess(AS_public);
10240 VaListTagDecl->addDecl(Field);
10241 }
10242 VaListTagDecl->completeDefinition();
10243 Context->VaListTagDecl = VaListTagDecl;
10244 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10245
10246 // } __va_list_tag;
10247 TypedefDecl *VaListTagTypedefDecl =
10248 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10249
10250 return VaListTagTypedefDecl;
10251}
10252
10255 switch (Kind) {
10257 return CreateCharPtrBuiltinVaListDecl(Context);
10259 return CreateVoidPtrBuiltinVaListDecl(Context);
10261 return CreateAArch64ABIBuiltinVaListDecl(Context);
10263 return CreatePowerABIBuiltinVaListDecl(Context);
10265 return CreateX86_64ABIBuiltinVaListDecl(Context);
10267 return CreateAAPCSABIBuiltinVaListDecl(Context);
10269 return CreateSystemZBuiltinVaListDecl(Context);
10271 return CreateHexagonBuiltinVaListDecl(Context);
10273 return CreateXtensaABIBuiltinVaListDecl(Context);
10274 }
10275
10276 llvm_unreachable("Unhandled __builtin_va_list type kind");
10277}
10278
10280 if (!BuiltinVaListDecl) {
10281 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10282 assert(BuiltinVaListDecl->isImplicit());
10283 }
10284
10285 return BuiltinVaListDecl;
10286}
10287
10289 // Force the creation of VaListTagDecl by building the __builtin_va_list
10290 // declaration.
10291 if (!VaListTagDecl)
10292 (void)getBuiltinVaListDecl();
10293
10294 return VaListTagDecl;
10295}
10296
10298 if (!BuiltinMSVaListDecl)
10299 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10300
10301 return BuiltinMSVaListDecl;
10302}
10303
10305 // Allow redecl custom type checking builtin for HLSL.
10306 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10307 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10308 return true;
10309 // Allow redecl custom type checking builtin for SPIR-V.
10310 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10311 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10312 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10313 return true;
10314 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10315}
10316
10318 assert(ObjCConstantStringType.isNull() &&
10319 "'NSConstantString' type already set!");
10320
10321 ObjCConstantStringType = getObjCInterfaceType(Decl);
10322}
10323
10324/// Retrieve the template name that corresponds to a non-empty
10325/// lookup.
10328 UnresolvedSetIterator End) const {
10329 unsigned size = End - Begin;
10330 assert(size > 1 && "set is not overloaded!");
10331
10332 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10333 size * sizeof(FunctionTemplateDecl*));
10334 auto *OT = new (memory) OverloadedTemplateStorage(size);
10335
10336 NamedDecl **Storage = OT->getStorage();
10337 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10338 NamedDecl *D = *I;
10339 assert(isa<FunctionTemplateDecl>(D) ||
10343 *Storage++ = D;
10344 }
10345
10346 return TemplateName(OT);
10347}
10348
10349/// Retrieve a template name representing an unqualified-id that has been
10350/// assumed to name a template for ADL purposes.
10352 auto *OT = new (*this) AssumedTemplateStorage(Name);
10353 return TemplateName(OT);
10354}
10355
10356/// Retrieve the template name that represents a qualified
10357/// template name such as \c std::vector.
10359 bool TemplateKeyword,
10360 TemplateName Template) const {
10361 assert(Template.getKind() == TemplateName::Template ||
10363
10364 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10365 assert(!Qualifier && "unexpected qualified template template parameter");
10366 assert(TemplateKeyword == false);
10367 return Template;
10368 }
10369
10370 // FIXME: Canonicalization?
10371 llvm::FoldingSetNodeID ID;
10372 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10373
10374 void *InsertPos = nullptr;
10376 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10377 if (!QTN) {
10378 QTN = new (*this, alignof(QualifiedTemplateName))
10379 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10380 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10381 }
10382
10383 return TemplateName(QTN);
10384}
10385
10386/// Retrieve the template name that represents a dependent
10387/// template name such as \c MetaFun::template operator+.
10390 llvm::FoldingSetNodeID ID;
10391 S.Profile(ID);
10392
10393 void *InsertPos = nullptr;
10394 if (DependentTemplateName *QTN =
10395 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10396 return TemplateName(QTN);
10397
10399 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10400 DependentTemplateNames.InsertNode(QTN, InsertPos);
10401 return TemplateName(QTN);
10402}
10403
10405 Decl *AssociatedDecl,
10406 unsigned Index,
10407 UnsignedOrNone PackIndex,
10408 bool Final) const {
10409 llvm::FoldingSetNodeID ID;
10410 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10411 Index, PackIndex, Final);
10412
10413 void *insertPos = nullptr;
10415 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10416
10417 if (!subst) {
10418 subst = new (*this) SubstTemplateTemplateParmStorage(
10419 Replacement, AssociatedDecl, Index, PackIndex, Final);
10420 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10421 }
10422
10423 return TemplateName(subst);
10424}
10425
10428 Decl *AssociatedDecl,
10429 unsigned Index, bool Final) const {
10430 auto &Self = const_cast<ASTContext &>(*this);
10431 llvm::FoldingSetNodeID ID;
10433 AssociatedDecl, Index, Final);
10434
10435 void *InsertPos = nullptr;
10437 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10438
10439 if (!Subst) {
10440 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10441 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10442 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10443 }
10444
10445 return TemplateName(Subst);
10446}
10447
10448/// Retrieve the template name that represents a template name
10449/// deduced from a specialization.
10452 DefaultArguments DefaultArgs) const {
10453 if (!DefaultArgs)
10454 return Underlying;
10455
10456 llvm::FoldingSetNodeID ID;
10457 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10458
10459 void *InsertPos = nullptr;
10461 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10462 if (!DTS) {
10463 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10464 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10465 alignof(DeducedTemplateStorage));
10466 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10467 DeducedTemplates.InsertNode(DTS, InsertPos);
10468 }
10469 return TemplateName(DTS);
10470}
10471
10472/// getFromTargetType - Given one of the integer types provided by
10473/// TargetInfo, produce the corresponding type. The unsigned @p Type
10474/// is actually a value of type @c TargetInfo::IntType.
10475CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10476 switch (Type) {
10477 case TargetInfo::NoInt: return {};
10480 case TargetInfo::SignedShort: return ShortTy;
10482 case TargetInfo::SignedInt: return IntTy;
10484 case TargetInfo::SignedLong: return LongTy;
10488 }
10489
10490 llvm_unreachable("Unhandled TargetInfo::IntType value");
10491}
10492
10493//===----------------------------------------------------------------------===//
10494// Type Predicates.
10495//===----------------------------------------------------------------------===//
10496
10497/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10498/// garbage collection attribute.
10499///
10501 if (getLangOpts().getGC() == LangOptions::NonGC)
10502 return Qualifiers::GCNone;
10503
10504 assert(getLangOpts().ObjC);
10505 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10506
10507 // Default behaviour under objective-C's gc is for ObjC pointers
10508 // (or pointers to them) be treated as though they were declared
10509 // as __strong.
10510 if (GCAttrs == Qualifiers::GCNone) {
10512 return Qualifiers::Strong;
10513 else if (Ty->isPointerType())
10515 } else {
10516 // It's not valid to set GC attributes on anything that isn't a
10517 // pointer.
10518#ifndef NDEBUG
10520 while (const auto *AT = dyn_cast<ArrayType>(CT))
10521 CT = AT->getElementType();
10522 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10523#endif
10524 }
10525 return GCAttrs;
10526}
10527
10528//===----------------------------------------------------------------------===//
10529// Type Compatibility Testing
10530//===----------------------------------------------------------------------===//
10531
10532/// areCompatVectorTypes - Return true if the two specified vector types are
10533/// compatible.
10534static bool areCompatVectorTypes(const VectorType *LHS,
10535 const VectorType *RHS) {
10536 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10537 return LHS->getElementType() == RHS->getElementType() &&
10538 LHS->getNumElements() == RHS->getNumElements();
10539}
10540
10541/// areCompatMatrixTypes - Return true if the two specified matrix types are
10542/// compatible.
10544 const ConstantMatrixType *RHS) {
10545 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10546 return LHS->getElementType() == RHS->getElementType() &&
10547 LHS->getNumRows() == RHS->getNumRows() &&
10548 LHS->getNumColumns() == RHS->getNumColumns();
10549}
10550
10552 QualType SecondVec) {
10553 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10554 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10555
10556 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10557 return true;
10558
10559 // Treat Neon vector types and most AltiVec vector types as if they are the
10560 // equivalent GCC vector types.
10561 const auto *First = FirstVec->castAs<VectorType>();
10562 const auto *Second = SecondVec->castAs<VectorType>();
10563 if (First->getNumElements() == Second->getNumElements() &&
10564 hasSameType(First->getElementType(), Second->getElementType()) &&
10565 First->getVectorKind() != VectorKind::AltiVecPixel &&
10566 First->getVectorKind() != VectorKind::AltiVecBool &&
10569 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10570 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10573 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10575 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10577 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10579 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10581 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10583 return true;
10584
10585 return false;
10586}
10587
10588/// getRVVTypeSize - Return RVV vector register size.
10589static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10590 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10591 auto VScale = Context.getTargetInfo().getVScaleRange(
10592 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10593 if (!VScale)
10594 return 0;
10595
10596 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10597
10598 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10599 if (Info.ElementType == Context.BoolTy)
10600 EltSize = 1;
10601
10602 uint64_t MinElts = Info.EC.getKnownMinValue();
10603 return VScale->first * MinElts * EltSize;
10604}
10605
10607 QualType SecondType) {
10608 assert(
10609 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10610 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10611 "Expected RVV builtin type and vector type!");
10612
10613 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10614 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10615 if (const auto *VT = SecondType->getAs<VectorType>()) {
10616 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10618 return FirstType->isRVVVLSBuiltinType() &&
10619 Info.ElementType == BoolTy &&
10620 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10621 }
10622 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10624 return FirstType->isRVVVLSBuiltinType() &&
10625 Info.ElementType == BoolTy &&
10626 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10627 }
10628 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10630 return FirstType->isRVVVLSBuiltinType() &&
10631 Info.ElementType == BoolTy &&
10632 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10633 }
10634 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10636 return FirstType->isRVVVLSBuiltinType() &&
10637 Info.ElementType == BoolTy &&
10638 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10639 }
10640 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10641 VT->getVectorKind() == VectorKind::Generic)
10642 return FirstType->isRVVVLSBuiltinType() &&
10643 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10644 hasSameType(VT->getElementType(),
10645 getBuiltinVectorTypeInfo(BT).ElementType);
10646 }
10647 }
10648 return false;
10649 };
10650
10651 return IsValidCast(FirstType, SecondType) ||
10652 IsValidCast(SecondType, FirstType);
10653}
10654
10656 QualType SecondType) {
10657 assert(
10658 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10659 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10660 "Expected RVV builtin type and vector type!");
10661
10662 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10663 const auto *BT = FirstType->getAs<BuiltinType>();
10664 if (!BT)
10665 return false;
10666
10667 if (!BT->isRVVVLSBuiltinType())
10668 return false;
10669
10670 const auto *VecTy = SecondType->getAs<VectorType>();
10671 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10673 getLangOpts().getLaxVectorConversions();
10674
10675 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10676 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10677 return false;
10678
10679 // If -flax-vector-conversions=all is specified, the types are
10680 // certainly compatible.
10682 return true;
10683
10684 // If -flax-vector-conversions=integer is specified, the types are
10685 // compatible if the elements are integer types.
10687 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10688 FirstType->getRVVEltType(*this)->isIntegerType();
10689 }
10690
10691 return false;
10692 };
10693
10694 return IsLaxCompatible(FirstType, SecondType) ||
10695 IsLaxCompatible(SecondType, FirstType);
10696}
10697
10699 while (true) {
10700 // __strong id
10701 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10702 if (Attr->getAttrKind() == attr::ObjCOwnership)
10703 return true;
10704
10705 Ty = Attr->getModifiedType();
10706
10707 // X *__strong (...)
10708 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10709 Ty = Paren->getInnerType();
10710
10711 // We do not want to look through typedefs, typeof(expr),
10712 // typeof(type), or any other way that the type is somehow
10713 // abstracted.
10714 } else {
10715 return false;
10716 }
10717 }
10718}
10719
10720//===----------------------------------------------------------------------===//
10721// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10722//===----------------------------------------------------------------------===//
10723
10724/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10725/// inheritance hierarchy of 'rProto'.
10726bool
10728 ObjCProtocolDecl *rProto) const {
10729 if (declaresSameEntity(lProto, rProto))
10730 return true;
10731 for (auto *PI : rProto->protocols())
10732 if (ProtocolCompatibleWithProtocol(lProto, PI))
10733 return true;
10734 return false;
10735}
10736
10737/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10738/// Class<pr1, ...>.
10740 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10741 for (auto *lhsProto : lhs->quals()) {
10742 bool match = false;
10743 for (auto *rhsProto : rhs->quals()) {
10744 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10745 match = true;
10746 break;
10747 }
10748 }
10749 if (!match)
10750 return false;
10751 }
10752 return true;
10753}
10754
10755/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10756/// ObjCQualifiedIDType.
10758 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10759 bool compare) {
10760 // Allow id<P..> and an 'id' in all cases.
10761 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10762 return true;
10763
10764 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10765 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10767 return false;
10768
10769 if (lhs->isObjCQualifiedIdType()) {
10770 if (rhs->qual_empty()) {
10771 // If the RHS is a unqualified interface pointer "NSString*",
10772 // make sure we check the class hierarchy.
10773 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10774 for (auto *I : lhs->quals()) {
10775 // when comparing an id<P> on lhs with a static type on rhs,
10776 // see if static class implements all of id's protocols, directly or
10777 // through its super class and categories.
10778 if (!rhsID->ClassImplementsProtocol(I, true))
10779 return false;
10780 }
10781 }
10782 // If there are no qualifiers and no interface, we have an 'id'.
10783 return true;
10784 }
10785 // Both the right and left sides have qualifiers.
10786 for (auto *lhsProto : lhs->quals()) {
10787 bool match = false;
10788
10789 // when comparing an id<P> on lhs with a static type on rhs,
10790 // see if static class implements all of id's protocols, directly or
10791 // through its super class and categories.
10792 for (auto *rhsProto : rhs->quals()) {
10793 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10794 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10795 match = true;
10796 break;
10797 }
10798 }
10799 // If the RHS is a qualified interface pointer "NSString<P>*",
10800 // make sure we check the class hierarchy.
10801 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10802 for (auto *I : lhs->quals()) {
10803 // when comparing an id<P> on lhs with a static type on rhs,
10804 // see if static class implements all of id's protocols, directly or
10805 // through its super class and categories.
10806 if (rhsID->ClassImplementsProtocol(I, true)) {
10807 match = true;
10808 break;
10809 }
10810 }
10811 }
10812 if (!match)
10813 return false;
10814 }
10815
10816 return true;
10817 }
10818
10819 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10820
10821 if (lhs->getInterfaceType()) {
10822 // If both the right and left sides have qualifiers.
10823 for (auto *lhsProto : lhs->quals()) {
10824 bool match = false;
10825
10826 // when comparing an id<P> on rhs with a static type on lhs,
10827 // see if static class implements all of id's protocols, directly or
10828 // through its super class and categories.
10829 // First, lhs protocols in the qualifier list must be found, direct
10830 // or indirect in rhs's qualifier list or it is a mismatch.
10831 for (auto *rhsProto : rhs->quals()) {
10832 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10833 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10834 match = true;
10835 break;
10836 }
10837 }
10838 if (!match)
10839 return false;
10840 }
10841
10842 // Static class's protocols, or its super class or category protocols
10843 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10844 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10845 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10846 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10847 // This is rather dubious but matches gcc's behavior. If lhs has
10848 // no type qualifier and its class has no static protocol(s)
10849 // assume that it is mismatch.
10850 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10851 return false;
10852 for (auto *lhsProto : LHSInheritedProtocols) {
10853 bool match = false;
10854 for (auto *rhsProto : rhs->quals()) {
10855 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10856 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10857 match = true;
10858 break;
10859 }
10860 }
10861 if (!match)
10862 return false;
10863 }
10864 }
10865 return true;
10866 }
10867 return false;
10868}
10869
10870/// canAssignObjCInterfaces - Return true if the two interface types are
10871/// compatible for assignment from RHS to LHS. This handles validation of any
10872/// protocol qualifiers on the LHS or RHS.
10874 const ObjCObjectPointerType *RHSOPT) {
10875 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10876 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10877
10878 // If either type represents the built-in 'id' type, return true.
10879 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10880 return true;
10881
10882 // Function object that propagates a successful result or handles
10883 // __kindof types.
10884 auto finish = [&](bool succeeded) -> bool {
10885 if (succeeded)
10886 return true;
10887
10888 if (!RHS->isKindOfType())
10889 return false;
10890
10891 // Strip off __kindof and protocol qualifiers, then check whether
10892 // we can assign the other way.
10894 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10895 };
10896
10897 // Casts from or to id<P> are allowed when the other side has compatible
10898 // protocols.
10899 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10900 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10901 }
10902
10903 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10904 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10905 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10906 }
10907
10908 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10909 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10910 return true;
10911 }
10912
10913 // If we have 2 user-defined types, fall into that path.
10914 if (LHS->getInterface() && RHS->getInterface()) {
10915 return finish(canAssignObjCInterfaces(LHS, RHS));
10916 }
10917
10918 return false;
10919}
10920
10921/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10922/// for providing type-safety for objective-c pointers used to pass/return
10923/// arguments in block literals. When passed as arguments, passing 'A*' where
10924/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10925/// not OK. For the return type, the opposite is not OK.
10927 const ObjCObjectPointerType *LHSOPT,
10928 const ObjCObjectPointerType *RHSOPT,
10929 bool BlockReturnType) {
10930
10931 // Function object that propagates a successful result or handles
10932 // __kindof types.
10933 auto finish = [&](bool succeeded) -> bool {
10934 if (succeeded)
10935 return true;
10936
10937 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10938 if (!Expected->isKindOfType())
10939 return false;
10940
10941 // Strip off __kindof and protocol qualifiers, then check whether
10942 // we can assign the other way.
10944 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10945 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10946 BlockReturnType);
10947 };
10948
10949 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10950 return true;
10951
10952 if (LHSOPT->isObjCBuiltinType()) {
10953 return finish(RHSOPT->isObjCBuiltinType() ||
10954 RHSOPT->isObjCQualifiedIdType());
10955 }
10956
10957 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10958 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10959 // Use for block parameters previous type checking for compatibility.
10960 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10961 // Or corrected type checking as in non-compat mode.
10962 (!BlockReturnType &&
10963 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10964 else
10966 (BlockReturnType ? LHSOPT : RHSOPT),
10967 (BlockReturnType ? RHSOPT : LHSOPT), false));
10968 }
10969
10970 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10971 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10972 if (LHS && RHS) { // We have 2 user-defined types.
10973 if (LHS != RHS) {
10974 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10975 return finish(BlockReturnType);
10976 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10977 return finish(!BlockReturnType);
10978 }
10979 else
10980 return true;
10981 }
10982 return false;
10983}
10984
10985/// Comparison routine for Objective-C protocols to be used with
10986/// llvm::array_pod_sort.
10988 ObjCProtocolDecl * const *rhs) {
10989 return (*lhs)->getName().compare((*rhs)->getName());
10990}
10991
10992/// getIntersectionOfProtocols - This routine finds the intersection of set
10993/// of protocols inherited from two distinct objective-c pointer objects with
10994/// the given common base.
10995/// It is used to build composite qualifier list of the composite type of
10996/// the conditional expression involving two objective-c pointer objects.
10997static
10999 const ObjCInterfaceDecl *CommonBase,
11000 const ObjCObjectPointerType *LHSOPT,
11001 const ObjCObjectPointerType *RHSOPT,
11002 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11003
11004 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11005 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11006 assert(LHS->getInterface() && "LHS must have an interface base");
11007 assert(RHS->getInterface() && "RHS must have an interface base");
11008
11009 // Add all of the protocols for the LHS.
11011
11012 // Start with the protocol qualifiers.
11013 for (auto *proto : LHS->quals()) {
11014 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11015 }
11016
11017 // Also add the protocols associated with the LHS interface.
11018 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11019
11020 // Add all of the protocols for the RHS.
11022
11023 // Start with the protocol qualifiers.
11024 for (auto *proto : RHS->quals()) {
11025 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11026 }
11027
11028 // Also add the protocols associated with the RHS interface.
11029 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11030
11031 // Compute the intersection of the collected protocol sets.
11032 for (auto *proto : LHSProtocolSet) {
11033 if (RHSProtocolSet.count(proto))
11034 IntersectionSet.push_back(proto);
11035 }
11036
11037 // Compute the set of protocols that is implied by either the common type or
11038 // the protocols within the intersection.
11040 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11041
11042 // Remove any implied protocols from the list of inherited protocols.
11043 if (!ImpliedProtocols.empty()) {
11044 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11045 return ImpliedProtocols.contains(proto);
11046 });
11047 }
11048
11049 // Sort the remaining protocols by name.
11050 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11052}
11053
11054/// Determine whether the first type is a subtype of the second.
11056 QualType rhs) {
11057 // Common case: two object pointers.
11058 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11059 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11060 if (lhsOPT && rhsOPT)
11061 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11062
11063 // Two block pointers.
11064 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11065 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11066 if (lhsBlock && rhsBlock)
11067 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11068
11069 // If either is an unqualified 'id' and the other is a block, it's
11070 // acceptable.
11071 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11072 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11073 return true;
11074
11075 return false;
11076}
11077
11078// Check that the given Objective-C type argument lists are equivalent.
11080 const ObjCInterfaceDecl *iface,
11081 ArrayRef<QualType> lhsArgs,
11082 ArrayRef<QualType> rhsArgs,
11083 bool stripKindOf) {
11084 if (lhsArgs.size() != rhsArgs.size())
11085 return false;
11086
11087 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11088 if (!typeParams)
11089 return false;
11090
11091 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11092 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11093 continue;
11094
11095 switch (typeParams->begin()[i]->getVariance()) {
11097 if (!stripKindOf ||
11098 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11099 rhsArgs[i].stripObjCKindOfType(ctx))) {
11100 return false;
11101 }
11102 break;
11103
11105 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11106 return false;
11107 break;
11108
11110 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11111 return false;
11112 break;
11113 }
11114 }
11115
11116 return true;
11117}
11118
11120 const ObjCObjectPointerType *Lptr,
11121 const ObjCObjectPointerType *Rptr) {
11122 const ObjCObjectType *LHS = Lptr->getObjectType();
11123 const ObjCObjectType *RHS = Rptr->getObjectType();
11124 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11125 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11126
11127 if (!LDecl || !RDecl)
11128 return {};
11129
11130 // When either LHS or RHS is a kindof type, we should return a kindof type.
11131 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11132 // kindof(A).
11133 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11134
11135 // Follow the left-hand side up the class hierarchy until we either hit a
11136 // root or find the RHS. Record the ancestors in case we don't find it.
11137 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11138 LHSAncestors;
11139 while (true) {
11140 // Record this ancestor. We'll need this if the common type isn't in the
11141 // path from the LHS to the root.
11142 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11143
11144 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11145 // Get the type arguments.
11146 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11147 bool anyChanges = false;
11148 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11149 // Both have type arguments, compare them.
11150 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11151 LHS->getTypeArgs(), RHS->getTypeArgs(),
11152 /*stripKindOf=*/true))
11153 return {};
11154 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11155 // If only one has type arguments, the result will not have type
11156 // arguments.
11157 LHSTypeArgs = {};
11158 anyChanges = true;
11159 }
11160
11161 // Compute the intersection of protocols.
11163 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11164 Protocols);
11165 if (!Protocols.empty())
11166 anyChanges = true;
11167
11168 // If anything in the LHS will have changed, build a new result type.
11169 // If we need to return a kindof type but LHS is not a kindof type, we
11170 // build a new result type.
11171 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11172 QualType Result = getObjCInterfaceType(LHS->getInterface());
11173 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11174 anyKindOf || LHS->isKindOfType());
11176 }
11177
11178 return getObjCObjectPointerType(QualType(LHS, 0));
11179 }
11180
11181 // Find the superclass.
11182 QualType LHSSuperType = LHS->getSuperClassType();
11183 if (LHSSuperType.isNull())
11184 break;
11185
11186 LHS = LHSSuperType->castAs<ObjCObjectType>();
11187 }
11188
11189 // We didn't find anything by following the LHS to its root; now check
11190 // the RHS against the cached set of ancestors.
11191 while (true) {
11192 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11193 if (KnownLHS != LHSAncestors.end()) {
11194 LHS = KnownLHS->second;
11195
11196 // Get the type arguments.
11197 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11198 bool anyChanges = false;
11199 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11200 // Both have type arguments, compare them.
11201 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11202 LHS->getTypeArgs(), RHS->getTypeArgs(),
11203 /*stripKindOf=*/true))
11204 return {};
11205 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11206 // If only one has type arguments, the result will not have type
11207 // arguments.
11208 RHSTypeArgs = {};
11209 anyChanges = true;
11210 }
11211
11212 // Compute the intersection of protocols.
11214 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11215 Protocols);
11216 if (!Protocols.empty())
11217 anyChanges = true;
11218
11219 // If we need to return a kindof type but RHS is not a kindof type, we
11220 // build a new result type.
11221 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11222 QualType Result = getObjCInterfaceType(RHS->getInterface());
11223 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11224 anyKindOf || RHS->isKindOfType());
11226 }
11227
11228 return getObjCObjectPointerType(QualType(RHS, 0));
11229 }
11230
11231 // Find the superclass of the RHS.
11232 QualType RHSSuperType = RHS->getSuperClassType();
11233 if (RHSSuperType.isNull())
11234 break;
11235
11236 RHS = RHSSuperType->castAs<ObjCObjectType>();
11237 }
11238
11239 return {};
11240}
11241
11243 const ObjCObjectType *RHS) {
11244 assert(LHS->getInterface() && "LHS is not an interface type");
11245 assert(RHS->getInterface() && "RHS is not an interface type");
11246
11247 // Verify that the base decls are compatible: the RHS must be a subclass of
11248 // the LHS.
11249 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11250 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11251 if (!IsSuperClass)
11252 return false;
11253
11254 // If the LHS has protocol qualifiers, determine whether all of them are
11255 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11256 // LHS).
11257 if (LHS->getNumProtocols() > 0) {
11258 // OK if conversion of LHS to SuperClass results in narrowing of types
11259 // ; i.e., SuperClass may implement at least one of the protocols
11260 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11261 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11262 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11263 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11264 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11265 // qualifiers.
11266 for (auto *RHSPI : RHS->quals())
11267 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11268 // If there is no protocols associated with RHS, it is not a match.
11269 if (SuperClassInheritedProtocols.empty())
11270 return false;
11271
11272 for (const auto *LHSProto : LHS->quals()) {
11273 bool SuperImplementsProtocol = false;
11274 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11275 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11276 SuperImplementsProtocol = true;
11277 break;
11278 }
11279 if (!SuperImplementsProtocol)
11280 return false;
11281 }
11282 }
11283
11284 // If the LHS is specialized, we may need to check type arguments.
11285 if (LHS->isSpecialized()) {
11286 // Follow the superclass chain until we've matched the LHS class in the
11287 // hierarchy. This substitutes type arguments through.
11288 const ObjCObjectType *RHSSuper = RHS;
11289 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11290 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11291
11292 // If the RHS is specializd, compare type arguments.
11293 if (RHSSuper->isSpecialized() &&
11294 !sameObjCTypeArgs(*this, LHS->getInterface(),
11295 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11296 /*stripKindOf=*/true)) {
11297 return false;
11298 }
11299 }
11300
11301 return true;
11302}
11303
11305 // get the "pointed to" types
11306 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11307 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11308
11309 if (!LHSOPT || !RHSOPT)
11310 return false;
11311
11312 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11313 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11314}
11315
11318 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11319 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11320}
11321
11322/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11323/// both shall have the identically qualified version of a compatible type.
11324/// C99 6.2.7p1: Two types have compatible types if their types are the
11325/// same. See 6.7.[2,3,5] for additional rules.
11327 bool CompareUnqualified) {
11328 if (getLangOpts().CPlusPlus)
11329 return hasSameType(LHS, RHS);
11330
11331 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11332}
11333
11335 return typesAreCompatible(LHS, RHS);
11336}
11337
11339 return !mergeTypes(LHS, RHS, true).isNull();
11340}
11341
11342/// mergeTransparentUnionType - if T is a transparent union type and a member
11343/// of T is compatible with SubType, return the merged type, else return
11344/// QualType()
11346 bool OfBlockPointer,
11347 bool Unqualified) {
11348 if (const RecordType *UT = T->getAsUnionType()) {
11349 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11350 if (UD->hasAttr<TransparentUnionAttr>()) {
11351 for (const auto *I : UD->fields()) {
11352 QualType ET = I->getType().getUnqualifiedType();
11353 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11354 if (!MT.isNull())
11355 return MT;
11356 }
11357 }
11358 }
11359
11360 return {};
11361}
11362
11363/// mergeFunctionParameterTypes - merge two types which appear as function
11364/// parameter types
11366 bool OfBlockPointer,
11367 bool Unqualified) {
11368 // GNU extension: two types are compatible if they appear as a function
11369 // argument, one of the types is a transparent union type and the other
11370 // type is compatible with a union member
11371 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11372 Unqualified);
11373 if (!lmerge.isNull())
11374 return lmerge;
11375
11376 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11377 Unqualified);
11378 if (!rmerge.isNull())
11379 return rmerge;
11380
11381 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11382}
11383
11385 bool OfBlockPointer, bool Unqualified,
11386 bool AllowCXX,
11387 bool IsConditionalOperator) {
11388 const auto *lbase = lhs->castAs<FunctionType>();
11389 const auto *rbase = rhs->castAs<FunctionType>();
11390 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11391 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11392 bool allLTypes = true;
11393 bool allRTypes = true;
11394
11395 // Check return type
11396 QualType retType;
11397 if (OfBlockPointer) {
11398 QualType RHS = rbase->getReturnType();
11399 QualType LHS = lbase->getReturnType();
11400 bool UnqualifiedResult = Unqualified;
11401 if (!UnqualifiedResult)
11402 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11403 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11404 }
11405 else
11406 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11407 Unqualified);
11408 if (retType.isNull())
11409 return {};
11410
11411 if (Unqualified)
11412 retType = retType.getUnqualifiedType();
11413
11414 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11415 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11416 if (Unqualified) {
11417 LRetType = LRetType.getUnqualifiedType();
11418 RRetType = RRetType.getUnqualifiedType();
11419 }
11420
11421 if (getCanonicalType(retType) != LRetType)
11422 allLTypes = false;
11423 if (getCanonicalType(retType) != RRetType)
11424 allRTypes = false;
11425
11426 // FIXME: double check this
11427 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11428 // rbase->getRegParmAttr() != 0 &&
11429 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11430 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11431 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11432
11433 // Compatible functions must have compatible calling conventions
11434 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11435 return {};
11436
11437 // Regparm is part of the calling convention.
11438 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11439 return {};
11440 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11441 return {};
11442
11443 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11444 return {};
11445 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11446 return {};
11447 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11448 return {};
11449
11450 // When merging declarations, it's common for supplemental information like
11451 // attributes to only be present in one of the declarations, and we generally
11452 // want type merging to preserve the union of information. So a merged
11453 // function type should be noreturn if it was noreturn in *either* operand
11454 // type.
11455 //
11456 // But for the conditional operator, this is backwards. The result of the
11457 // operator could be either operand, and its type should conservatively
11458 // reflect that. So a function type in a composite type is noreturn only
11459 // if it's noreturn in *both* operand types.
11460 //
11461 // Arguably, noreturn is a kind of subtype, and the conditional operator
11462 // ought to produce the most specific common supertype of its operand types.
11463 // That would differ from this rule in contravariant positions. However,
11464 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11465 // as a practical matter, it would only affect C code that does abstraction of
11466 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11467 // say the least. So we use the simpler rule.
11468 bool NoReturn = IsConditionalOperator
11469 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11470 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11471 if (lbaseInfo.getNoReturn() != NoReturn)
11472 allLTypes = false;
11473 if (rbaseInfo.getNoReturn() != NoReturn)
11474 allRTypes = false;
11475
11476 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11477
11478 std::optional<FunctionEffectSet> MergedFX;
11479
11480 if (lproto && rproto) { // two C99 style function prototypes
11481 assert((AllowCXX ||
11482 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11483 "C++ shouldn't be here");
11484 // Compatible functions must have the same number of parameters
11485 if (lproto->getNumParams() != rproto->getNumParams())
11486 return {};
11487
11488 // Variadic and non-variadic functions aren't compatible
11489 if (lproto->isVariadic() != rproto->isVariadic())
11490 return {};
11491
11492 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11493 return {};
11494
11495 // Function protos with different 'cfi_salt' values aren't compatible.
11496 if (lproto->getExtraAttributeInfo().CFISalt !=
11497 rproto->getExtraAttributeInfo().CFISalt)
11498 return {};
11499
11500 // Function effects are handled similarly to noreturn, see above.
11501 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11502 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11503 if (LHSFX != RHSFX) {
11504 if (IsConditionalOperator)
11505 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11506 else {
11508 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11509 // Here we're discarding a possible error due to conflicts in the effect
11510 // sets. But we're not in a context where we can report it. The
11511 // operation does however guarantee maintenance of invariants.
11512 }
11513 if (*MergedFX != LHSFX)
11514 allLTypes = false;
11515 if (*MergedFX != RHSFX)
11516 allRTypes = false;
11517 }
11518
11520 bool canUseLeft, canUseRight;
11521 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11522 newParamInfos))
11523 return {};
11524
11525 if (!canUseLeft)
11526 allLTypes = false;
11527 if (!canUseRight)
11528 allRTypes = false;
11529
11530 // Check parameter type compatibility
11532 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11533 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11534 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11536 lParamType, rParamType, OfBlockPointer, Unqualified);
11537 if (paramType.isNull())
11538 return {};
11539
11540 if (Unqualified)
11541 paramType = paramType.getUnqualifiedType();
11542
11543 types.push_back(paramType);
11544 if (Unqualified) {
11545 lParamType = lParamType.getUnqualifiedType();
11546 rParamType = rParamType.getUnqualifiedType();
11547 }
11548
11549 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11550 allLTypes = false;
11551 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11552 allRTypes = false;
11553 }
11554
11555 if (allLTypes) return lhs;
11556 if (allRTypes) return rhs;
11557
11558 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11559 EPI.ExtInfo = einfo;
11560 EPI.ExtParameterInfos =
11561 newParamInfos.empty() ? nullptr : newParamInfos.data();
11562 if (MergedFX)
11563 EPI.FunctionEffects = *MergedFX;
11564 return getFunctionType(retType, types, EPI);
11565 }
11566
11567 if (lproto) allRTypes = false;
11568 if (rproto) allLTypes = false;
11569
11570 const FunctionProtoType *proto = lproto ? lproto : rproto;
11571 if (proto) {
11572 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11573 if (proto->isVariadic())
11574 return {};
11575 // Check that the types are compatible with the types that
11576 // would result from default argument promotions (C99 6.7.5.3p15).
11577 // The only types actually affected are promotable integer
11578 // types and floats, which would be passed as a different
11579 // type depending on whether the prototype is visible.
11580 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11581 QualType paramTy = proto->getParamType(i);
11582
11583 // Look at the converted type of enum types, since that is the type used
11584 // to pass enum values.
11585 if (const auto *ED = paramTy->getAsEnumDecl()) {
11586 paramTy = ED->getIntegerType();
11587 if (paramTy.isNull())
11588 return {};
11589 }
11590
11591 if (isPromotableIntegerType(paramTy) ||
11592 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11593 return {};
11594 }
11595
11596 if (allLTypes) return lhs;
11597 if (allRTypes) return rhs;
11598
11600 EPI.ExtInfo = einfo;
11601 if (MergedFX)
11602 EPI.FunctionEffects = *MergedFX;
11603 return getFunctionType(retType, proto->getParamTypes(), EPI);
11604 }
11605
11606 if (allLTypes) return lhs;
11607 if (allRTypes) return rhs;
11608 return getFunctionNoProtoType(retType, einfo);
11609}
11610
11611/// Given that we have an enum type and a non-enum type, try to merge them.
11612static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11613 QualType other, bool isBlockReturnType) {
11614 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11615 // a signed integer type, or an unsigned integer type.
11616 // Compatibility is based on the underlying type, not the promotion
11617 // type.
11618 QualType underlyingType =
11619 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11620 if (underlyingType.isNull())
11621 return {};
11622 if (Context.hasSameType(underlyingType, other))
11623 return other;
11624
11625 // In block return types, we're more permissive and accept any
11626 // integral type of the same size.
11627 if (isBlockReturnType && other->isIntegerType() &&
11628 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11629 return other;
11630
11631 return {};
11632}
11633
11635 // C17 and earlier and C++ disallow two tag definitions within the same TU
11636 // from being compatible.
11637 if (LangOpts.CPlusPlus || !LangOpts.C23)
11638 return {};
11639
11640 // C23, on the other hand, requires the members to be "the same enough", so
11641 // we use a structural equivalence check.
11644 getLangOpts(), *this, *this, NonEquivalentDecls,
11645 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11646 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11647 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11648}
11649
11650QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11651 bool Unqualified, bool BlockReturnType,
11652 bool IsConditionalOperator) {
11653 // For C++ we will not reach this code with reference types (see below),
11654 // for OpenMP variant call overloading we might.
11655 //
11656 // C++ [expr]: If an expression initially has the type "reference to T", the
11657 // type is adjusted to "T" prior to any further analysis, the expression
11658 // designates the object or function denoted by the reference, and the
11659 // expression is an lvalue unless the reference is an rvalue reference and
11660 // the expression is a function call (possibly inside parentheses).
11661 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11662 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11663 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11664 LHS->getTypeClass() == RHS->getTypeClass())
11665 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11666 OfBlockPointer, Unqualified, BlockReturnType);
11667 if (LHSRefTy || RHSRefTy)
11668 return {};
11669
11670 if (Unqualified) {
11671 LHS = LHS.getUnqualifiedType();
11672 RHS = RHS.getUnqualifiedType();
11673 }
11674
11675 QualType LHSCan = getCanonicalType(LHS),
11676 RHSCan = getCanonicalType(RHS);
11677
11678 // If two types are identical, they are compatible.
11679 if (LHSCan == RHSCan)
11680 return LHS;
11681
11682 // If the qualifiers are different, the types aren't compatible... mostly.
11683 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11684 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11685 if (LQuals != RQuals) {
11686 // If any of these qualifiers are different, we have a type
11687 // mismatch.
11688 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11689 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11690 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11691 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11692 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11693 return {};
11694
11695 // Exactly one GC qualifier difference is allowed: __strong is
11696 // okay if the other type has no GC qualifier but is an Objective
11697 // C object pointer (i.e. implicitly strong by default). We fix
11698 // this by pretending that the unqualified type was actually
11699 // qualified __strong.
11700 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11701 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11702 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11703
11704 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11705 return {};
11706
11707 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11709 }
11710 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11712 }
11713 return {};
11714 }
11715
11716 // Okay, qualifiers are equal.
11717
11718 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11719 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11720
11721 // We want to consider the two function types to be the same for these
11722 // comparisons, just force one to the other.
11723 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11724 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11725
11726 // Same as above for arrays
11727 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11728 LHSClass = Type::ConstantArray;
11729 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11730 RHSClass = Type::ConstantArray;
11731
11732 // ObjCInterfaces are just specialized ObjCObjects.
11733 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11734 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11735
11736 // Canonicalize ExtVector -> Vector.
11737 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11738 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11739
11740 // If the canonical type classes don't match.
11741 if (LHSClass != RHSClass) {
11742 // Note that we only have special rules for turning block enum
11743 // returns into block int returns, not vice-versa.
11744 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11745 return mergeEnumWithInteger(*this, ETy, RHS, false);
11746 }
11747 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11748 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11749 }
11750 // allow block pointer type to match an 'id' type.
11751 if (OfBlockPointer && !BlockReturnType) {
11752 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11753 return LHS;
11754 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11755 return RHS;
11756 }
11757 // Allow __auto_type to match anything; it merges to the type with more
11758 // information.
11759 if (const auto *AT = LHS->getAs<AutoType>()) {
11760 if (!AT->isDeduced() && AT->isGNUAutoType())
11761 return RHS;
11762 }
11763 if (const auto *AT = RHS->getAs<AutoType>()) {
11764 if (!AT->isDeduced() && AT->isGNUAutoType())
11765 return LHS;
11766 }
11767 return {};
11768 }
11769
11770 // The canonical type classes match.
11771 switch (LHSClass) {
11772#define TYPE(Class, Base)
11773#define ABSTRACT_TYPE(Class, Base)
11774#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11775#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11776#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11777#include "clang/AST/TypeNodes.inc"
11778 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11779
11780 case Type::Auto:
11781 case Type::DeducedTemplateSpecialization:
11782 case Type::LValueReference:
11783 case Type::RValueReference:
11784 case Type::MemberPointer:
11785 llvm_unreachable("C++ should never be in mergeTypes");
11786
11787 case Type::ObjCInterface:
11788 case Type::IncompleteArray:
11789 case Type::VariableArray:
11790 case Type::FunctionProto:
11791 case Type::ExtVector:
11792 llvm_unreachable("Types are eliminated above");
11793
11794 case Type::Pointer:
11795 {
11796 // Merge two pointer types, while trying to preserve typedef info
11797 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11798 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11799 if (Unqualified) {
11800 LHSPointee = LHSPointee.getUnqualifiedType();
11801 RHSPointee = RHSPointee.getUnqualifiedType();
11802 }
11803 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11804 Unqualified);
11805 if (ResultType.isNull())
11806 return {};
11807 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11808 return LHS;
11809 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11810 return RHS;
11811 return getPointerType(ResultType);
11812 }
11813 case Type::BlockPointer:
11814 {
11815 // Merge two block pointer types, while trying to preserve typedef info
11816 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11817 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11818 if (Unqualified) {
11819 LHSPointee = LHSPointee.getUnqualifiedType();
11820 RHSPointee = RHSPointee.getUnqualifiedType();
11821 }
11822 if (getLangOpts().OpenCL) {
11823 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11824 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11825 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11826 // 6.12.5) thus the following check is asymmetric.
11827 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11828 return {};
11829 LHSPteeQual.removeAddressSpace();
11830 RHSPteeQual.removeAddressSpace();
11831 LHSPointee =
11832 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11833 RHSPointee =
11834 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11835 }
11836 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11837 Unqualified);
11838 if (ResultType.isNull())
11839 return {};
11840 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11841 return LHS;
11842 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11843 return RHS;
11844 return getBlockPointerType(ResultType);
11845 }
11846 case Type::Atomic:
11847 {
11848 // Merge two pointer types, while trying to preserve typedef info
11849 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11850 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11851 if (Unqualified) {
11852 LHSValue = LHSValue.getUnqualifiedType();
11853 RHSValue = RHSValue.getUnqualifiedType();
11854 }
11855 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11856 Unqualified);
11857 if (ResultType.isNull())
11858 return {};
11859 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11860 return LHS;
11861 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11862 return RHS;
11863 return getAtomicType(ResultType);
11864 }
11865 case Type::ConstantArray:
11866 {
11867 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11868 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11869 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11870 return {};
11871
11872 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11873 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11874 if (Unqualified) {
11875 LHSElem = LHSElem.getUnqualifiedType();
11876 RHSElem = RHSElem.getUnqualifiedType();
11877 }
11878
11879 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11880 if (ResultType.isNull())
11881 return {};
11882
11883 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11884 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11885
11886 // If either side is a variable array, and both are complete, check whether
11887 // the current dimension is definite.
11888 if (LVAT || RVAT) {
11889 auto SizeFetch = [this](const VariableArrayType* VAT,
11890 const ConstantArrayType* CAT)
11891 -> std::pair<bool,llvm::APInt> {
11892 if (VAT) {
11893 std::optional<llvm::APSInt> TheInt;
11894 Expr *E = VAT->getSizeExpr();
11895 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11896 return std::make_pair(true, *TheInt);
11897 return std::make_pair(false, llvm::APSInt());
11898 }
11899 if (CAT)
11900 return std::make_pair(true, CAT->getSize());
11901 return std::make_pair(false, llvm::APInt());
11902 };
11903
11904 bool HaveLSize, HaveRSize;
11905 llvm::APInt LSize, RSize;
11906 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11907 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11908 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11909 return {}; // Definite, but unequal, array dimension
11910 }
11911
11912 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11913 return LHS;
11914 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11915 return RHS;
11916 if (LCAT)
11917 return getConstantArrayType(ResultType, LCAT->getSize(),
11918 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11919 if (RCAT)
11920 return getConstantArrayType(ResultType, RCAT->getSize(),
11921 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11922 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11923 return LHS;
11924 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11925 return RHS;
11926 if (LVAT) {
11927 // FIXME: This isn't correct! But tricky to implement because
11928 // the array's size has to be the size of LHS, but the type
11929 // has to be different.
11930 return LHS;
11931 }
11932 if (RVAT) {
11933 // FIXME: This isn't correct! But tricky to implement because
11934 // the array's size has to be the size of RHS, but the type
11935 // has to be different.
11936 return RHS;
11937 }
11938 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11939 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11940 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11941 }
11942 case Type::FunctionNoProto:
11943 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11944 /*AllowCXX=*/false, IsConditionalOperator);
11945 case Type::Record:
11946 case Type::Enum:
11947 return mergeTagDefinitions(LHS, RHS);
11948 case Type::Builtin:
11949 // Only exactly equal builtin types are compatible, which is tested above.
11950 return {};
11951 case Type::Complex:
11952 // Distinct complex types are incompatible.
11953 return {};
11954 case Type::Vector:
11955 // FIXME: The merged type should be an ExtVector!
11956 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11957 RHSCan->castAs<VectorType>()))
11958 return LHS;
11959 return {};
11960 case Type::ConstantMatrix:
11962 RHSCan->castAs<ConstantMatrixType>()))
11963 return LHS;
11964 return {};
11965 case Type::ObjCObject: {
11966 // Check if the types are assignment compatible.
11967 // FIXME: This should be type compatibility, e.g. whether
11968 // "LHS x; RHS x;" at global scope is legal.
11970 RHS->castAs<ObjCObjectType>()))
11971 return LHS;
11972 return {};
11973 }
11974 case Type::ObjCObjectPointer:
11975 if (OfBlockPointer) {
11978 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11979 return LHS;
11980 return {};
11981 }
11984 return LHS;
11985 return {};
11986 case Type::Pipe:
11987 assert(LHS != RHS &&
11988 "Equivalent pipe types should have already been handled!");
11989 return {};
11990 case Type::ArrayParameter:
11991 assert(LHS != RHS &&
11992 "Equivalent ArrayParameter types should have already been handled!");
11993 return {};
11994 case Type::BitInt: {
11995 // Merge two bit-precise int types, while trying to preserve typedef info.
11996 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
11997 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
11998 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
11999 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12000
12001 // Like unsigned/int, shouldn't have a type if they don't match.
12002 if (LHSUnsigned != RHSUnsigned)
12003 return {};
12004
12005 if (LHSBits != RHSBits)
12006 return {};
12007 return LHS;
12008 }
12009 case Type::HLSLAttributedResource: {
12010 const HLSLAttributedResourceType *LHSTy =
12011 LHS->castAs<HLSLAttributedResourceType>();
12012 const HLSLAttributedResourceType *RHSTy =
12013 RHS->castAs<HLSLAttributedResourceType>();
12014 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12015 LHSTy->getWrappedType()->isHLSLResourceType() &&
12016 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12017
12018 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12019 LHSTy->getContainedType() == RHSTy->getContainedType())
12020 return LHS;
12021 return {};
12022 }
12023 case Type::HLSLInlineSpirv:
12024 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12025 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12026
12027 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12028 LHSTy->getSize() == RHSTy->getSize() &&
12029 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12030 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12031 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12032 return {};
12033
12034 return LHS;
12035 }
12036 return {};
12037 }
12038
12039 llvm_unreachable("Invalid Type::Class!");
12040}
12041
12043 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12044 bool &CanUseFirst, bool &CanUseSecond,
12046 assert(NewParamInfos.empty() && "param info list not empty");
12047 CanUseFirst = CanUseSecond = true;
12048 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12049 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12050
12051 // Fast path: if the first type doesn't have ext parameter infos,
12052 // we match if and only if the second type also doesn't have them.
12053 if (!FirstHasInfo && !SecondHasInfo)
12054 return true;
12055
12056 bool NeedParamInfo = false;
12057 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12058 : SecondFnType->getExtParameterInfos().size();
12059
12060 for (size_t I = 0; I < E; ++I) {
12061 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12062 if (FirstHasInfo)
12063 FirstParam = FirstFnType->getExtParameterInfo(I);
12064 if (SecondHasInfo)
12065 SecondParam = SecondFnType->getExtParameterInfo(I);
12066
12067 // Cannot merge unless everything except the noescape flag matches.
12068 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12069 return false;
12070
12071 bool FirstNoEscape = FirstParam.isNoEscape();
12072 bool SecondNoEscape = SecondParam.isNoEscape();
12073 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12074 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12075 if (NewParamInfos.back().getOpaqueValue())
12076 NeedParamInfo = true;
12077 if (FirstNoEscape != IsNoEscape)
12078 CanUseFirst = false;
12079 if (SecondNoEscape != IsNoEscape)
12080 CanUseSecond = false;
12081 }
12082
12083 if (!NeedParamInfo)
12084 NewParamInfos.clear();
12085
12086 return true;
12087}
12088
12090 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12091 It->second = nullptr;
12092 for (auto *SubClass : ObjCSubClasses[D])
12093 ResetObjCLayout(SubClass);
12094 }
12095}
12096
12097/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12098/// 'RHS' attributes and returns the merged version; including for function
12099/// return types.
12101 QualType LHSCan = getCanonicalType(LHS),
12102 RHSCan = getCanonicalType(RHS);
12103 // If two types are identical, they are compatible.
12104 if (LHSCan == RHSCan)
12105 return LHS;
12106 if (RHSCan->isFunctionType()) {
12107 if (!LHSCan->isFunctionType())
12108 return {};
12109 QualType OldReturnType =
12110 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12111 QualType NewReturnType =
12112 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12113 QualType ResReturnType =
12114 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12115 if (ResReturnType.isNull())
12116 return {};
12117 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12118 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12119 // In either case, use OldReturnType to build the new function type.
12120 const auto *F = LHS->castAs<FunctionType>();
12121 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12122 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12123 EPI.ExtInfo = getFunctionExtInfo(LHS);
12124 QualType ResultType =
12125 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12126 return ResultType;
12127 }
12128 }
12129 return {};
12130 }
12131
12132 // If the qualifiers are different, the types can still be merged.
12133 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12134 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12135 if (LQuals != RQuals) {
12136 // If any of these qualifiers are different, we have a type mismatch.
12137 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12138 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12139 return {};
12140
12141 // Exactly one GC qualifier difference is allowed: __strong is
12142 // okay if the other type has no GC qualifier but is an Objective
12143 // C object pointer (i.e. implicitly strong by default). We fix
12144 // this by pretending that the unqualified type was actually
12145 // qualified __strong.
12146 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12147 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12148 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12149
12150 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12151 return {};
12152
12153 if (GC_L == Qualifiers::Strong)
12154 return LHS;
12155 if (GC_R == Qualifiers::Strong)
12156 return RHS;
12157 return {};
12158 }
12159
12160 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12161 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12162 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12163 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12164 if (ResQT == LHSBaseQT)
12165 return LHS;
12166 if (ResQT == RHSBaseQT)
12167 return RHS;
12168 }
12169 return {};
12170}
12171
12172//===----------------------------------------------------------------------===//
12173// Integer Predicates
12174//===----------------------------------------------------------------------===//
12175
12177 if (const auto *ED = T->getAsEnumDecl())
12178 T = ED->getIntegerType();
12179 if (T->isBooleanType())
12180 return 1;
12181 if (const auto *EIT = T->getAs<BitIntType>())
12182 return EIT->getNumBits();
12183 // For builtin types, just use the standard type sizing method
12184 return (unsigned)getTypeSize(T);
12185}
12186
12188 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12189 T->isFixedPointType()) &&
12190 "Unexpected type");
12191
12192 // Turn <4 x signed int> -> <4 x unsigned int>
12193 if (const auto *VTy = T->getAs<VectorType>())
12194 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12195 VTy->getNumElements(), VTy->getVectorKind());
12196
12197 // For _BitInt, return an unsigned _BitInt with same width.
12198 if (const auto *EITy = T->getAs<BitIntType>())
12199 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12200
12201 // For enums, get the underlying integer type of the enum, and let the general
12202 // integer type signchanging code handle it.
12203 if (const auto *ED = T->getAsEnumDecl())
12204 T = ED->getIntegerType();
12205
12206 switch (T->castAs<BuiltinType>()->getKind()) {
12207 case BuiltinType::Char_U:
12208 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12209 case BuiltinType::Char_S:
12210 case BuiltinType::SChar:
12211 case BuiltinType::Char8:
12212 return UnsignedCharTy;
12213 case BuiltinType::Short:
12214 return UnsignedShortTy;
12215 case BuiltinType::Int:
12216 return UnsignedIntTy;
12217 case BuiltinType::Long:
12218 return UnsignedLongTy;
12219 case BuiltinType::LongLong:
12220 return UnsignedLongLongTy;
12221 case BuiltinType::Int128:
12222 return UnsignedInt128Ty;
12223 // wchar_t is special. It is either signed or not, but when it's signed,
12224 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12225 // version of its underlying type instead.
12226 case BuiltinType::WChar_S:
12227 return getUnsignedWCharType();
12228
12229 case BuiltinType::ShortAccum:
12230 return UnsignedShortAccumTy;
12231 case BuiltinType::Accum:
12232 return UnsignedAccumTy;
12233 case BuiltinType::LongAccum:
12234 return UnsignedLongAccumTy;
12235 case BuiltinType::SatShortAccum:
12237 case BuiltinType::SatAccum:
12238 return SatUnsignedAccumTy;
12239 case BuiltinType::SatLongAccum:
12241 case BuiltinType::ShortFract:
12242 return UnsignedShortFractTy;
12243 case BuiltinType::Fract:
12244 return UnsignedFractTy;
12245 case BuiltinType::LongFract:
12246 return UnsignedLongFractTy;
12247 case BuiltinType::SatShortFract:
12249 case BuiltinType::SatFract:
12250 return SatUnsignedFractTy;
12251 case BuiltinType::SatLongFract:
12253 default:
12254 assert((T->hasUnsignedIntegerRepresentation() ||
12255 T->isUnsignedFixedPointType()) &&
12256 "Unexpected signed integer or fixed point type");
12257 return T;
12258 }
12259}
12260
12262 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12263 T->isFixedPointType()) &&
12264 "Unexpected type");
12265
12266 // Turn <4 x unsigned int> -> <4 x signed int>
12267 if (const auto *VTy = T->getAs<VectorType>())
12268 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12269 VTy->getNumElements(), VTy->getVectorKind());
12270
12271 // For _BitInt, return a signed _BitInt with same width.
12272 if (const auto *EITy = T->getAs<BitIntType>())
12273 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12274
12275 // For enums, get the underlying integer type of the enum, and let the general
12276 // integer type signchanging code handle it.
12277 if (const auto *ED = T->getAsEnumDecl())
12278 T = ED->getIntegerType();
12279
12280 switch (T->castAs<BuiltinType>()->getKind()) {
12281 case BuiltinType::Char_S:
12282 // Plain `char` is mapped to `signed char` even if it's already signed
12283 case BuiltinType::Char_U:
12284 case BuiltinType::UChar:
12285 case BuiltinType::Char8:
12286 return SignedCharTy;
12287 case BuiltinType::UShort:
12288 return ShortTy;
12289 case BuiltinType::UInt:
12290 return IntTy;
12291 case BuiltinType::ULong:
12292 return LongTy;
12293 case BuiltinType::ULongLong:
12294 return LongLongTy;
12295 case BuiltinType::UInt128:
12296 return Int128Ty;
12297 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12298 // there's no matching "signed wchar_t". Therefore we return the signed
12299 // version of its underlying type instead.
12300 case BuiltinType::WChar_U:
12301 return getSignedWCharType();
12302
12303 case BuiltinType::UShortAccum:
12304 return ShortAccumTy;
12305 case BuiltinType::UAccum:
12306 return AccumTy;
12307 case BuiltinType::ULongAccum:
12308 return LongAccumTy;
12309 case BuiltinType::SatUShortAccum:
12310 return SatShortAccumTy;
12311 case BuiltinType::SatUAccum:
12312 return SatAccumTy;
12313 case BuiltinType::SatULongAccum:
12314 return SatLongAccumTy;
12315 case BuiltinType::UShortFract:
12316 return ShortFractTy;
12317 case BuiltinType::UFract:
12318 return FractTy;
12319 case BuiltinType::ULongFract:
12320 return LongFractTy;
12321 case BuiltinType::SatUShortFract:
12322 return SatShortFractTy;
12323 case BuiltinType::SatUFract:
12324 return SatFractTy;
12325 case BuiltinType::SatULongFract:
12326 return SatLongFractTy;
12327 default:
12328 assert(
12329 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12330 "Unexpected signed integer or fixed point type");
12331 return T;
12332 }
12333}
12334
12336
12339
12340//===----------------------------------------------------------------------===//
12341// Builtin Type Computation
12342//===----------------------------------------------------------------------===//
12343
12344/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12345/// pointer over the consumed characters. This returns the resultant type. If
12346/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12347/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12348/// a vector of "i*".
12349///
12350/// RequiresICE is filled in on return to indicate whether the value is required
12351/// to be an Integer Constant Expression.
12352static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12354 bool &RequiresICE,
12355 bool AllowTypeModifiers) {
12356 // Modifiers.
12357 int HowLong = 0;
12358 bool Signed = false, Unsigned = false;
12359 RequiresICE = false;
12360
12361 // Read the prefixed modifiers first.
12362 bool Done = false;
12363 #ifndef NDEBUG
12364 bool IsSpecial = false;
12365 #endif
12366 while (!Done) {
12367 switch (*Str++) {
12368 default: Done = true; --Str; break;
12369 case 'I':
12370 RequiresICE = true;
12371 break;
12372 case 'S':
12373 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12374 assert(!Signed && "Can't use 'S' modifier multiple times!");
12375 Signed = true;
12376 break;
12377 case 'U':
12378 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12379 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12380 Unsigned = true;
12381 break;
12382 case 'L':
12383 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12384 assert(HowLong <= 2 && "Can't have LLLL modifier");
12385 ++HowLong;
12386 break;
12387 case 'N':
12388 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12389 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12390 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12391 #ifndef NDEBUG
12392 IsSpecial = true;
12393 #endif
12394 if (Context.getTargetInfo().getLongWidth() == 32)
12395 ++HowLong;
12396 break;
12397 case 'W':
12398 // This modifier represents int64 type.
12399 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12400 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12401 #ifndef NDEBUG
12402 IsSpecial = true;
12403 #endif
12404 switch (Context.getTargetInfo().getInt64Type()) {
12405 default:
12406 llvm_unreachable("Unexpected integer type");
12408 HowLong = 1;
12409 break;
12411 HowLong = 2;
12412 break;
12413 }
12414 break;
12415 case 'Z':
12416 // This modifier represents int32 type.
12417 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12418 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12419 #ifndef NDEBUG
12420 IsSpecial = true;
12421 #endif
12422 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12423 default:
12424 llvm_unreachable("Unexpected integer type");
12426 HowLong = 0;
12427 break;
12429 HowLong = 1;
12430 break;
12432 HowLong = 2;
12433 break;
12434 }
12435 break;
12436 case 'O':
12437 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12438 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12439 #ifndef NDEBUG
12440 IsSpecial = true;
12441 #endif
12442 if (Context.getLangOpts().OpenCL)
12443 HowLong = 1;
12444 else
12445 HowLong = 2;
12446 break;
12447 }
12448 }
12449
12450 QualType Type;
12451
12452 // Read the base type.
12453 switch (*Str++) {
12454 default: llvm_unreachable("Unknown builtin type letter!");
12455 case 'x':
12456 assert(HowLong == 0 && !Signed && !Unsigned &&
12457 "Bad modifiers used with 'x'!");
12458 Type = Context.Float16Ty;
12459 break;
12460 case 'y':
12461 assert(HowLong == 0 && !Signed && !Unsigned &&
12462 "Bad modifiers used with 'y'!");
12463 Type = Context.BFloat16Ty;
12464 break;
12465 case 'v':
12466 assert(HowLong == 0 && !Signed && !Unsigned &&
12467 "Bad modifiers used with 'v'!");
12468 Type = Context.VoidTy;
12469 break;
12470 case 'h':
12471 assert(HowLong == 0 && !Signed && !Unsigned &&
12472 "Bad modifiers used with 'h'!");
12473 Type = Context.HalfTy;
12474 break;
12475 case 'f':
12476 assert(HowLong == 0 && !Signed && !Unsigned &&
12477 "Bad modifiers used with 'f'!");
12478 Type = Context.FloatTy;
12479 break;
12480 case 'd':
12481 assert(HowLong < 3 && !Signed && !Unsigned &&
12482 "Bad modifiers used with 'd'!");
12483 if (HowLong == 1)
12484 Type = Context.LongDoubleTy;
12485 else if (HowLong == 2)
12486 Type = Context.Float128Ty;
12487 else
12488 Type = Context.DoubleTy;
12489 break;
12490 case 's':
12491 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12492 if (Unsigned)
12493 Type = Context.UnsignedShortTy;
12494 else
12495 Type = Context.ShortTy;
12496 break;
12497 case 'i':
12498 if (HowLong == 3)
12499 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12500 else if (HowLong == 2)
12501 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12502 else if (HowLong == 1)
12503 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12504 else
12505 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12506 break;
12507 case 'c':
12508 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12509 if (Signed)
12510 Type = Context.SignedCharTy;
12511 else if (Unsigned)
12512 Type = Context.UnsignedCharTy;
12513 else
12514 Type = Context.CharTy;
12515 break;
12516 case 'b': // boolean
12517 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12518 Type = Context.BoolTy;
12519 break;
12520 case 'z': // size_t.
12521 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12522 Type = Context.getSizeType();
12523 break;
12524 case 'w': // wchar_t.
12525 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12526 Type = Context.getWideCharType();
12527 break;
12528 case 'F':
12529 Type = Context.getCFConstantStringType();
12530 break;
12531 case 'G':
12532 Type = Context.getObjCIdType();
12533 break;
12534 case 'H':
12535 Type = Context.getObjCSelType();
12536 break;
12537 case 'M':
12538 Type = Context.getObjCSuperType();
12539 break;
12540 case 'a':
12541 Type = Context.getBuiltinVaListType();
12542 assert(!Type.isNull() && "builtin va list type not initialized!");
12543 break;
12544 case 'A':
12545 // This is a "reference" to a va_list; however, what exactly
12546 // this means depends on how va_list is defined. There are two
12547 // different kinds of va_list: ones passed by value, and ones
12548 // passed by reference. An example of a by-value va_list is
12549 // x86, where va_list is a char*. An example of by-ref va_list
12550 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12551 // we want this argument to be a char*&; for x86-64, we want
12552 // it to be a __va_list_tag*.
12553 Type = Context.getBuiltinVaListType();
12554 assert(!Type.isNull() && "builtin va list type not initialized!");
12555 if (Type->isArrayType())
12556 Type = Context.getArrayDecayedType(Type);
12557 else
12558 Type = Context.getLValueReferenceType(Type);
12559 break;
12560 case 'q': {
12561 char *End;
12562 unsigned NumElements = strtoul(Str, &End, 10);
12563 assert(End != Str && "Missing vector size");
12564 Str = End;
12565
12566 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12567 RequiresICE, false);
12568 assert(!RequiresICE && "Can't require vector ICE");
12569
12570 Type = Context.getScalableVectorType(ElementType, NumElements);
12571 break;
12572 }
12573 case 'Q': {
12574 switch (*Str++) {
12575 case 'a': {
12576 Type = Context.SveCountTy;
12577 break;
12578 }
12579 case 'b': {
12580 Type = Context.AMDGPUBufferRsrcTy;
12581 break;
12582 }
12583 default:
12584 llvm_unreachable("Unexpected target builtin type");
12585 }
12586 break;
12587 }
12588 case 'V': {
12589 char *End;
12590 unsigned NumElements = strtoul(Str, &End, 10);
12591 assert(End != Str && "Missing vector size");
12592 Str = End;
12593
12594 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12595 RequiresICE, false);
12596 assert(!RequiresICE && "Can't require vector ICE");
12597
12598 // TODO: No way to make AltiVec vectors in builtins yet.
12599 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12600 break;
12601 }
12602 case 'E': {
12603 char *End;
12604
12605 unsigned NumElements = strtoul(Str, &End, 10);
12606 assert(End != Str && "Missing vector size");
12607
12608 Str = End;
12609
12610 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12611 false);
12612 Type = Context.getExtVectorType(ElementType, NumElements);
12613 break;
12614 }
12615 case 'X': {
12616 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12617 false);
12618 assert(!RequiresICE && "Can't require complex ICE");
12619 Type = Context.getComplexType(ElementType);
12620 break;
12621 }
12622 case 'Y':
12623 Type = Context.getPointerDiffType();
12624 break;
12625 case 'P':
12626 Type = Context.getFILEType();
12627 if (Type.isNull()) {
12629 return {};
12630 }
12631 break;
12632 case 'J':
12633 if (Signed)
12634 Type = Context.getsigjmp_bufType();
12635 else
12636 Type = Context.getjmp_bufType();
12637
12638 if (Type.isNull()) {
12640 return {};
12641 }
12642 break;
12643 case 'K':
12644 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12645 Type = Context.getucontext_tType();
12646
12647 if (Type.isNull()) {
12649 return {};
12650 }
12651 break;
12652 case 'p':
12653 Type = Context.getProcessIDType();
12654 break;
12655 case 'm':
12656 Type = Context.MFloat8Ty;
12657 break;
12658 }
12659
12660 // If there are modifiers and if we're allowed to parse them, go for it.
12661 Done = !AllowTypeModifiers;
12662 while (!Done) {
12663 switch (char c = *Str++) {
12664 default: Done = true; --Str; break;
12665 case '*':
12666 case '&': {
12667 // Both pointers and references can have their pointee types
12668 // qualified with an address space.
12669 char *End;
12670 unsigned AddrSpace = strtoul(Str, &End, 10);
12671 if (End != Str) {
12672 // Note AddrSpace == 0 is not the same as an unspecified address space.
12673 Type = Context.getAddrSpaceQualType(
12674 Type,
12675 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12676 Str = End;
12677 }
12678 if (c == '*')
12679 Type = Context.getPointerType(Type);
12680 else
12681 Type = Context.getLValueReferenceType(Type);
12682 break;
12683 }
12684 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12685 case 'C':
12686 Type = Type.withConst();
12687 break;
12688 case 'D':
12689 Type = Context.getVolatileType(Type);
12690 break;
12691 case 'R':
12692 Type = Type.withRestrict();
12693 break;
12694 }
12695 }
12696
12697 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12698 "Integer constant 'I' type must be an integer");
12699
12700 return Type;
12701}
12702
12703// On some targets such as PowerPC, some of the builtins are defined with custom
12704// type descriptors for target-dependent types. These descriptors are decoded in
12705// other functions, but it may be useful to be able to fall back to default
12706// descriptor decoding to define builtins mixing target-dependent and target-
12707// independent types. This function allows decoding one type descriptor with
12708// default decoding.
12709QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12710 GetBuiltinTypeError &Error, bool &RequireICE,
12711 bool AllowTypeModifiers) const {
12712 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12713}
12714
12715/// GetBuiltinType - Return the type for the specified builtin.
12718 unsigned *IntegerConstantArgs) const {
12719 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12720 if (TypeStr[0] == '\0') {
12722 return {};
12723 }
12724
12725 SmallVector<QualType, 8> ArgTypes;
12726
12727 bool RequiresICE = false;
12728 Error = GE_None;
12729 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12730 RequiresICE, true);
12731 if (Error != GE_None)
12732 return {};
12733
12734 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12735
12736 while (TypeStr[0] && TypeStr[0] != '.') {
12737 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12738 if (Error != GE_None)
12739 return {};
12740
12741 // If this argument is required to be an IntegerConstantExpression and the
12742 // caller cares, fill in the bitmask we return.
12743 if (RequiresICE && IntegerConstantArgs)
12744 *IntegerConstantArgs |= 1 << ArgTypes.size();
12745
12746 // Do array -> pointer decay. The builtin should use the decayed type.
12747 if (Ty->isArrayType())
12748 Ty = getArrayDecayedType(Ty);
12749
12750 ArgTypes.push_back(Ty);
12751 }
12752
12753 if (Id == Builtin::BI__GetExceptionInfo)
12754 return {};
12755
12756 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12757 "'.' should only occur at end of builtin type list!");
12758
12759 bool Variadic = (TypeStr[0] == '.');
12760
12761 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12762 if (BuiltinInfo.isNoReturn(Id))
12763 EI = EI.withNoReturn(true);
12764
12765 // We really shouldn't be making a no-proto type here.
12766 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12767 return getFunctionNoProtoType(ResType, EI);
12768
12770 EPI.ExtInfo = EI;
12771 EPI.Variadic = Variadic;
12772 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12773 EPI.ExceptionSpec.Type =
12775
12776 return getFunctionType(ResType, ArgTypes, EPI);
12777}
12778
12780 const FunctionDecl *FD) {
12781 if (!FD->isExternallyVisible())
12782 return GVA_Internal;
12783
12784 // Non-user-provided functions get emitted as weak definitions with every
12785 // use, no matter whether they've been explicitly instantiated etc.
12786 if (!FD->isUserProvided())
12787 return GVA_DiscardableODR;
12788
12790 switch (FD->getTemplateSpecializationKind()) {
12791 case TSK_Undeclared:
12794 break;
12795
12797 return GVA_StrongODR;
12798
12799 // C++11 [temp.explicit]p10:
12800 // [ Note: The intent is that an inline function that is the subject of
12801 // an explicit instantiation declaration will still be implicitly
12802 // instantiated when used so that the body can be considered for
12803 // inlining, but that no out-of-line copy of the inline function would be
12804 // generated in the translation unit. -- end note ]
12807
12810 break;
12811 }
12812
12813 if (!FD->isInlined())
12814 return External;
12815
12816 if ((!Context.getLangOpts().CPlusPlus &&
12817 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12818 !FD->hasAttr<DLLExportAttr>()) ||
12819 FD->hasAttr<GNUInlineAttr>()) {
12820 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12821
12822 // GNU or C99 inline semantics. Determine whether this symbol should be
12823 // externally visible.
12825 return External;
12826
12827 // C99 inline semantics, where the symbol is not externally visible.
12829 }
12830
12831 // Functions specified with extern and inline in -fms-compatibility mode
12832 // forcibly get emitted. While the body of the function cannot be later
12833 // replaced, the function definition cannot be discarded.
12834 if (FD->isMSExternInline())
12835 return GVA_StrongODR;
12836
12837 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12839 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12840 // Our approach to inheriting constructors is fundamentally different from
12841 // that used by the MS ABI, so keep our inheriting constructor thunks
12842 // internal rather than trying to pick an unambiguous mangling for them.
12843 return GVA_Internal;
12844
12845 return GVA_DiscardableODR;
12846}
12847
12849 const Decl *D, GVALinkage L) {
12850 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12851 // dllexport/dllimport on inline functions.
12852 if (D->hasAttr<DLLImportAttr>()) {
12853 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12855 } else if (D->hasAttr<DLLExportAttr>()) {
12856 if (L == GVA_DiscardableODR)
12857 return GVA_StrongODR;
12858 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12859 // Device-side functions with __global__ attribute must always be
12860 // visible externally so they can be launched from host.
12861 if (D->hasAttr<CUDAGlobalAttr>() &&
12862 (L == GVA_DiscardableODR || L == GVA_Internal))
12863 return GVA_StrongODR;
12864 // Single source offloading languages like CUDA/HIP need to be able to
12865 // access static device variables from host code of the same compilation
12866 // unit. This is done by externalizing the static variable with a shared
12867 // name between the host and device compilation which is the same for the
12868 // same compilation unit whereas different among different compilation
12869 // units.
12870 if (Context.shouldExternalize(D))
12871 return GVA_StrongExternal;
12872 }
12873 return L;
12874}
12875
12876/// Adjust the GVALinkage for a declaration based on what an external AST source
12877/// knows about whether there can be other definitions of this declaration.
12878static GVALinkage
12880 GVALinkage L) {
12881 ExternalASTSource *Source = Ctx.getExternalSource();
12882 if (!Source)
12883 return L;
12884
12885 switch (Source->hasExternalDefinitions(D)) {
12887 // Other translation units rely on us to provide the definition.
12888 if (L == GVA_DiscardableODR)
12889 return GVA_StrongODR;
12890 break;
12891
12894
12896 break;
12897 }
12898 return L;
12899}
12900
12906
12908 const VarDecl *VD) {
12909 // As an extension for interactive REPLs, make sure constant variables are
12910 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12911 // marking them as internal.
12912 if (Context.getLangOpts().CPlusPlus &&
12913 Context.getLangOpts().IncrementalExtensions &&
12914 VD->getType().isConstQualified() &&
12915 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12917 return GVA_DiscardableODR;
12918
12919 if (!VD->isExternallyVisible())
12920 return GVA_Internal;
12921
12922 if (VD->isStaticLocal()) {
12923 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12924 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12925 LexicalContext = LexicalContext->getLexicalParent();
12926
12927 // ObjC Blocks can create local variables that don't have a FunctionDecl
12928 // LexicalContext.
12929 if (!LexicalContext)
12930 return GVA_DiscardableODR;
12931
12932 // Otherwise, let the static local variable inherit its linkage from the
12933 // nearest enclosing function.
12934 auto StaticLocalLinkage =
12935 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12936
12937 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12938 // be emitted in any object with references to the symbol for the object it
12939 // contains, whether inline or out-of-line."
12940 // Similar behavior is observed with MSVC. An alternative ABI could use
12941 // StrongODR/AvailableExternally to match the function, but none are
12942 // known/supported currently.
12943 if (StaticLocalLinkage == GVA_StrongODR ||
12944 StaticLocalLinkage == GVA_AvailableExternally)
12945 return GVA_DiscardableODR;
12946 return StaticLocalLinkage;
12947 }
12948
12949 // MSVC treats in-class initialized static data members as definitions.
12950 // By giving them non-strong linkage, out-of-line definitions won't
12951 // cause link errors.
12952 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12953 return GVA_DiscardableODR;
12954
12955 // Most non-template variables have strong linkage; inline variables are
12956 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12957 GVALinkage StrongLinkage;
12958 switch (Context.getInlineVariableDefinitionKind(VD)) {
12960 StrongLinkage = GVA_StrongExternal;
12961 break;
12964 StrongLinkage = GVA_DiscardableODR;
12965 break;
12967 StrongLinkage = GVA_StrongODR;
12968 break;
12969 }
12970
12971 switch (VD->getTemplateSpecializationKind()) {
12972 case TSK_Undeclared:
12973 return StrongLinkage;
12974
12976 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12977 VD->isStaticDataMember()
12979 : StrongLinkage;
12980
12982 return GVA_StrongODR;
12983
12986
12988 return GVA_DiscardableODR;
12989 }
12990
12991 llvm_unreachable("Invalid Linkage!");
12992}
12993
12999
13001 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13002 if (!VD->isFileVarDecl())
13003 return false;
13004 // Global named register variables (GNU extension) are never emitted.
13005 if (VD->getStorageClass() == SC_Register)
13006 return false;
13007 if (VD->getDescribedVarTemplate() ||
13009 return false;
13010 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13011 // We never need to emit an uninstantiated function template.
13012 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13013 return false;
13014 } else if (isa<PragmaCommentDecl>(D))
13015 return true;
13017 return true;
13018 else if (isa<OMPRequiresDecl>(D))
13019 return true;
13020 else if (isa<OMPThreadPrivateDecl>(D))
13021 return !D->getDeclContext()->isDependentContext();
13022 else if (isa<OMPAllocateDecl>(D))
13023 return !D->getDeclContext()->isDependentContext();
13025 return !D->getDeclContext()->isDependentContext();
13026 else if (isa<ImportDecl>(D))
13027 return true;
13028 else
13029 return false;
13030
13031 // If this is a member of a class template, we do not need to emit it.
13033 return false;
13034
13035 // Weak references don't produce any output by themselves.
13036 if (D->hasAttr<WeakRefAttr>())
13037 return false;
13038
13039 // SYCL device compilation requires that functions defined with the
13040 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13041 // other entities are emitted only if they are used by a function
13042 // defined with one of those attributes.
13043 if (LangOpts.SYCLIsDevice)
13044 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13045 D->hasAttr<SYCLExternalAttr>());
13046
13047 // Aliases and used decls are required.
13048 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13049 return true;
13050
13051 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13052 // Forward declarations aren't required.
13053 if (!FD->doesThisDeclarationHaveABody())
13054 return FD->doesDeclarationForceExternallyVisibleDefinition();
13055
13056 // Constructors and destructors are required.
13057 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13058 return true;
13059
13060 // The key function for a class is required. This rule only comes
13061 // into play when inline functions can be key functions, though.
13062 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13063 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13064 const CXXRecordDecl *RD = MD->getParent();
13065 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13066 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13067 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13068 return true;
13069 }
13070 }
13071 }
13072
13074
13075 // static, static inline, always_inline, and extern inline functions can
13076 // always be deferred. Normal inline functions can be deferred in C99/C++.
13077 // Implicit template instantiations can also be deferred in C++.
13079 }
13080
13081 const auto *VD = cast<VarDecl>(D);
13082 assert(VD->isFileVarDecl() && "Expected file scoped var");
13083
13084 // If the decl is marked as `declare target to`, it should be emitted for the
13085 // host and for the device.
13086 if (LangOpts.OpenMP &&
13087 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13088 return true;
13089
13090 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13092 return false;
13093
13094 if (VD->shouldEmitInExternalSource())
13095 return false;
13096
13097 // Variables that can be needed in other TUs are required.
13100 return true;
13101
13102 // We never need to emit a variable that is available in another TU.
13104 return false;
13105
13106 // Variables that have destruction with side-effects are required.
13107 if (VD->needsDestruction(*this))
13108 return true;
13109
13110 // Variables that have initialization with side-effects are required.
13111 if (VD->hasInitWithSideEffects())
13112 return true;
13113
13114 // Likewise, variables with tuple-like bindings are required if their
13115 // bindings have side-effects.
13116 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13117 for (const auto *BD : DD->flat_bindings())
13118 if (const auto *BindingVD = BD->getHoldingVar())
13119 if (DeclMustBeEmitted(BindingVD))
13120 return true;
13121 }
13122
13123 return false;
13124}
13125
13127 const FunctionDecl *FD,
13128 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13129 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13130 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13131 FD = FD->getMostRecentDecl();
13132 // FIXME: The order of traversal here matters and depends on the order of
13133 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13134 // shouldn't rely on that.
13135 for (auto *CurDecl :
13137 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13138 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13139 SeenDecls.insert(CurFD).second) {
13140 Pred(CurFD);
13141 }
13142 }
13143}
13144
13146 bool IsCXXMethod) const {
13147 // Pass through to the C++ ABI object
13148 if (IsCXXMethod)
13149 return ABI->getDefaultMethodCallConv(IsVariadic);
13150
13151 switch (LangOpts.getDefaultCallingConv()) {
13153 break;
13155 return CC_C;
13157 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13158 return CC_X86FastCall;
13159 break;
13161 if (!IsVariadic)
13162 return CC_X86StdCall;
13163 break;
13165 // __vectorcall cannot be applied to variadic functions.
13166 if (!IsVariadic)
13167 return CC_X86VectorCall;
13168 break;
13170 // __regcall cannot be applied to variadic functions.
13171 if (!IsVariadic)
13172 return CC_X86RegCall;
13173 break;
13175 if (!IsVariadic)
13176 return CC_M68kRTD;
13177 break;
13178 }
13179 return Target->getDefaultCallingConv();
13180}
13181
13183 // Pass through to the C++ ABI object
13184 return ABI->isNearlyEmpty(RD);
13185}
13186
13188 if (!VTContext) {
13189 auto ABI = Target->getCXXABI();
13190 if (ABI.isMicrosoft())
13191 VTContext.reset(new MicrosoftVTableContext(*this));
13192 else {
13193 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13196 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13197 }
13198 }
13199 return VTContext.get();
13200}
13201
13203 if (!T)
13204 T = Target;
13205 switch (T->getCXXABI().getKind()) {
13206 case TargetCXXABI::AppleARM64:
13207 case TargetCXXABI::Fuchsia:
13208 case TargetCXXABI::GenericAArch64:
13209 case TargetCXXABI::GenericItanium:
13210 case TargetCXXABI::GenericARM:
13211 case TargetCXXABI::GenericMIPS:
13212 case TargetCXXABI::iOS:
13213 case TargetCXXABI::WebAssembly:
13214 case TargetCXXABI::WatchOS:
13215 case TargetCXXABI::XL:
13217 case TargetCXXABI::Microsoft:
13219 }
13220 llvm_unreachable("Unsupported ABI");
13221}
13222
13224 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13225 "Device mangle context does not support Microsoft mangling.");
13226 switch (T.getCXXABI().getKind()) {
13227 case TargetCXXABI::AppleARM64:
13228 case TargetCXXABI::Fuchsia:
13229 case TargetCXXABI::GenericAArch64:
13230 case TargetCXXABI::GenericItanium:
13231 case TargetCXXABI::GenericARM:
13232 case TargetCXXABI::GenericMIPS:
13233 case TargetCXXABI::iOS:
13234 case TargetCXXABI::WebAssembly:
13235 case TargetCXXABI::WatchOS:
13236 case TargetCXXABI::XL:
13238 *this, getDiagnostics(),
13239 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13240 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13241 return RD->getDeviceLambdaManglingNumber();
13242 return std::nullopt;
13243 },
13244 /*IsAux=*/true);
13245 case TargetCXXABI::Microsoft:
13247 /*IsAux=*/true);
13248 }
13249 llvm_unreachable("Unsupported ABI");
13250}
13251
13252CXXABI::~CXXABI() = default;
13253
13255 return ASTRecordLayouts.getMemorySize() +
13256 llvm::capacity_in_bytes(ObjCLayouts) +
13257 llvm::capacity_in_bytes(KeyFunctions) +
13258 llvm::capacity_in_bytes(ObjCImpls) +
13259 llvm::capacity_in_bytes(BlockVarCopyInits) +
13260 llvm::capacity_in_bytes(DeclAttrs) +
13261 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13262 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13263 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13264 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13265 llvm::capacity_in_bytes(OverriddenMethods) +
13266 llvm::capacity_in_bytes(Types) +
13267 llvm::capacity_in_bytes(VariableArrayTypes);
13268}
13269
13270/// getIntTypeForBitwidth -
13271/// sets integer QualTy according to specified details:
13272/// bitwidth, signed/unsigned.
13273/// Returns empty type if there is no appropriate target types.
13275 unsigned Signed) const {
13277 CanQualType QualTy = getFromTargetType(Ty);
13278 if (!QualTy && DestWidth == 128)
13279 return Signed ? Int128Ty : UnsignedInt128Ty;
13280 return QualTy;
13281}
13282
13283/// getRealTypeForBitwidth -
13284/// sets floating point QualTy according to specified bitwidth.
13285/// Returns empty type if there is no appropriate target types.
13287 FloatModeKind ExplicitType) const {
13288 FloatModeKind Ty =
13289 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13290 switch (Ty) {
13292 return HalfTy;
13294 return FloatTy;
13296 return DoubleTy;
13298 return LongDoubleTy;
13300 return Float128Ty;
13302 return Ibm128Ty;
13304 return {};
13305 }
13306
13307 llvm_unreachable("Unhandled TargetInfo::RealType value");
13308}
13309
13310void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13311 if (Number <= 1)
13312 return;
13313
13314 MangleNumbers[ND] = Number;
13315
13316 if (Listener)
13317 Listener->AddedManglingNumber(ND, Number);
13318}
13319
13321 bool ForAuxTarget) const {
13322 auto I = MangleNumbers.find(ND);
13323 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13324 // CUDA/HIP host compilation encodes host and device mangling numbers
13325 // as lower and upper half of 32 bit integer.
13326 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13327 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13328 } else {
13329 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13330 "number for aux target");
13331 }
13332 return Res > 1 ? Res : 1;
13333}
13334
13335void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13336 if (Number <= 1)
13337 return;
13338
13339 StaticLocalNumbers[VD] = Number;
13340
13341 if (Listener)
13342 Listener->AddedStaticLocalNumbers(VD, Number);
13343}
13344
13346 auto I = StaticLocalNumbers.find(VD);
13347 return I != StaticLocalNumbers.end() ? I->second : 1;
13348}
13349
13351 bool IsDestroying) {
13352 if (!IsDestroying) {
13353 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13354 return;
13355 }
13356 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13357}
13358
13360 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13361}
13362
13364 bool IsTypeAware) {
13365 if (!IsTypeAware) {
13366 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13367 return;
13368 }
13369 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13370}
13371
13373 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13374}
13375
13378 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13379 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13380 if (!MCtx)
13382 return *MCtx;
13383}
13384
13387 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13388 std::unique_ptr<MangleNumberingContext> &MCtx =
13389 ExtraMangleNumberingContexts[D];
13390 if (!MCtx)
13392 return *MCtx;
13393}
13394
13395std::unique_ptr<MangleNumberingContext>
13397 return ABI->createMangleNumberingContext();
13398}
13399
13400const CXXConstructorDecl *
13402 return ABI->getCopyConstructorForExceptionObject(
13404}
13405
13407 CXXConstructorDecl *CD) {
13408 return ABI->addCopyConstructorForExceptionObject(
13411}
13412
13414 TypedefNameDecl *DD) {
13415 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13416}
13417
13420 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13421}
13422
13424 DeclaratorDecl *DD) {
13425 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13426}
13427
13429 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13430}
13431
13433 ParamIndices[D] = index;
13434}
13435
13437 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13438 assert(I != ParamIndices.end() &&
13439 "ParmIndices lacks entry set by ParmVarDecl");
13440 return I->second;
13441}
13442
13444 unsigned Length) const {
13445 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13446 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13447 EltTy = EltTy.withConst();
13448
13449 EltTy = adjustStringLiteralBaseType(EltTy);
13450
13451 // Get an array type for the string, according to C99 6.4.5. This includes
13452 // the null terminator character.
13453 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13454 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13455}
13456
13459 StringLiteral *&Result = StringLiteralCache[Key];
13460 if (!Result)
13462 *this, Key, StringLiteralKind::Ordinary,
13463 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13464 SourceLocation());
13465 return Result;
13466}
13467
13468MSGuidDecl *
13470 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13471
13472 llvm::FoldingSetNodeID ID;
13473 MSGuidDecl::Profile(ID, Parts);
13474
13475 void *InsertPos;
13476 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13477 return Existing;
13478
13479 QualType GUIDType = getMSGuidType().withConst();
13480 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13481 MSGuidDecls.InsertNode(New, InsertPos);
13482 return New;
13483}
13484
13487 const APValue &APVal) const {
13488 llvm::FoldingSetNodeID ID;
13490
13491 void *InsertPos;
13492 if (UnnamedGlobalConstantDecl *Existing =
13493 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13494 return Existing;
13495
13497 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13498 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13499 return New;
13500}
13501
13504 assert(T->isRecordType() && "template param object of unexpected type");
13505
13506 // C++ [temp.param]p8:
13507 // [...] a static storage duration object of type 'const T' [...]
13508 T.addConst();
13509
13510 llvm::FoldingSetNodeID ID;
13512
13513 void *InsertPos;
13514 if (TemplateParamObjectDecl *Existing =
13515 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13516 return Existing;
13517
13518 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13519 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13520 return New;
13521}
13522
13524 const llvm::Triple &T = getTargetInfo().getTriple();
13525 if (!T.isOSDarwin())
13526 return false;
13527
13528 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13529 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13530 return false;
13531
13532 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13533 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13534 uint64_t Size = sizeChars.getQuantity();
13535 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13536 unsigned Align = alignChars.getQuantity();
13537 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13538 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13539}
13540
13541bool
13543 const ObjCMethodDecl *MethodImpl) {
13544 // No point trying to match an unavailable/deprecated mothod.
13545 if (MethodDecl->hasAttr<UnavailableAttr>()
13546 || MethodDecl->hasAttr<DeprecatedAttr>())
13547 return false;
13548 if (MethodDecl->getObjCDeclQualifier() !=
13549 MethodImpl->getObjCDeclQualifier())
13550 return false;
13551 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13552 return false;
13553
13554 if (MethodDecl->param_size() != MethodImpl->param_size())
13555 return false;
13556
13557 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13558 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13559 EF = MethodDecl->param_end();
13560 IM != EM && IF != EF; ++IM, ++IF) {
13561 const ParmVarDecl *DeclVar = (*IF);
13562 const ParmVarDecl *ImplVar = (*IM);
13563 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13564 return false;
13565 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13566 return false;
13567 }
13568
13569 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13570}
13571
13573 LangAS AS;
13575 AS = LangAS::Default;
13576 else
13577 AS = QT->getPointeeType().getAddressSpace();
13578
13580}
13581
13584}
13585
13586bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13587 if (X == Y)
13588 return true;
13589 if (!X || !Y)
13590 return false;
13591 llvm::FoldingSetNodeID IDX, IDY;
13592 X->Profile(IDX, *this, /*Canonical=*/true);
13593 Y->Profile(IDY, *this, /*Canonical=*/true);
13594 return IDX == IDY;
13595}
13596
13597// The getCommon* helpers return, for given 'same' X and Y entities given as
13598// inputs, another entity which is also the 'same' as the inputs, but which
13599// is closer to the canonical form of the inputs, each according to a given
13600// criteria.
13601// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13602// the regular ones.
13603
13605 if (!declaresSameEntity(X, Y))
13606 return nullptr;
13607 for (const Decl *DX : X->redecls()) {
13608 // If we reach Y before reaching the first decl, that means X is older.
13609 if (DX == Y)
13610 return X;
13611 // If we reach the first decl, then Y is older.
13612 if (DX->isFirstDecl())
13613 return Y;
13614 }
13615 llvm_unreachable("Corrupt redecls chain");
13616}
13617
13618template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13619static T *getCommonDecl(T *X, T *Y) {
13620 return cast_or_null<T>(
13621 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13622 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13623}
13624
13625template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13626static T *getCommonDeclChecked(T *X, T *Y) {
13627 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13628 const_cast<Decl *>(cast<Decl>(Y))));
13629}
13630
13632 TemplateName Y,
13633 bool IgnoreDeduced = false) {
13634 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13635 return X;
13636 // FIXME: There are cases here where we could find a common template name
13637 // with more sugar. For example one could be a SubstTemplateTemplate*
13638 // replacing the other.
13639 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13640 if (CX.getAsVoidPointer() !=
13642 return TemplateName();
13643 return CX;
13644}
13645
13648 bool IgnoreDeduced) {
13649 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13650 assert(R.getAsVoidPointer() != nullptr);
13651 return R;
13652}
13653
13655 ArrayRef<QualType> Ys, bool Unqualified = false) {
13656 assert(Xs.size() == Ys.size());
13657 SmallVector<QualType, 8> Rs(Xs.size());
13658 for (size_t I = 0; I < Rs.size(); ++I)
13659 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13660 return Rs;
13661}
13662
13663template <class T>
13664static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13665 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13666 : SourceLocation();
13667}
13668
13670 const TemplateArgument &X,
13671 const TemplateArgument &Y) {
13672 if (X.getKind() != Y.getKind())
13673 return TemplateArgument();
13674
13675 switch (X.getKind()) {
13677 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13678 return TemplateArgument();
13679 return TemplateArgument(
13680 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13682 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13683 return TemplateArgument();
13684 return TemplateArgument(
13685 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13686 /*Unqualified=*/true);
13688 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13689 return TemplateArgument();
13690 // FIXME: Try to keep the common sugar.
13691 return X;
13693 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13694 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13695 if (!CTN.getAsVoidPointer())
13696 return TemplateArgument();
13697 return TemplateArgument(CTN);
13698 }
13700 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13702 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13703 if (!CTN.getAsVoidPointer())
13704 return TemplateName();
13705 auto NExpX = X.getNumTemplateExpansions();
13706 assert(NExpX == Y.getNumTemplateExpansions());
13707 return TemplateArgument(CTN, NExpX);
13708 }
13709 default:
13710 // FIXME: Handle the other argument kinds.
13711 return X;
13712 }
13713}
13714
13719 if (Xs.size() != Ys.size())
13720 return true;
13721 R.resize(Xs.size());
13722 for (size_t I = 0; I < R.size(); ++I) {
13723 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13724 if (R[I].isNull())
13725 return true;
13726 }
13727 return false;
13728}
13729
13734 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13735 assert(!Different);
13736 (void)Different;
13737 return R;
13738}
13739
13740template <class T>
13742 bool IsSame) {
13743 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13744 if (KX == KY)
13745 return KX;
13747 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13748 return KX;
13749}
13750
13751/// Returns a NestedNameSpecifier which has only the common sugar
13752/// present in both NNS1 and NNS2.
13755 NestedNameSpecifier NNS2, bool IsSame) {
13756 // If they are identical, all sugar is common.
13757 if (NNS1 == NNS2)
13758 return NNS1;
13759
13760 // IsSame implies both Qualifiers are equivalent.
13761 NestedNameSpecifier Canon = NNS1.getCanonical();
13762 if (Canon != NNS2.getCanonical()) {
13763 assert(!IsSame && "Should be the same NestedNameSpecifier");
13764 // If they are not the same, there is nothing to unify.
13765 return std::nullopt;
13766 }
13767
13768 NestedNameSpecifier R = std::nullopt;
13769 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13770 assert(Kind == NNS2.getKind());
13771 switch (Kind) {
13773 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13774 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13775 auto Kind = Namespace1->getKind();
13776 if (Kind != Namespace2->getKind() ||
13777 (Kind == Decl::NamespaceAlias &&
13778 !declaresSameEntity(Namespace1, Namespace2))) {
13780 Ctx,
13781 ::getCommonDeclChecked(Namespace1->getNamespace(),
13782 Namespace2->getNamespace()),
13783 /*Prefix=*/std::nullopt);
13784 break;
13785 }
13786 // The prefixes for namespaces are not significant, its declaration
13787 // identifies it uniquely.
13788 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13789 /*IsSame=*/false);
13790 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13791 Prefix);
13792 break;
13793 }
13795 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13796 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13797 /*Unqualified=*/true)
13798 .getTypePtr();
13800 break;
13801 }
13803 // FIXME: Can __super even be used with data members?
13804 // If it's only usable in functions, we will never see it here,
13805 // unless we save the qualifiers used in function types.
13806 // In that case, it might be possible NNS2 is a type,
13807 // in which case we should degrade the result to
13808 // a CXXRecordType.
13810 NNS2.getAsMicrosoftSuper()));
13811 break;
13812 }
13815 // These are singletons.
13816 llvm_unreachable("singletons did not compare equal");
13817 }
13818 assert(R.getCanonical() == Canon);
13819 return R;
13820}
13821
13822template <class T>
13824 const T *Y, bool IsSame) {
13825 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13826}
13827
13828template <class T>
13829static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13830 const T *Y) {
13831 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13832}
13833
13834template <class T>
13836 Qualifiers &QX, const T *Y,
13837 Qualifiers &QY) {
13838 QualType EX = X->getElementType(), EY = Y->getElementType();
13839 QualType R = Ctx.getCommonSugaredType(EX, EY,
13840 /*Unqualified=*/true);
13841 // Qualifiers common to both element types.
13842 Qualifiers RQ = R.getQualifiers();
13843 // For each side, move to the top level any qualifiers which are not common to
13844 // both element types. The caller must assume top level qualifiers might
13845 // be different, even if they are the same type, and can be treated as sugar.
13846 QX += EX.getQualifiers() - RQ;
13847 QY += EY.getQualifiers() - RQ;
13848 return R;
13849}
13850
13851template <class T>
13852static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13853 const T *Y) {
13854 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13855}
13856
13857template <class T>
13858static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13859 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13860 return X->getSizeExpr();
13861}
13862
13863static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13864 assert(X->getSizeModifier() == Y->getSizeModifier());
13865 return X->getSizeModifier();
13866}
13867
13869 const ArrayType *Y) {
13870 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13871 return X->getIndexTypeCVRQualifiers();
13872}
13873
13874// Merges two type lists such that the resulting vector will contain
13875// each type (in a canonical sense) only once, in the order they appear
13876// from X to Y. If they occur in both X and Y, the result will contain
13877// the common sugared type between them.
13878static void mergeTypeLists(const ASTContext &Ctx,
13881 llvm::DenseMap<QualType, unsigned> Found;
13882 for (auto Ts : {X, Y}) {
13883 for (QualType T : Ts) {
13884 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13885 if (!Res.second) {
13886 QualType &U = Out[Res.first->second];
13887 U = Ctx.getCommonSugaredType(U, T);
13888 } else {
13889 Out.emplace_back(T);
13890 }
13891 }
13892 }
13893}
13894
13895FunctionProtoType::ExceptionSpecInfo
13898 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13899 bool AcceptDependent) const {
13900 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13901
13902 // If either of them can throw anything, that is the result.
13903 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13904 if (EST1 == I)
13905 return ESI1;
13906 if (EST2 == I)
13907 return ESI2;
13908 }
13909
13910 // If either of them is non-throwing, the result is the other.
13911 for (auto I :
13913 if (EST1 == I)
13914 return ESI2;
13915 if (EST2 == I)
13916 return ESI1;
13917 }
13918
13919 // If we're left with value-dependent computed noexcept expressions, we're
13920 // stuck. Before C++17, we can just drop the exception specification entirely,
13921 // since it's not actually part of the canonical type. And this should never
13922 // happen in C++17, because it would mean we were computing the composite
13923 // pointer type of dependent types, which should never happen.
13924 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13925 assert(AcceptDependent &&
13926 "computing composite pointer type of dependent types");
13928 }
13929
13930 // Switch over the possibilities so that people adding new values know to
13931 // update this function.
13932 switch (EST1) {
13933 case EST_None:
13934 case EST_DynamicNone:
13935 case EST_MSAny:
13936 case EST_BasicNoexcept:
13938 case EST_NoexceptFalse:
13939 case EST_NoexceptTrue:
13940 case EST_NoThrow:
13941 llvm_unreachable("These ESTs should be handled above");
13942
13943 case EST_Dynamic: {
13944 // This is the fun case: both exception specifications are dynamic. Form
13945 // the union of the two lists.
13946 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13947 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13948 ESI2.Exceptions);
13950 Result.Exceptions = ExceptionTypeStorage;
13951 return Result;
13952 }
13953
13954 case EST_Unevaluated:
13955 case EST_Uninstantiated:
13956 case EST_Unparsed:
13957 llvm_unreachable("shouldn't see unresolved exception specifications here");
13958 }
13959
13960 llvm_unreachable("invalid ExceptionSpecificationType");
13961}
13962
13964 Qualifiers &QX, const Type *Y,
13965 Qualifiers &QY) {
13966 Type::TypeClass TC = X->getTypeClass();
13967 assert(TC == Y->getTypeClass());
13968 switch (TC) {
13969#define UNEXPECTED_TYPE(Class, Kind) \
13970 case Type::Class: \
13971 llvm_unreachable("Unexpected " Kind ": " #Class);
13972
13973#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13974#define TYPE(Class, Base)
13975#include "clang/AST/TypeNodes.inc"
13976
13977#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13979 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13980 SUGAR_FREE_TYPE(DependentBitInt)
13982 SUGAR_FREE_TYPE(ObjCInterface)
13983 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13984 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
13985 SUGAR_FREE_TYPE(UnresolvedUsing)
13986 SUGAR_FREE_TYPE(HLSLAttributedResource)
13987 SUGAR_FREE_TYPE(HLSLInlineSpirv)
13988#undef SUGAR_FREE_TYPE
13989#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
13990 NON_UNIQUE_TYPE(TypeOfExpr)
13991 NON_UNIQUE_TYPE(VariableArray)
13992#undef NON_UNIQUE_TYPE
13993
13994 UNEXPECTED_TYPE(TypeOf, "sugar")
13995
13996#undef UNEXPECTED_TYPE
13997
13998 case Type::Auto: {
13999 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14000 assert(AX->getDeducedType().isNull());
14001 assert(AY->getDeducedType().isNull());
14002 assert(AX->getKeyword() == AY->getKeyword());
14003 assert(AX->isInstantiationDependentType() ==
14004 AY->isInstantiationDependentType());
14005 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14006 AY->getTypeConstraintArguments());
14007 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14009 AX->containsUnexpandedParameterPack(),
14010 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14011 AY->getTypeConstraintConcept()),
14012 As);
14013 }
14014 case Type::IncompleteArray: {
14015 const auto *AX = cast<IncompleteArrayType>(X),
14017 return Ctx.getIncompleteArrayType(
14018 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14020 }
14021 case Type::DependentSizedArray: {
14022 const auto *AX = cast<DependentSizedArrayType>(X),
14024 return Ctx.getDependentSizedArrayType(
14025 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14026 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14028 }
14029 case Type::ConstantArray: {
14030 const auto *AX = cast<ConstantArrayType>(X),
14031 *AY = cast<ConstantArrayType>(Y);
14032 assert(AX->getSize() == AY->getSize());
14033 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14034 ? AX->getSizeExpr()
14035 : nullptr;
14036 return Ctx.getConstantArrayType(
14037 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14039 }
14040 case Type::ArrayParameter: {
14041 const auto *AX = cast<ArrayParameterType>(X),
14042 *AY = cast<ArrayParameterType>(Y);
14043 assert(AX->getSize() == AY->getSize());
14044 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14045 ? AX->getSizeExpr()
14046 : nullptr;
14047 auto ArrayTy = Ctx.getConstantArrayType(
14048 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14050 return Ctx.getArrayParameterType(ArrayTy);
14051 }
14052 case Type::Atomic: {
14053 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14054 return Ctx.getAtomicType(
14055 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14056 }
14057 case Type::Complex: {
14058 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14059 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14060 }
14061 case Type::Pointer: {
14062 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14063 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14064 }
14065 case Type::BlockPointer: {
14066 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14067 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14068 }
14069 case Type::ObjCObjectPointer: {
14070 const auto *PX = cast<ObjCObjectPointerType>(X),
14072 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14073 }
14074 case Type::MemberPointer: {
14075 const auto *PX = cast<MemberPointerType>(X),
14076 *PY = cast<MemberPointerType>(Y);
14077 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14078 PY->getMostRecentCXXRecordDecl()));
14079 return Ctx.getMemberPointerType(
14080 getCommonPointeeType(Ctx, PX, PY),
14081 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14082 PX->getMostRecentCXXRecordDecl());
14083 }
14084 case Type::LValueReference: {
14085 const auto *PX = cast<LValueReferenceType>(X),
14087 // FIXME: Preserve PointeeTypeAsWritten.
14088 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14089 PX->isSpelledAsLValue() ||
14090 PY->isSpelledAsLValue());
14091 }
14092 case Type::RValueReference: {
14093 const auto *PX = cast<RValueReferenceType>(X),
14095 // FIXME: Preserve PointeeTypeAsWritten.
14096 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14097 }
14098 case Type::DependentAddressSpace: {
14099 const auto *PX = cast<DependentAddressSpaceType>(X),
14101 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14102 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14103 PX->getAddrSpaceExpr(),
14104 getCommonAttrLoc(PX, PY));
14105 }
14106 case Type::FunctionNoProto: {
14107 const auto *FX = cast<FunctionNoProtoType>(X),
14109 assert(FX->getExtInfo() == FY->getExtInfo());
14110 return Ctx.getFunctionNoProtoType(
14111 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14112 FX->getExtInfo());
14113 }
14114 case Type::FunctionProto: {
14115 const auto *FX = cast<FunctionProtoType>(X),
14116 *FY = cast<FunctionProtoType>(Y);
14117 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14118 EPIY = FY->getExtProtoInfo();
14119 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14120 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14121 assert(!EPIX.ExtParameterInfos ||
14122 llvm::equal(
14123 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14124 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14125 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14126 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14127 assert(EPIX.Variadic == EPIY.Variadic);
14128
14129 // FIXME: Can we handle an empty EllipsisLoc?
14130 // Use emtpy EllipsisLoc if X and Y differ.
14131
14132 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14133
14134 QualType R =
14135 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14136 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14137 /*Unqualified=*/true);
14138
14139 SmallVector<QualType, 8> Exceptions;
14141 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14142 return Ctx.getFunctionType(R, P, EPIX);
14143 }
14144 case Type::ObjCObject: {
14145 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14146 assert(
14147 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14148 OY->getProtocols().begin(), OY->getProtocols().end(),
14149 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14150 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14151 }) &&
14152 "protocol lists must be the same");
14153 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14154 OY->getTypeArgsAsWritten());
14155 return Ctx.getObjCObjectType(
14156 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14157 OX->getProtocols(),
14158 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14159 }
14160 case Type::ConstantMatrix: {
14161 const auto *MX = cast<ConstantMatrixType>(X),
14162 *MY = cast<ConstantMatrixType>(Y);
14163 assert(MX->getNumRows() == MY->getNumRows());
14164 assert(MX->getNumColumns() == MY->getNumColumns());
14165 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14166 MX->getNumRows(), MX->getNumColumns());
14167 }
14168 case Type::DependentSizedMatrix: {
14169 const auto *MX = cast<DependentSizedMatrixType>(X),
14171 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14172 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14173 return Ctx.getDependentSizedMatrixType(
14174 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14175 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14176 }
14177 case Type::Vector: {
14178 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14179 assert(VX->getNumElements() == VY->getNumElements());
14180 assert(VX->getVectorKind() == VY->getVectorKind());
14181 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14182 VX->getNumElements(), VX->getVectorKind());
14183 }
14184 case Type::ExtVector: {
14185 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14186 assert(VX->getNumElements() == VY->getNumElements());
14187 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14188 VX->getNumElements());
14189 }
14190 case Type::DependentSizedExtVector: {
14191 const auto *VX = cast<DependentSizedExtVectorType>(X),
14194 getCommonSizeExpr(Ctx, VX, VY),
14195 getCommonAttrLoc(VX, VY));
14196 }
14197 case Type::DependentVector: {
14198 const auto *VX = cast<DependentVectorType>(X),
14200 assert(VX->getVectorKind() == VY->getVectorKind());
14201 return Ctx.getDependentVectorType(
14202 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14203 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14204 }
14205 case Type::Enum:
14206 case Type::Record:
14207 case Type::InjectedClassName: {
14208 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14209 return Ctx.getTagType(
14210 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14211 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14212 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14213 /*OwnedTag=*/false);
14214 }
14215 case Type::TemplateSpecialization: {
14216 const auto *TX = cast<TemplateSpecializationType>(X),
14218 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14219 TY->template_arguments());
14221 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14222 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14223 TY->getTemplateName(),
14224 /*IgnoreDeduced=*/true),
14225 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14226 }
14227 case Type::Decltype: {
14228 const auto *DX = cast<DecltypeType>(X);
14229 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14230 assert(DX->isDependentType());
14231 assert(DY->isDependentType());
14232 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14233 // As Decltype is not uniqued, building a common type would be wasteful.
14234 return QualType(DX, 0);
14235 }
14236 case Type::PackIndexing: {
14237 const auto *DX = cast<PackIndexingType>(X);
14238 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14239 assert(DX->isDependentType());
14240 assert(DY->isDependentType());
14241 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14242 return QualType(DX, 0);
14243 }
14244 case Type::DependentName: {
14245 const auto *NX = cast<DependentNameType>(X),
14246 *NY = cast<DependentNameType>(Y);
14247 assert(NX->getIdentifier() == NY->getIdentifier());
14248 return Ctx.getDependentNameType(
14249 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14250 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14251 }
14252 case Type::UnaryTransform: {
14253 const auto *TX = cast<UnaryTransformType>(X),
14254 *TY = cast<UnaryTransformType>(Y);
14255 assert(TX->getUTTKind() == TY->getUTTKind());
14256 return Ctx.getUnaryTransformType(
14257 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14258 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14259 TY->getUnderlyingType()),
14260 TX->getUTTKind());
14261 }
14262 case Type::PackExpansion: {
14263 const auto *PX = cast<PackExpansionType>(X),
14264 *PY = cast<PackExpansionType>(Y);
14265 assert(PX->getNumExpansions() == PY->getNumExpansions());
14266 return Ctx.getPackExpansionType(
14267 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14268 PX->getNumExpansions(), false);
14269 }
14270 case Type::Pipe: {
14271 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14272 assert(PX->isReadOnly() == PY->isReadOnly());
14273 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14275 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14276 }
14277 case Type::TemplateTypeParm: {
14278 const auto *TX = cast<TemplateTypeParmType>(X),
14280 assert(TX->getDepth() == TY->getDepth());
14281 assert(TX->getIndex() == TY->getIndex());
14282 assert(TX->isParameterPack() == TY->isParameterPack());
14283 return Ctx.getTemplateTypeParmType(
14284 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14285 getCommonDecl(TX->getDecl(), TY->getDecl()));
14286 }
14287 }
14288 llvm_unreachable("Unknown Type Class");
14289}
14290
14292 const Type *Y,
14293 SplitQualType Underlying) {
14294 Type::TypeClass TC = X->getTypeClass();
14295 if (TC != Y->getTypeClass())
14296 return QualType();
14297 switch (TC) {
14298#define UNEXPECTED_TYPE(Class, Kind) \
14299 case Type::Class: \
14300 llvm_unreachable("Unexpected " Kind ": " #Class);
14301#define TYPE(Class, Base)
14302#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14303#include "clang/AST/TypeNodes.inc"
14304
14305#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14308 CANONICAL_TYPE(BlockPointer)
14311 CANONICAL_TYPE(ConstantArray)
14312 CANONICAL_TYPE(ArrayParameter)
14313 CANONICAL_TYPE(ConstantMatrix)
14315 CANONICAL_TYPE(ExtVector)
14316 CANONICAL_TYPE(FunctionNoProto)
14317 CANONICAL_TYPE(FunctionProto)
14318 CANONICAL_TYPE(IncompleteArray)
14319 CANONICAL_TYPE(HLSLAttributedResource)
14320 CANONICAL_TYPE(HLSLInlineSpirv)
14321 CANONICAL_TYPE(LValueReference)
14322 CANONICAL_TYPE(ObjCInterface)
14323 CANONICAL_TYPE(ObjCObject)
14324 CANONICAL_TYPE(ObjCObjectPointer)
14328 CANONICAL_TYPE(RValueReference)
14329 CANONICAL_TYPE(VariableArray)
14331#undef CANONICAL_TYPE
14332
14333#undef UNEXPECTED_TYPE
14334
14335 case Type::Adjusted: {
14336 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14337 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14338 if (!Ctx.hasSameType(OX, OY))
14339 return QualType();
14340 // FIXME: It's inefficient to have to unify the original types.
14341 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14342 Ctx.getQualifiedType(Underlying));
14343 }
14344 case Type::Decayed: {
14345 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14346 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14347 if (!Ctx.hasSameType(OX, OY))
14348 return QualType();
14349 // FIXME: It's inefficient to have to unify the original types.
14350 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14351 Ctx.getQualifiedType(Underlying));
14352 }
14353 case Type::Attributed: {
14354 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14355 AttributedType::Kind Kind = AX->getAttrKind();
14356 if (Kind != AY->getAttrKind())
14357 return QualType();
14358 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14359 if (!Ctx.hasSameType(MX, MY))
14360 return QualType();
14361 // FIXME: It's inefficient to have to unify the modified types.
14362 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14363 Ctx.getQualifiedType(Underlying),
14364 AX->getAttr());
14365 }
14366 case Type::BTFTagAttributed: {
14367 const auto *BX = cast<BTFTagAttributedType>(X);
14368 const BTFTypeTagAttr *AX = BX->getAttr();
14369 // The attribute is not uniqued, so just compare the tag.
14370 if (AX->getBTFTypeTag() !=
14371 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14372 return QualType();
14373 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14374 }
14375 case Type::Auto: {
14376 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14377
14378 AutoTypeKeyword KW = AX->getKeyword();
14379 if (KW != AY->getKeyword())
14380 return QualType();
14381
14382 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14383 AY->getTypeConstraintConcept());
14385 if (CD &&
14386 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14387 AY->getTypeConstraintArguments())) {
14388 CD = nullptr; // The arguments differ, so make it unconstrained.
14389 As.clear();
14390 }
14391
14392 // Both auto types can't be dependent, otherwise they wouldn't have been
14393 // sugar. This implies they can't contain unexpanded packs either.
14394 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14395 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14396 }
14397 case Type::PackIndexing:
14398 case Type::Decltype:
14399 return QualType();
14400 case Type::DeducedTemplateSpecialization:
14401 // FIXME: Try to merge these.
14402 return QualType();
14403 case Type::MacroQualified: {
14404 const auto *MX = cast<MacroQualifiedType>(X),
14405 *MY = cast<MacroQualifiedType>(Y);
14406 const IdentifierInfo *IX = MX->getMacroIdentifier();
14407 if (IX != MY->getMacroIdentifier())
14408 return QualType();
14409 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14410 }
14411 case Type::SubstTemplateTypeParm: {
14412 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14414 Decl *CD =
14415 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14416 if (!CD)
14417 return QualType();
14418 unsigned Index = SX->getIndex();
14419 if (Index != SY->getIndex())
14420 return QualType();
14421 auto PackIndex = SX->getPackIndex();
14422 if (PackIndex != SY->getPackIndex())
14423 return QualType();
14424 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14425 CD, Index, PackIndex,
14426 SX->getFinal() && SY->getFinal());
14427 }
14428 case Type::ObjCTypeParam:
14429 // FIXME: Try to merge these.
14430 return QualType();
14431 case Type::Paren:
14432 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14433
14434 case Type::TemplateSpecialization: {
14435 const auto *TX = cast<TemplateSpecializationType>(X),
14437 TemplateName CTN =
14438 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14439 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14440 if (!CTN.getAsVoidPointer())
14441 return QualType();
14443 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14444 TY->template_arguments()))
14445 return QualType();
14447 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14448 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14449 }
14450 case Type::Typedef: {
14451 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14452 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14453 if (!CD)
14454 return QualType();
14455 return Ctx.getTypedefType(
14456 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14457 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14458 Ctx.getQualifiedType(Underlying));
14459 }
14460 case Type::TypeOf: {
14461 // The common sugar between two typeof expressions, where one is
14462 // potentially a typeof_unqual and the other is not, we unify to the
14463 // qualified type as that retains the most information along with the type.
14464 // We only return a typeof_unqual type when both types are unqual types.
14469 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14470 }
14471 case Type::TypeOfExpr:
14472 return QualType();
14473
14474 case Type::UnaryTransform: {
14475 const auto *UX = cast<UnaryTransformType>(X),
14476 *UY = cast<UnaryTransformType>(Y);
14477 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14478 if (KX != UY->getUTTKind())
14479 return QualType();
14480 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14481 if (!Ctx.hasSameType(BX, BY))
14482 return QualType();
14483 // FIXME: It's inefficient to have to unify the base types.
14484 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14485 Ctx.getQualifiedType(Underlying), KX);
14486 }
14487 case Type::Using: {
14488 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14489 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14490 if (!CD)
14491 return QualType();
14492 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14493 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14494 CD, Ctx.getQualifiedType(Underlying));
14495 }
14496 case Type::MemberPointer: {
14497 const auto *PX = cast<MemberPointerType>(X),
14498 *PY = cast<MemberPointerType>(Y);
14499 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14500 assert(Cls == PY->getMostRecentCXXRecordDecl());
14501 return Ctx.getMemberPointerType(
14502 ::getCommonPointeeType(Ctx, PX, PY),
14503 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14504 }
14505 case Type::CountAttributed: {
14506 const auto *DX = cast<CountAttributedType>(X),
14508 if (DX->isCountInBytes() != DY->isCountInBytes())
14509 return QualType();
14510 if (DX->isOrNull() != DY->isOrNull())
14511 return QualType();
14512 Expr *CEX = DX->getCountExpr();
14513 Expr *CEY = DY->getCountExpr();
14514 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14515 if (Ctx.hasSameExpr(CEX, CEY))
14516 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14517 DX->isCountInBytes(), DX->isOrNull(),
14518 CDX);
14519 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14520 return QualType();
14521 // Two declarations with the same integer constant may still differ in their
14522 // expression pointers, so we need to evaluate them.
14523 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14524 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14525 if (VX != VY)
14526 return QualType();
14527 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14528 DX->isCountInBytes(), DX->isOrNull(),
14529 CDX);
14530 }
14531 case Type::PredefinedSugar:
14532 assert(cast<PredefinedSugarType>(X)->getKind() !=
14534 return QualType();
14535 }
14536 llvm_unreachable("Unhandled Type Class");
14537}
14538
14539static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14541 while (true) {
14542 QTotal.addConsistentQualifiers(T.Quals);
14543 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14544 if (NT == QualType(T.Ty, 0))
14545 break;
14546 R.push_back(T);
14547 T = NT.split();
14548 }
14549 return R;
14550}
14551
14553 bool Unqualified) const {
14554 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14555 if (X == Y)
14556 return X;
14557 if (!Unqualified) {
14558 if (X.isCanonical())
14559 return X;
14560 if (Y.isCanonical())
14561 return Y;
14562 }
14563
14564 SplitQualType SX = X.split(), SY = Y.split();
14565 Qualifiers QX, QY;
14566 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14567 // until we reach their underlying "canonical nodes". Note these are not
14568 // necessarily canonical types, as they may still have sugared properties.
14569 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14570 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14571
14572 // If this is an ArrayType, the element qualifiers are interchangeable with
14573 // the top level qualifiers.
14574 // * In case the canonical nodes are the same, the elements types are already
14575 // the same.
14576 // * Otherwise, the element types will be made the same, and any different
14577 // element qualifiers will be moved up to the top level qualifiers, per
14578 // 'getCommonArrayElementType'.
14579 // In both cases, this means there may be top level qualifiers which differ
14580 // between X and Y. If so, these differing qualifiers are redundant with the
14581 // element qualifiers, and can be removed without changing the canonical type.
14582 // The desired behaviour is the same as for the 'Unqualified' case here:
14583 // treat the redundant qualifiers as sugar, remove the ones which are not
14584 // common to both sides.
14585 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14586
14587 if (SX.Ty != SY.Ty) {
14588 // The canonical nodes differ. Build a common canonical node out of the two,
14589 // unifying their sugar. This may recurse back here.
14590 SX.Ty =
14591 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14592 } else {
14593 // The canonical nodes were identical: We may have desugared too much.
14594 // Add any common sugar back in.
14595 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14596 QX -= SX.Quals;
14597 QY -= SY.Quals;
14598 SX = Xs.pop_back_val();
14599 SY = Ys.pop_back_val();
14600 }
14601 }
14602 if (KeepCommonQualifiers)
14604 else
14605 assert(QX == QY);
14606
14607 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14608 // related. Walk up these nodes, unifying them and adding the result.
14609 while (!Xs.empty() && !Ys.empty()) {
14610 auto Underlying = SplitQualType(
14611 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14612 SX = Xs.pop_back_val();
14613 SY = Ys.pop_back_val();
14614 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14616 // Stop at the first pair which is unrelated.
14617 if (!SX.Ty) {
14618 SX.Ty = Underlying.Ty;
14619 break;
14620 }
14621 QX -= Underlying.Quals;
14622 };
14623
14624 // Add back the missing accumulated qualifiers, which were stripped off
14625 // with the sugar nodes we could not unify.
14626 QualType R = getQualifiedType(SX.Ty, QX);
14627 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14628 return R;
14629}
14630
14632 assert(Ty->isFixedPointType());
14633
14635 return Ty;
14636
14637 switch (Ty->castAs<BuiltinType>()->getKind()) {
14638 default:
14639 llvm_unreachable("Not a saturated fixed point type!");
14640 case BuiltinType::SatShortAccum:
14641 return ShortAccumTy;
14642 case BuiltinType::SatAccum:
14643 return AccumTy;
14644 case BuiltinType::SatLongAccum:
14645 return LongAccumTy;
14646 case BuiltinType::SatUShortAccum:
14647 return UnsignedShortAccumTy;
14648 case BuiltinType::SatUAccum:
14649 return UnsignedAccumTy;
14650 case BuiltinType::SatULongAccum:
14651 return UnsignedLongAccumTy;
14652 case BuiltinType::SatShortFract:
14653 return ShortFractTy;
14654 case BuiltinType::SatFract:
14655 return FractTy;
14656 case BuiltinType::SatLongFract:
14657 return LongFractTy;
14658 case BuiltinType::SatUShortFract:
14659 return UnsignedShortFractTy;
14660 case BuiltinType::SatUFract:
14661 return UnsignedFractTy;
14662 case BuiltinType::SatULongFract:
14663 return UnsignedLongFractTy;
14664 }
14665}
14666
14668 assert(Ty->isFixedPointType());
14669
14670 if (Ty->isSaturatedFixedPointType()) return Ty;
14671
14672 switch (Ty->castAs<BuiltinType>()->getKind()) {
14673 default:
14674 llvm_unreachable("Not a fixed point type!");
14675 case BuiltinType::ShortAccum:
14676 return SatShortAccumTy;
14677 case BuiltinType::Accum:
14678 return SatAccumTy;
14679 case BuiltinType::LongAccum:
14680 return SatLongAccumTy;
14681 case BuiltinType::UShortAccum:
14683 case BuiltinType::UAccum:
14684 return SatUnsignedAccumTy;
14685 case BuiltinType::ULongAccum:
14687 case BuiltinType::ShortFract:
14688 return SatShortFractTy;
14689 case BuiltinType::Fract:
14690 return SatFractTy;
14691 case BuiltinType::LongFract:
14692 return SatLongFractTy;
14693 case BuiltinType::UShortFract:
14695 case BuiltinType::UFract:
14696 return SatUnsignedFractTy;
14697 case BuiltinType::ULongFract:
14699 }
14700}
14701
14703 if (LangOpts.OpenCL)
14705
14706 if (LangOpts.CUDA)
14708
14709 return getLangASFromTargetAS(AS);
14710}
14711
14712// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14713// doesn't include ASTContext.h
14714template
14716 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14718 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14719 const clang::ASTContext &Ctx, Decl *Value);
14720
14722 assert(Ty->isFixedPointType());
14723
14724 const TargetInfo &Target = getTargetInfo();
14725 switch (Ty->castAs<BuiltinType>()->getKind()) {
14726 default:
14727 llvm_unreachable("Not a fixed point type!");
14728 case BuiltinType::ShortAccum:
14729 case BuiltinType::SatShortAccum:
14730 return Target.getShortAccumScale();
14731 case BuiltinType::Accum:
14732 case BuiltinType::SatAccum:
14733 return Target.getAccumScale();
14734 case BuiltinType::LongAccum:
14735 case BuiltinType::SatLongAccum:
14736 return Target.getLongAccumScale();
14737 case BuiltinType::UShortAccum:
14738 case BuiltinType::SatUShortAccum:
14739 return Target.getUnsignedShortAccumScale();
14740 case BuiltinType::UAccum:
14741 case BuiltinType::SatUAccum:
14742 return Target.getUnsignedAccumScale();
14743 case BuiltinType::ULongAccum:
14744 case BuiltinType::SatULongAccum:
14745 return Target.getUnsignedLongAccumScale();
14746 case BuiltinType::ShortFract:
14747 case BuiltinType::SatShortFract:
14748 return Target.getShortFractScale();
14749 case BuiltinType::Fract:
14750 case BuiltinType::SatFract:
14751 return Target.getFractScale();
14752 case BuiltinType::LongFract:
14753 case BuiltinType::SatLongFract:
14754 return Target.getLongFractScale();
14755 case BuiltinType::UShortFract:
14756 case BuiltinType::SatUShortFract:
14757 return Target.getUnsignedShortFractScale();
14758 case BuiltinType::UFract:
14759 case BuiltinType::SatUFract:
14760 return Target.getUnsignedFractScale();
14761 case BuiltinType::ULongFract:
14762 case BuiltinType::SatULongFract:
14763 return Target.getUnsignedLongFractScale();
14764 }
14765}
14766
14768 assert(Ty->isFixedPointType());
14769
14770 const TargetInfo &Target = getTargetInfo();
14771 switch (Ty->castAs<BuiltinType>()->getKind()) {
14772 default:
14773 llvm_unreachable("Not a fixed point type!");
14774 case BuiltinType::ShortAccum:
14775 case BuiltinType::SatShortAccum:
14776 return Target.getShortAccumIBits();
14777 case BuiltinType::Accum:
14778 case BuiltinType::SatAccum:
14779 return Target.getAccumIBits();
14780 case BuiltinType::LongAccum:
14781 case BuiltinType::SatLongAccum:
14782 return Target.getLongAccumIBits();
14783 case BuiltinType::UShortAccum:
14784 case BuiltinType::SatUShortAccum:
14785 return Target.getUnsignedShortAccumIBits();
14786 case BuiltinType::UAccum:
14787 case BuiltinType::SatUAccum:
14788 return Target.getUnsignedAccumIBits();
14789 case BuiltinType::ULongAccum:
14790 case BuiltinType::SatULongAccum:
14791 return Target.getUnsignedLongAccumIBits();
14792 case BuiltinType::ShortFract:
14793 case BuiltinType::SatShortFract:
14794 case BuiltinType::Fract:
14795 case BuiltinType::SatFract:
14796 case BuiltinType::LongFract:
14797 case BuiltinType::SatLongFract:
14798 case BuiltinType::UShortFract:
14799 case BuiltinType::SatUShortFract:
14800 case BuiltinType::UFract:
14801 case BuiltinType::SatUFract:
14802 case BuiltinType::ULongFract:
14803 case BuiltinType::SatULongFract:
14804 return 0;
14805 }
14806}
14807
14808llvm::FixedPointSemantics
14810 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14811 "Can only get the fixed point semantics for a "
14812 "fixed point or integer type.");
14813 if (Ty->isIntegerType())
14814 return llvm::FixedPointSemantics::GetIntegerSemantics(
14815 getIntWidth(Ty), Ty->isSignedIntegerType());
14816
14817 bool isSigned = Ty->isSignedFixedPointType();
14818 return llvm::FixedPointSemantics(
14819 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14821 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14822}
14823
14824llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14825 assert(Ty->isFixedPointType());
14826 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14827}
14828
14829llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14830 assert(Ty->isFixedPointType());
14831 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14832}
14833
14835 assert(Ty->isUnsignedFixedPointType() &&
14836 "Expected unsigned fixed point type");
14837
14838 switch (Ty->castAs<BuiltinType>()->getKind()) {
14839 case BuiltinType::UShortAccum:
14840 return ShortAccumTy;
14841 case BuiltinType::UAccum:
14842 return AccumTy;
14843 case BuiltinType::ULongAccum:
14844 return LongAccumTy;
14845 case BuiltinType::SatUShortAccum:
14846 return SatShortAccumTy;
14847 case BuiltinType::SatUAccum:
14848 return SatAccumTy;
14849 case BuiltinType::SatULongAccum:
14850 return SatLongAccumTy;
14851 case BuiltinType::UShortFract:
14852 return ShortFractTy;
14853 case BuiltinType::UFract:
14854 return FractTy;
14855 case BuiltinType::ULongFract:
14856 return LongFractTy;
14857 case BuiltinType::SatUShortFract:
14858 return SatShortFractTy;
14859 case BuiltinType::SatUFract:
14860 return SatFractTy;
14861 case BuiltinType::SatULongFract:
14862 return SatLongFractTy;
14863 default:
14864 llvm_unreachable("Unexpected unsigned fixed point type");
14865 }
14866}
14867
14868// Given a list of FMV features, return a concatenated list of the
14869// corresponding backend features (which may contain duplicates).
14870static std::vector<std::string> getFMVBackendFeaturesFor(
14871 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14872 std::vector<std::string> BackendFeats;
14873 llvm::AArch64::ExtensionSet FeatureBits;
14874 for (StringRef F : FMVFeatStrings)
14875 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14876 if (FMVExt->ID)
14877 FeatureBits.enable(*FMVExt->ID);
14878 FeatureBits.toLLVMFeatureList(BackendFeats);
14879 return BackendFeats;
14880}
14881
14882ParsedTargetAttr
14883ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14884 assert(TD != nullptr);
14885 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14886
14887 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14888 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14889 });
14890 return ParsedAttr;
14891}
14892
14893void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14894 const FunctionDecl *FD) const {
14895 if (FD)
14896 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14897 else
14898 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14899 Target->getTargetOpts().CPU,
14900 Target->getTargetOpts().Features);
14901}
14902
14903// Fills in the supplied string map with the set of target features for the
14904// passed in function.
14905void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14906 GlobalDecl GD) const {
14907 StringRef TargetCPU = Target->getTargetOpts().CPU;
14908 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14909 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14911
14912 // Make a copy of the features as passed on the command line into the
14913 // beginning of the additional features from the function to override.
14914 // AArch64 handles command line option features in parseTargetAttr().
14915 if (!Target->getTriple().isAArch64())
14916 ParsedAttr.Features.insert(
14917 ParsedAttr.Features.begin(),
14918 Target->getTargetOpts().FeaturesAsWritten.begin(),
14919 Target->getTargetOpts().FeaturesAsWritten.end());
14920
14921 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14922 TargetCPU = ParsedAttr.CPU;
14923
14924 // Now populate the feature map, first with the TargetCPU which is either
14925 // the default or a new one from the target attribute string. Then we'll use
14926 // the passed in features (FeaturesAsWritten) along with the new ones from
14927 // the attribute.
14928 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14929 ParsedAttr.Features);
14930 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14932 Target->getCPUSpecificCPUDispatchFeatures(
14933 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14934 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14935 Features.insert(Features.begin(),
14936 Target->getTargetOpts().FeaturesAsWritten.begin(),
14937 Target->getTargetOpts().FeaturesAsWritten.end());
14938 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14939 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14940 if (Target->getTriple().isAArch64()) {
14942 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14943 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14944 Features.insert(Features.begin(),
14945 Target->getTargetOpts().FeaturesAsWritten.begin(),
14946 Target->getTargetOpts().FeaturesAsWritten.end());
14947 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14948 } else if (Target->getTriple().isRISCV()) {
14949 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14950 std::vector<std::string> Features;
14951 if (VersionStr != "default") {
14952 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14953 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14954 ParsedAttr.Features.end());
14955 }
14956 Features.insert(Features.begin(),
14957 Target->getTargetOpts().FeaturesAsWritten.begin(),
14958 Target->getTargetOpts().FeaturesAsWritten.end());
14959 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14960 } else {
14961 std::vector<std::string> Features;
14962 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14963 if (VersionStr.starts_with("arch="))
14964 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14965 else if (VersionStr != "default")
14966 Features.push_back((StringRef{"+"} + VersionStr).str());
14967 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14968 }
14969 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14970 std::vector<std::string> Features;
14971 if (Target->getTriple().isRISCV()) {
14972 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14973 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14974 ParsedAttr.Features.end());
14975 } else {
14976 assert(Target->getTriple().isAArch64());
14978 TV->getFeatures(Feats);
14979 Features = getFMVBackendFeaturesFor(Feats);
14980 }
14981 Features.insert(Features.begin(),
14982 Target->getTargetOpts().FeaturesAsWritten.begin(),
14983 Target->getTargetOpts().FeaturesAsWritten.end());
14984 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14985 } else {
14986 FeatureMap = Target->getTargetOpts().FeatureMap;
14987 }
14988}
14989
14991 CanQualType KernelNameType,
14992 const FunctionDecl *FD) {
14993 // Host and device compilation may use different ABIs and different ABIs
14994 // may allocate name mangling discriminators differently. A discriminator
14995 // override is used to ensure consistent discriminator allocation across
14996 // host and device compilation.
14997 auto DeviceDiscriminatorOverrider =
14998 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
14999 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15000 if (RD->isLambda())
15001 return RD->getDeviceLambdaManglingNumber();
15002 return std::nullopt;
15003 };
15004 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15005 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15006
15007 // Construct a mangled name for the SYCL kernel caller offload entry point.
15008 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15009 // name the SYCL kernel caller offload entry point function. This mangling
15010 // does not suffice to clearly identify symbols that correspond to SYCL
15011 // kernel caller functions, nor is this mangling natural for targets that
15012 // use a non-Itanium ABI.
15013 std::string Buffer;
15014 Buffer.reserve(128);
15015 llvm::raw_string_ostream Out(Buffer);
15016 MC->mangleCanonicalTypeName(KernelNameType, Out);
15017 std::string KernelName = Out.str();
15018
15019 return {KernelNameType, FD, KernelName};
15020}
15021
15023 // If the function declaration to register is invalid or dependent, the
15024 // registration attempt is ignored.
15025 if (FD->isInvalidDecl() || FD->isTemplated())
15026 return;
15027
15028 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15029 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15030
15031 // Be tolerant of multiple registration attempts so long as each attempt
15032 // is for the same entity. Callers are obligated to detect and diagnose
15033 // conflicting kernel names prior to calling this function.
15034 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15035 auto IT = SYCLKernels.find(KernelNameType);
15036 assert((IT == SYCLKernels.end() ||
15037 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15038 "SYCL kernel name conflict");
15039 (void)IT;
15040 SYCLKernels.insert(std::make_pair(
15041 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15042}
15043
15045 CanQualType KernelNameType = getCanonicalType(T);
15046 return SYCLKernels.at(KernelNameType);
15047}
15048
15050 CanQualType KernelNameType = getCanonicalType(T);
15051 auto IT = SYCLKernels.find(KernelNameType);
15052 if (IT != SYCLKernels.end())
15053 return &IT->second;
15054 return nullptr;
15055}
15056
15058 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15059 return *OMPTraitInfoVector.back();
15060}
15061
15064 const ASTContext::SectionInfo &Section) {
15065 if (Section.Decl)
15066 return DB << Section.Decl;
15067 return DB << "a prior #pragma section";
15068}
15069
15070bool ASTContext::mayExternalize(const Decl *D) const {
15071 bool IsInternalVar =
15072 isa<VarDecl>(D) &&
15074 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15075 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15076 (D->hasAttr<CUDAConstantAttr>() &&
15077 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15078 // CUDA/HIP: managed variables need to be externalized since it is
15079 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15080 // anonymous name space needs to be externalized to avoid duplicate symbols.
15081 return (IsInternalVar &&
15082 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15083 (D->hasAttr<CUDAGlobalAttr>() &&
15085 GVA_Internal);
15086}
15087
15089 return mayExternalize(D) &&
15090 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15092}
15093
15094StringRef ASTContext::getCUIDHash() const {
15095 if (!CUIDHash.empty())
15096 return CUIDHash;
15097 if (LangOpts.CUID.empty())
15098 return StringRef();
15099 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15100 return CUIDHash;
15101}
15102
15103const CXXRecordDecl *
15105 assert(ThisClass);
15106 assert(ThisClass->isPolymorphic());
15107 const CXXRecordDecl *PrimaryBase = ThisClass;
15108 while (1) {
15109 assert(PrimaryBase);
15110 assert(PrimaryBase->isPolymorphic());
15111 auto &Layout = getASTRecordLayout(PrimaryBase);
15112 auto Base = Layout.getPrimaryBase();
15113 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15114 break;
15115 PrimaryBase = Base;
15116 }
15117 return PrimaryBase;
15118}
15119
15121 StringRef MangledName) {
15122 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15123 assert(Method->isVirtual());
15124 bool DefaultIncludesPointerAuth =
15125 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15126
15127 if (!DefaultIncludesPointerAuth)
15128 return true;
15129
15130 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15131 if (Existing != ThunksToBeAbbreviated.end())
15132 return Existing->second.contains(MangledName.str());
15133
15134 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15135 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15136 auto VtableContext = getVTableContext();
15137 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15138 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15139 for (const auto &Thunk : *ThunkInfos) {
15140 SmallString<256> ElidedName;
15141 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15142 if (Destructor)
15143 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15144 Thunk, /* elideOverrideInfo */ true,
15145 ElidedNameStream);
15146 else
15147 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15148 ElidedNameStream);
15149 SmallString<256> MangledName;
15150 llvm::raw_svector_ostream mangledNameStream(MangledName);
15151 if (Destructor)
15152 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15153 Thunk, /* elideOverrideInfo */ false,
15154 mangledNameStream);
15155 else
15156 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15157 mangledNameStream);
15158
15159 Thunks[ElidedName].push_back(std::string(MangledName));
15160 }
15161 }
15162 llvm::StringSet<> SimplifiedThunkNames;
15163 for (auto &ThunkList : Thunks) {
15164 llvm::sort(ThunkList.second);
15165 SimplifiedThunkNames.insert(ThunkList.second[0]);
15166 }
15167 bool Result = SimplifiedThunkNames.contains(MangledName);
15168 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15169 return Result;
15170}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static std::string charUnitsToString(const CharUnits &CU)
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static SmallVector< SourceLocation, 2 > getDeclLocsForCommentSearch(const Decl *D, SourceManager &SourceMgr)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:419
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:188
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:953
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:741
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:742
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:737
Builtin::Context & BuiltinInfo
Definition ASTContext.h:739
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:891
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:738
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:924
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:520
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:740
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:927
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:189
void PrintStats() const
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:743
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:790
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:512
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:933
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:811
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:856
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:949
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:940
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:3508
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:3890
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3738
QualType getElementType() const
Definition TypeBase.h:3732
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3742
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:8089
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8137
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8154
unsigned getNumBits() const
Definition TypeBase.h:8149
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4651
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Pointer to a block type.
Definition TypeBase.h:3540
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3557
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
Declaration of a class template.
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h: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:205
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:199
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3854
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3873
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4371
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4409
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4400
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:3523
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:779
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4059
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4081
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8182
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4009
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4038
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4099
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4124
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4430
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4450
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:6209
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6214
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4225
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4250
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:904
Represents an enum.
Definition Decl.h:4004
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4213
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4111
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp: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:4265
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:246
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5420
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3242
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4641
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3832
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2409
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition Decl.cpp:4019
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5232
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:5064
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5098
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4842
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4858
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
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:5577
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5737
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5733
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4571
CallingConv getCC() const
Definition TypeBase.h:4630
unsigned getRegParm() const
Definition TypeBase.h:4623
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4619
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4486
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4526
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
QualType getReturnType() const
Definition TypeBase.h:4800
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:5032
Represents a C array with an unspecified size.
Definition TypeBase.h:3907
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3924
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:3615
@ 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:6143
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:4349
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4356
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3651
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3694
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:316
bool isExternallyVisible() const
Definition Decl.h:432
Represent a C++ namespace.
Definition Decl.h:591
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp: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:7847
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:7903
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7984
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:7978
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8060
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7940
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7961
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7915
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7955
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:8022
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7967
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:838
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition DeclObjC.cpp:176
bool isOptional() const
Definition DeclObjC.h:916
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:873
Selector getSetterName() const
Definition DeclObjC.h:893
QualType getType() const
Definition DeclObjC.h:804
Selector getGetterName() const
Definition DeclObjC.h:885
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2805
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2879
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
protocol_range protocols() const
Definition DeclObjC.h:2161
bool isGNUFamily() const
Is this runtime basically of the GNU family of runtimes?
Represents the declaration of an Objective-C type parameter.
Definition DeclObjC.h:578
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:623
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:662
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4357
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3302
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3316
void clear()
Clear parent maps.
Represents a parameter to a function.
Definition Decl.h:1789
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1853
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8120
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:8196
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:8369
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:8416
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
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:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8306
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
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:8342
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8289
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:8317
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:8225
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8232
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:3633
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition Decl.h:4309
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5125
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_range fields() const
Definition Decl.h:4512
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5111
RecordDecl * getMostRecentDecl()
Definition Decl.h:4335
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5170
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
bool field_empty() const
Definition Decl.h:4520
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3571
QualType getPointeeType() const
Definition TypeBase.h:3589
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3597
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:3714
TagTypeKind TagKind
Definition Decl.h:3719
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3945
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4840
bool isUnion() const
Definition Decl.h:3919
TagKind getTagKind() const
Definition Decl.h:3908
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition TargetInfo.h:323
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:853
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:746
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:330
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:339
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:344
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:353
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:335
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:348
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:502
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:404
IntType getSizeType() const
Definition TargetInfo.h:385
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:970
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:754
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:386
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:240
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
ConceptReference * getConceptReference() const
Definition ASTConcept.h:244
Represents a declaration of a type.
Definition Decl.h:3510
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition TypeLoc.cpp:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:216
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6175
A container of type source information.
Definition TypeBase.h:8256
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:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isObjCBuiltinType() const
Definition TypeBase.h:8742
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:8629
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:8625
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:8621
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8522
bool isArrayParameterType() const
Definition TypeBase.h:8637
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
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:8962
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8712
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:8996
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:8787
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
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:8934
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8950
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:8724
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8958
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
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:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
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:8976
bool isVectorType() const
Definition TypeBase.h:8661
bool isObjCClassType() const
Definition TypeBase.h:8730
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:8530
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:9098
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:8915
bool isRecordType() const
Definition TypeBase.h:8649
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:3664
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5633
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
QualType getUnderlyingType() const
Definition Decl.h:3614
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6119
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:5980
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6017
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:6057
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
void clear()
Definition Value.cpp:216
Represents a variable declaration or definition.
Definition Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2810
bool hasInit() const
Definition Decl.cpp:2398
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition Decl.cpp:2461
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1207
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4197
VectorKind getVectorKind() const
Definition TypeBase.h:4193
QualType getElementType() const
Definition TypeBase.h:4187
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:8420
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
@ AS_public
Definition Specifiers.h:124
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:257
@ SC_Static
Definition Specifiers.h:252
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ TypeAlignment
Definition TypeBase.h:76
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3717
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:5893
@ Struct
The "struct" keyword.
Definition TypeBase.h:5890
@ Class
The "class" keyword.
Definition TypeBase.h:5899
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
FloatModeKind
Definition TargetInfo.h:75
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:287
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:555
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:563
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:559
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4143
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4152
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4140
@ Generic
not a target-specific vector type
Definition TypeBase.h:4134
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4158
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4161
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4155
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:144
@ None
The alignment was not explicit in code.
Definition ASTContext.h:146
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:155
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:149
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:152
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5863
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5868
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5865
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5874
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5871
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5881
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:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h: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:5321
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5323
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5326
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5329
Extra information about a function prototype.
Definition TypeBase.h:5349
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5395
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5354
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5399
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5388
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:175
bool isAlignRequired()
Definition ASTContext.h:167
AlignRequirementKind AlignRequirement
Definition ASTContext.h:161
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986