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 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4571 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4572 return It->second;
4573
4574 if (Target->hasAArch64ACLETypes()) {
4575 uint64_t EltTySize = getTypeSize(EltTy);
4576
4577#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4578 ElBits, NF, IsSigned) \
4579 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4580 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4581 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4582 return ScalableVecTyMap[K] = SingletonId; \
4583 }
4584#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4585 ElBits, NF) \
4586 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4587 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4588 return ScalableVecTyMap[K] = SingletonId; \
4589 }
4590#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4591 ElBits, NF) \
4592 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4593 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4594 return ScalableVecTyMap[K] = SingletonId; \
4595 }
4596#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4597 ElBits, NF) \
4598 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4599 NumElts == (NumEls * NF) && NumFields == 1) { \
4600 return ScalableVecTyMap[K] = SingletonId; \
4601 }
4602#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4603 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4604 return ScalableVecTyMap[K] = SingletonId;
4605#include "clang/Basic/AArch64ACLETypes.def"
4606 } else if (Target->hasRISCVVTypes()) {
4607 uint64_t EltTySize = getTypeSize(EltTy);
4608#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4609 IsFP, IsBF) \
4610 if (!EltTy->isBooleanType() && \
4611 ((EltTy->hasIntegerRepresentation() && \
4612 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4613 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4614 IsFP && !IsBF) || \
4615 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4616 IsBF && !IsFP)) && \
4617 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4618 return ScalableVecTyMap[K] = SingletonId;
4619#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4620 if (EltTy->isBooleanType() && NumElts == NumEls) \
4621 return ScalableVecTyMap[K] = SingletonId;
4622#include "clang/Basic/RISCVVTypes.def"
4623 }
4624 return QualType();
4625}
4626
4627/// getVectorType - Return the unique reference to a vector type of
4628/// the specified element type and size. VectorType must be a built-in type.
4630 VectorKind VecKind) const {
4631 assert(vecType->isBuiltinType() ||
4632 (vecType->isBitIntType() &&
4633 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4634 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4635
4636 // Check if we've already instantiated a vector of this type.
4637 llvm::FoldingSetNodeID ID;
4638 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4639
4640 void *InsertPos = nullptr;
4641 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4642 return QualType(VTP, 0);
4643
4644 // If the element type isn't canonical, this won't be a canonical type either,
4645 // so fill in the canonical type field.
4646 QualType Canonical;
4647 if (!vecType.isCanonical()) {
4648 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4649
4650 // Get the new insert position for the node we care about.
4651 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4652 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4653 }
4654 auto *New = new (*this, alignof(VectorType))
4655 VectorType(vecType, NumElts, Canonical, VecKind);
4656 VectorTypes.InsertNode(New, InsertPos);
4657 Types.push_back(New);
4658 return QualType(New, 0);
4659}
4660
4662 SourceLocation AttrLoc,
4663 VectorKind VecKind) const {
4664 llvm::FoldingSetNodeID ID;
4665 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4666 VecKind);
4667 void *InsertPos = nullptr;
4668 DependentVectorType *Canon =
4669 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4671
4672 if (Canon) {
4673 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4674 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4675 } else {
4676 QualType CanonVecTy = getCanonicalType(VecType);
4677 if (CanonVecTy == VecType) {
4678 New = new (*this, alignof(DependentVectorType))
4679 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4680
4681 DependentVectorType *CanonCheck =
4682 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4683 assert(!CanonCheck &&
4684 "Dependent-sized vector_size canonical type broken");
4685 (void)CanonCheck;
4686 DependentVectorTypes.InsertNode(New, InsertPos);
4687 } else {
4688 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4689 SourceLocation(), VecKind);
4690 New = new (*this, alignof(DependentVectorType))
4691 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4692 }
4693 }
4694
4695 Types.push_back(New);
4696 return QualType(New, 0);
4697}
4698
4699/// getExtVectorType - Return the unique reference to an extended vector type of
4700/// the specified element type and size. VectorType must be a built-in type.
4702 unsigned NumElts) const {
4703 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4704 (vecType->isBitIntType() &&
4705 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4706 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4707
4708 // Check if we've already instantiated a vector of this type.
4709 llvm::FoldingSetNodeID ID;
4710 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4712 void *InsertPos = nullptr;
4713 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4714 return QualType(VTP, 0);
4715
4716 // If the element type isn't canonical, this won't be a canonical type either,
4717 // so fill in the canonical type field.
4718 QualType Canonical;
4719 if (!vecType.isCanonical()) {
4720 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4721
4722 // Get the new insert position for the node we care about.
4723 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4724 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4725 }
4726 auto *New = new (*this, alignof(ExtVectorType))
4727 ExtVectorType(vecType, NumElts, Canonical);
4728 VectorTypes.InsertNode(New, InsertPos);
4729 Types.push_back(New);
4730 return QualType(New, 0);
4731}
4732
4735 Expr *SizeExpr,
4736 SourceLocation AttrLoc) const {
4737 llvm::FoldingSetNodeID ID;
4739 SizeExpr);
4740
4741 void *InsertPos = nullptr;
4743 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4745 if (Canon) {
4746 // We already have a canonical version of this array type; use it as
4747 // the canonical type for a newly-built type.
4748 New = new (*this, alignof(DependentSizedExtVectorType))
4749 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4750 AttrLoc);
4751 } else {
4752 QualType CanonVecTy = getCanonicalType(vecType);
4753 if (CanonVecTy == vecType) {
4754 New = new (*this, alignof(DependentSizedExtVectorType))
4755 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4756
4757 DependentSizedExtVectorType *CanonCheck
4758 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4759 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4760 (void)CanonCheck;
4761 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4762 } else {
4763 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4764 SourceLocation());
4765 New = new (*this, alignof(DependentSizedExtVectorType))
4766 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4767 }
4768 }
4769
4770 Types.push_back(New);
4771 return QualType(New, 0);
4772}
4773
4775 unsigned NumColumns) const {
4776 llvm::FoldingSetNodeID ID;
4777 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4778 Type::ConstantMatrix);
4779
4780 assert(MatrixType::isValidElementType(ElementTy) &&
4781 "need a valid element type");
4782 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4784 "need valid matrix dimensions");
4785 void *InsertPos = nullptr;
4786 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4787 return QualType(MTP, 0);
4788
4789 QualType Canonical;
4790 if (!ElementTy.isCanonical()) {
4791 Canonical =
4792 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4793
4794 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4795 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4796 (void)NewIP;
4797 }
4798
4799 auto *New = new (*this, alignof(ConstantMatrixType))
4800 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4801 MatrixTypes.InsertNode(New, InsertPos);
4802 Types.push_back(New);
4803 return QualType(New, 0);
4804}
4805
4807 Expr *RowExpr,
4808 Expr *ColumnExpr,
4809 SourceLocation AttrLoc) const {
4810 QualType CanonElementTy = getCanonicalType(ElementTy);
4811 llvm::FoldingSetNodeID ID;
4812 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4813 ColumnExpr);
4814
4815 void *InsertPos = nullptr;
4817 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4818
4819 if (!Canon) {
4820 Canon = new (*this, alignof(DependentSizedMatrixType))
4821 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4822 ColumnExpr, AttrLoc);
4823#ifndef NDEBUG
4824 DependentSizedMatrixType *CanonCheck =
4825 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4826 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4827#endif
4828 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4829 Types.push_back(Canon);
4830 }
4831
4832 // Already have a canonical version of the matrix type
4833 //
4834 // If it exactly matches the requested type, use it directly.
4835 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4836 Canon->getRowExpr() == ColumnExpr)
4837 return QualType(Canon, 0);
4838
4839 // Use Canon as the canonical type for newly-built type.
4841 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4842 ColumnExpr, AttrLoc);
4843 Types.push_back(New);
4844 return QualType(New, 0);
4845}
4846
4848 Expr *AddrSpaceExpr,
4849 SourceLocation AttrLoc) const {
4850 assert(AddrSpaceExpr->isInstantiationDependent());
4851
4852 QualType canonPointeeType = getCanonicalType(PointeeType);
4853
4854 void *insertPos = nullptr;
4855 llvm::FoldingSetNodeID ID;
4856 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4857 AddrSpaceExpr);
4858
4859 DependentAddressSpaceType *canonTy =
4860 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4861
4862 if (!canonTy) {
4863 canonTy = new (*this, alignof(DependentAddressSpaceType))
4864 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4865 AttrLoc);
4866 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4867 Types.push_back(canonTy);
4868 }
4869
4870 if (canonPointeeType == PointeeType &&
4871 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4872 return QualType(canonTy, 0);
4873
4874 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4875 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4876 AddrSpaceExpr, AttrLoc);
4877 Types.push_back(sugaredType);
4878 return QualType(sugaredType, 0);
4879}
4880
4881/// Determine whether \p T is canonical as the result type of a function.
4883 return T.isCanonical() &&
4884 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4885 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4886}
4887
4888/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4889QualType
4891 const FunctionType::ExtInfo &Info) const {
4892 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4893 // functionality creates a function without a prototype regardless of
4894 // language mode (so it makes them even in C++). Once the rewriter has been
4895 // fixed, this assertion can be enabled again.
4896 //assert(!LangOpts.requiresStrictPrototypes() &&
4897 // "strict prototypes are disabled");
4898
4899 // Unique functions, to guarantee there is only one function of a particular
4900 // structure.
4901 llvm::FoldingSetNodeID ID;
4902 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4903
4904 void *InsertPos = nullptr;
4905 if (FunctionNoProtoType *FT =
4906 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4907 return QualType(FT, 0);
4908
4909 QualType Canonical;
4910 if (!isCanonicalResultType(ResultTy)) {
4911 Canonical =
4913
4914 // Get the new insert position for the node we care about.
4915 FunctionNoProtoType *NewIP =
4916 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4917 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4918 }
4919
4920 auto *New = new (*this, alignof(FunctionNoProtoType))
4921 FunctionNoProtoType(ResultTy, Canonical, Info);
4922 Types.push_back(New);
4923 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4924 return QualType(New, 0);
4925}
4926
4929 CanQualType CanResultType = getCanonicalType(ResultType);
4930
4931 // Canonical result types do not have ARC lifetime qualifiers.
4932 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4933 Qualifiers Qs = CanResultType.getQualifiers();
4934 Qs.removeObjCLifetime();
4936 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4937 }
4938
4939 return CanResultType;
4940}
4941
4943 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4944 if (ESI.Type == EST_None)
4945 return true;
4946 if (!NoexceptInType)
4947 return false;
4948
4949 // C++17 onwards: exception specification is part of the type, as a simple
4950 // boolean "can this function type throw".
4951 if (ESI.Type == EST_BasicNoexcept)
4952 return true;
4953
4954 // A noexcept(expr) specification is (possibly) canonical if expr is
4955 // value-dependent.
4956 if (ESI.Type == EST_DependentNoexcept)
4957 return true;
4958
4959 // A dynamic exception specification is canonical if it only contains pack
4960 // expansions (so we can't tell whether it's non-throwing) and all its
4961 // contained types are canonical.
4962 if (ESI.Type == EST_Dynamic) {
4963 bool AnyPackExpansions = false;
4964 for (QualType ET : ESI.Exceptions) {
4965 if (!ET.isCanonical())
4966 return false;
4967 if (ET->getAs<PackExpansionType>())
4968 AnyPackExpansions = true;
4969 }
4970 return AnyPackExpansions;
4971 }
4972
4973 return false;
4974}
4975
4976QualType ASTContext::getFunctionTypeInternal(
4977 QualType ResultTy, ArrayRef<QualType> ArgArray,
4978 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4979 size_t NumArgs = ArgArray.size();
4980
4981 // Unique functions, to guarantee there is only one function of a particular
4982 // structure.
4983 llvm::FoldingSetNodeID ID;
4984 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4985 *this, true);
4986
4987 QualType Canonical;
4988 bool Unique = false;
4989
4990 void *InsertPos = nullptr;
4991 if (FunctionProtoType *FPT =
4992 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4993 QualType Existing = QualType(FPT, 0);
4994
4995 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4996 // it so long as our exception specification doesn't contain a dependent
4997 // noexcept expression, or we're just looking for a canonical type.
4998 // Otherwise, we're going to need to create a type
4999 // sugar node to hold the concrete expression.
5000 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5001 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5002 return Existing;
5003
5004 // We need a new type sugar node for this one, to hold the new noexcept
5005 // expression. We do no canonicalization here, but that's OK since we don't
5006 // expect to see the same noexcept expression much more than once.
5007 Canonical = getCanonicalType(Existing);
5008 Unique = true;
5009 }
5010
5011 bool NoexceptInType = getLangOpts().CPlusPlus17;
5012 bool IsCanonicalExceptionSpec =
5014
5015 // Determine whether the type being created is already canonical or not.
5016 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5017 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5018 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5019 if (!ArgArray[i].isCanonicalAsParam())
5020 isCanonical = false;
5021
5022 if (OnlyWantCanonical)
5023 assert(isCanonical &&
5024 "given non-canonical parameters constructing canonical type");
5025
5026 // If this type isn't canonical, get the canonical version of it if we don't
5027 // already have it. The exception spec is only partially part of the
5028 // canonical type, and only in C++17 onwards.
5029 if (!isCanonical && Canonical.isNull()) {
5030 SmallVector<QualType, 16> CanonicalArgs;
5031 CanonicalArgs.reserve(NumArgs);
5032 for (unsigned i = 0; i != NumArgs; ++i)
5033 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5034
5035 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5036 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5037 CanonicalEPI.HasTrailingReturn = false;
5038
5039 if (IsCanonicalExceptionSpec) {
5040 // Exception spec is already OK.
5041 } else if (NoexceptInType) {
5042 switch (EPI.ExceptionSpec.Type) {
5044 // We don't know yet. It shouldn't matter what we pick here; no-one
5045 // should ever look at this.
5046 [[fallthrough]];
5047 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5048 CanonicalEPI.ExceptionSpec.Type = EST_None;
5049 break;
5050
5051 // A dynamic exception specification is almost always "not noexcept",
5052 // with the exception that a pack expansion might expand to no types.
5053 case EST_Dynamic: {
5054 bool AnyPacks = false;
5055 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5056 if (ET->getAs<PackExpansionType>())
5057 AnyPacks = true;
5058 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5059 }
5060 if (!AnyPacks)
5061 CanonicalEPI.ExceptionSpec.Type = EST_None;
5062 else {
5063 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5064 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5065 }
5066 break;
5067 }
5068
5069 case EST_DynamicNone:
5070 case EST_BasicNoexcept:
5071 case EST_NoexceptTrue:
5072 case EST_NoThrow:
5073 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5074 break;
5075
5077 llvm_unreachable("dependent noexcept is already canonical");
5078 }
5079 } else {
5080 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5081 }
5082
5083 // Adjust the canonical function result type.
5084 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5085 Canonical =
5086 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5087
5088 // Get the new insert position for the node we care about.
5089 FunctionProtoType *NewIP =
5090 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5091 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5092 }
5093
5094 // Compute the needed size to hold this FunctionProtoType and the
5095 // various trailing objects.
5096 auto ESH = FunctionProtoType::getExceptionSpecSize(
5097 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5098 size_t Size = FunctionProtoType::totalSizeToAlloc<
5099 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5100 FunctionType::FunctionTypeExtraAttributeInfo,
5101 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5102 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5103 FunctionEffect, EffectConditionExpr>(
5106 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5107 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5108 EPI.ExtParameterInfos ? NumArgs : 0,
5110 EPI.FunctionEffects.conditions().size());
5111
5112 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5113 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5114 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5115 Types.push_back(FTP);
5116 if (!Unique)
5117 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5118 if (!EPI.FunctionEffects.empty())
5119 AnyFunctionEffects = true;
5120 return QualType(FTP, 0);
5121}
5122
5123QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5124 llvm::FoldingSetNodeID ID;
5125 PipeType::Profile(ID, T, ReadOnly);
5126
5127 void *InsertPos = nullptr;
5128 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5129 return QualType(PT, 0);
5130
5131 // If the pipe element type isn't canonical, this won't be a canonical type
5132 // either, so fill in the canonical type field.
5133 QualType Canonical;
5134 if (!T.isCanonical()) {
5135 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5136
5137 // Get the new insert position for the node we care about.
5138 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5139 assert(!NewIP && "Shouldn't be in the map!");
5140 (void)NewIP;
5141 }
5142 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5143 Types.push_back(New);
5144 PipeTypes.InsertNode(New, InsertPos);
5145 return QualType(New, 0);
5146}
5147
5149 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5150 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5151 : Ty;
5152}
5153
5155 return getPipeType(T, true);
5156}
5157
5159 return getPipeType(T, false);
5160}
5161
5162QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5163 llvm::FoldingSetNodeID ID;
5164 BitIntType::Profile(ID, IsUnsigned, NumBits);
5165
5166 void *InsertPos = nullptr;
5167 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5168 return QualType(EIT, 0);
5169
5170 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5171 BitIntTypes.InsertNode(New, InsertPos);
5172 Types.push_back(New);
5173 return QualType(New, 0);
5174}
5175
5177 Expr *NumBitsExpr) const {
5178 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5179 llvm::FoldingSetNodeID ID;
5180 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5181
5182 void *InsertPos = nullptr;
5183 if (DependentBitIntType *Existing =
5184 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5185 return QualType(Existing, 0);
5186
5187 auto *New = new (*this, alignof(DependentBitIntType))
5188 DependentBitIntType(IsUnsigned, NumBitsExpr);
5189 DependentBitIntTypes.InsertNode(New, InsertPos);
5190
5191 Types.push_back(New);
5192 return QualType(New, 0);
5193}
5194
5197 using Kind = PredefinedSugarType::Kind;
5198
5199 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5200 Target != nullptr)
5201 return QualType(Target, 0);
5202
5203 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5204 switch (KDI) {
5205 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5206 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5207 // are part of the core language and are widely used. Using
5208 // PredefinedSugarType makes these types as named sugar types rather than
5209 // standard integer types, enabling better hints and diagnostics.
5210 case Kind::SizeT:
5211 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5212 case Kind::SignedSizeT:
5213 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5214 case Kind::PtrdiffT:
5215 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5216 }
5217 llvm_unreachable("unexpected kind");
5218 };
5219 auto *New = new (*this, alignof(PredefinedSugarType))
5220 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5221 getCanonicalType(*this, static_cast<Kind>(KD)));
5222 Types.push_back(New);
5223 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5224 return QualType(New, 0);
5225}
5226
5228 NestedNameSpecifier Qualifier,
5229 const TypeDecl *Decl) const {
5230 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5231 return getTagType(Keyword, Qualifier, Tag,
5232 /*OwnsTag=*/false);
5233 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5234 return getTypedefType(Keyword, Qualifier, Typedef);
5235 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5236 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5237
5239 assert(!Qualifier);
5240 return QualType(Decl->TypeForDecl, 0);
5241}
5242
5244 if (auto *Tag = dyn_cast<TagDecl>(TD))
5245 return getCanonicalTagType(Tag);
5246 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5247 return getCanonicalType(TN->getUnderlyingType());
5248 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5250 assert(TD->TypeForDecl);
5251 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5252}
5253
5255 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5256 return getCanonicalTagType(TD);
5257 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5258 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5260 /*Qualifier=*/std::nullopt, TD);
5261 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5262 return getCanonicalUnresolvedUsingType(Using);
5263
5264 assert(Decl->TypeForDecl);
5265 return QualType(Decl->TypeForDecl, 0);
5266}
5267
5268/// getTypedefType - Return the unique reference to the type for the
5269/// specified typedef name decl.
5272 NestedNameSpecifier Qualifier,
5273 const TypedefNameDecl *Decl, QualType UnderlyingType,
5274 std::optional<bool> TypeMatchesDeclOrNone) const {
5275 if (!TypeMatchesDeclOrNone) {
5276 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5277 assert(!DeclUnderlyingType.isNull());
5278 if (UnderlyingType.isNull())
5279 UnderlyingType = DeclUnderlyingType;
5280 else
5281 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5282 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5283 } else {
5284 // FIXME: This is a workaround for a serialization cycle: assume the decl
5285 // underlying type is not available; don't touch it.
5286 assert(!UnderlyingType.isNull());
5287 }
5288
5289 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5290 *TypeMatchesDeclOrNone) {
5291 if (Decl->TypeForDecl)
5292 return QualType(Decl->TypeForDecl, 0);
5293
5294 auto *NewType = new (*this, alignof(TypedefType))
5295 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5296 !*TypeMatchesDeclOrNone);
5297
5298 Types.push_back(NewType);
5299 Decl->TypeForDecl = NewType;
5300 return QualType(NewType, 0);
5301 }
5302
5303 llvm::FoldingSetNodeID ID;
5304 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5305 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5306
5307 void *InsertPos = nullptr;
5308 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5309 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5310 return QualType(Placeholder->getType(), 0);
5311
5312 void *Mem =
5313 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5315 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5316 alignof(TypedefType));
5317 auto *NewType =
5318 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5319 UnderlyingType, !*TypeMatchesDeclOrNone);
5320 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5322 TypedefTypes.InsertNode(Placeholder, InsertPos);
5323 Types.push_back(NewType);
5324 return QualType(NewType, 0);
5325}
5326
5328 NestedNameSpecifier Qualifier,
5329 const UsingShadowDecl *D,
5330 QualType UnderlyingType) const {
5331 // FIXME: This is expensive to compute every time!
5332 if (UnderlyingType.isNull()) {
5333 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5334 UnderlyingType =
5337 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5338 }
5339
5340 llvm::FoldingSetNodeID ID;
5341 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5342
5343 void *InsertPos = nullptr;
5344 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5345 return QualType(T, 0);
5346
5347 assert(!UnderlyingType.hasLocalQualifiers());
5348
5349 assert(
5351 UnderlyingType));
5352
5353 void *Mem =
5354 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5355 alignof(UsingType));
5356 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5357 Types.push_back(T);
5358 UsingTypes.InsertNode(T, InsertPos);
5359 return QualType(T, 0);
5360}
5361
5362TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5363 NestedNameSpecifier Qualifier,
5364 const TagDecl *TD, bool OwnsTag,
5365 bool IsInjected,
5366 const Type *CanonicalType,
5367 bool WithFoldingSetNode) const {
5368 auto [TC, Size] = [&] {
5369 switch (TD->getDeclKind()) {
5370 case Decl::Enum:
5371 static_assert(alignof(EnumType) == alignof(TagType));
5372 return std::make_tuple(Type::Enum, sizeof(EnumType));
5373 case Decl::ClassTemplatePartialSpecialization:
5374 case Decl::ClassTemplateSpecialization:
5375 case Decl::CXXRecord:
5376 static_assert(alignof(RecordType) == alignof(TagType));
5377 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5378 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5379 return std::make_tuple(Type::InjectedClassName,
5380 sizeof(InjectedClassNameType));
5381 [[fallthrough]];
5382 case Decl::Record:
5383 return std::make_tuple(Type::Record, sizeof(RecordType));
5384 default:
5385 llvm_unreachable("unexpected decl kind");
5386 }
5387 }();
5388
5389 if (Qualifier) {
5390 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5391 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5392 sizeof(NestedNameSpecifier);
5393 }
5394 void *Mem;
5395 if (WithFoldingSetNode) {
5396 // FIXME: It would be more profitable to tail allocate the folding set node
5397 // from the type, instead of the other way around, due to the greater
5398 // alignment requirements of the type. But this makes it harder to deal with
5399 // the different type node sizes. This would require either uniquing from
5400 // different folding sets, or having the folding setaccept a
5401 // contextual parameter which is not fixed at construction.
5402 Mem = Allocate(
5403 sizeof(TagTypeFoldingSetPlaceholder) +
5404 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5405 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5406 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5407 Mem = T->getTagType();
5408 } else {
5409 Mem = Allocate(Size, alignof(TagType));
5410 }
5411
5412 auto *T = [&, TC = TC]() -> TagType * {
5413 switch (TC) {
5414 case Type::Enum: {
5415 assert(isa<EnumDecl>(TD));
5416 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5417 IsInjected, CanonicalType);
5418 assert(reinterpret_cast<void *>(T) ==
5419 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5420 "TagType must be the first base of EnumType");
5421 return T;
5422 }
5423 case Type::Record: {
5424 assert(isa<RecordDecl>(TD));
5425 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5426 IsInjected, CanonicalType);
5427 assert(reinterpret_cast<void *>(T) ==
5428 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5429 "TagType must be the first base of RecordType");
5430 return T;
5431 }
5432 case Type::InjectedClassName: {
5433 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5434 IsInjected, CanonicalType);
5435 assert(reinterpret_cast<void *>(T) ==
5436 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5437 "TagType must be the first base of InjectedClassNameType");
5438 return T;
5439 }
5440 default:
5441 llvm_unreachable("unexpected type class");
5442 }
5443 }();
5444 assert(T->getKeyword() == Keyword);
5445 assert(T->getQualifier() == Qualifier);
5446 assert(T->getOriginalDecl() == TD);
5447 assert(T->isInjected() == IsInjected);
5448 assert(T->isTagOwned() == OwnsTag);
5449 assert((T->isCanonicalUnqualified()
5450 ? QualType()
5451 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5452 Types.push_back(T);
5453 return T;
5454}
5455
5456static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5457 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5458 RD && RD->isInjectedClassName())
5459 return cast<TagDecl>(RD->getDeclContext());
5460 return TD;
5461}
5462
5465 if (TD->TypeForDecl)
5466 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5467
5468 const Type *CanonicalType = getTagTypeInternal(
5470 /*Qualifier=*/std::nullopt, TD,
5471 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5472 /*WithFoldingSetNode=*/false);
5473 TD->TypeForDecl = CanonicalType;
5474 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5475}
5476
5478 NestedNameSpecifier Qualifier,
5479 const TagDecl *TD, bool OwnsTag) const {
5480
5481 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5482 bool IsInjected = TD != NonInjectedTD;
5483
5484 ElaboratedTypeKeyword PreferredKeyword =
5487 NonInjectedTD->getTagKind());
5488
5489 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5490 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5491 return QualType(T, 0);
5492
5493 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5494 const Type *T =
5495 getTagTypeInternal(Keyword,
5496 /*Qualifier=*/std::nullopt, NonInjectedTD,
5497 /*OwnsTag=*/false, IsInjected, CanonicalType,
5498 /*WithFoldingSetNode=*/false);
5499 TD->TypeForDecl = T;
5500 return QualType(T, 0);
5501 }
5502
5503 llvm::FoldingSetNodeID ID;
5504 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5505 OwnsTag, IsInjected);
5506
5507 void *InsertPos = nullptr;
5508 if (TagTypeFoldingSetPlaceholder *T =
5509 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5510 return QualType(T->getTagType(), 0);
5511
5512 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5513 TagType *T =
5514 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5515 CanonicalType, /*WithFoldingSetNode=*/true);
5516 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5517 return QualType(T, 0);
5518}
5519
5520bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5521 unsigned NumPositiveBits,
5522 QualType &BestType,
5523 QualType &BestPromotionType) {
5524 unsigned IntWidth = Target->getIntWidth();
5525 unsigned CharWidth = Target->getCharWidth();
5526 unsigned ShortWidth = Target->getShortWidth();
5527 bool EnumTooLarge = false;
5528 unsigned BestWidth;
5529 if (NumNegativeBits) {
5530 // If there is a negative value, figure out the smallest integer type (of
5531 // int/long/longlong) that fits.
5532 // If it's packed, check also if it fits a char or a short.
5533 if (IsPacked && NumNegativeBits <= CharWidth &&
5534 NumPositiveBits < CharWidth) {
5535 BestType = SignedCharTy;
5536 BestWidth = CharWidth;
5537 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5538 NumPositiveBits < ShortWidth) {
5539 BestType = ShortTy;
5540 BestWidth = ShortWidth;
5541 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5542 BestType = IntTy;
5543 BestWidth = IntWidth;
5544 } else {
5545 BestWidth = Target->getLongWidth();
5546
5547 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5548 BestType = LongTy;
5549 } else {
5550 BestWidth = Target->getLongLongWidth();
5551
5552 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5553 EnumTooLarge = true;
5554 BestType = LongLongTy;
5555 }
5556 }
5557 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5558 } else {
5559 // If there is no negative value, figure out the smallest type that fits
5560 // all of the enumerator values.
5561 // If it's packed, check also if it fits a char or a short.
5562 if (IsPacked && NumPositiveBits <= CharWidth) {
5563 BestType = UnsignedCharTy;
5564 BestPromotionType = IntTy;
5565 BestWidth = CharWidth;
5566 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5567 BestType = UnsignedShortTy;
5568 BestPromotionType = IntTy;
5569 BestWidth = ShortWidth;
5570 } else if (NumPositiveBits <= IntWidth) {
5571 BestType = UnsignedIntTy;
5572 BestWidth = IntWidth;
5573 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5575 : IntTy;
5576 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5577 BestType = UnsignedLongTy;
5578 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5580 : LongTy;
5581 } else {
5582 BestWidth = Target->getLongLongWidth();
5583 if (NumPositiveBits > BestWidth) {
5584 // This can happen with bit-precise integer types, but those are not
5585 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5586 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5587 // a 128-bit integer, we should consider doing the same.
5588 EnumTooLarge = true;
5589 }
5590 BestType = UnsignedLongLongTy;
5591 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5593 : LongLongTy;
5594 }
5595 }
5596 return EnumTooLarge;
5597}
5598
5600 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5601 "Integral type required!");
5602 unsigned BitWidth = getIntWidth(T);
5603
5604 if (Value.isUnsigned() || Value.isNonNegative()) {
5605 if (T->isSignedIntegerOrEnumerationType())
5606 --BitWidth;
5607 return Value.getActiveBits() <= BitWidth;
5608 }
5609 return Value.getSignificantBits() <= BitWidth;
5610}
5611
5612UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5614 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5615 const Type *CanonicalType) const {
5616 void *Mem = Allocate(
5617 UnresolvedUsingType::totalSizeToAlloc<
5619 !!InsertPos, !!Qualifier),
5620 alignof(UnresolvedUsingType));
5621 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5622 if (InsertPos) {
5623 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5625 TypedefTypes.InsertNode(Placeholder, InsertPos);
5626 }
5627 Types.push_back(T);
5628 return T;
5629}
5630
5632 const UnresolvedUsingTypenameDecl *D) const {
5633 D = D->getCanonicalDecl();
5634 if (D->TypeForDecl)
5635 return D->TypeForDecl->getCanonicalTypeUnqualified();
5636
5637 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5639 /*Qualifier=*/std::nullopt, D,
5640 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5641 D->TypeForDecl = CanonicalType;
5642 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5643}
5644
5647 NestedNameSpecifier Qualifier,
5648 const UnresolvedUsingTypenameDecl *D) const {
5649 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5650 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5651 return QualType(T, 0);
5652
5653 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5654 const Type *T =
5655 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5656 /*Qualifier=*/std::nullopt, D,
5657 /*InsertPos=*/nullptr, CanonicalType);
5658 D->TypeForDecl = T;
5659 return QualType(T, 0);
5660 }
5661
5662 llvm::FoldingSetNodeID ID;
5663 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5664
5665 void *InsertPos = nullptr;
5667 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5668 return QualType(Placeholder->getType(), 0);
5669 assert(InsertPos);
5670
5671 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5672 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5673 InsertPos, CanonicalType);
5674 return QualType(T, 0);
5675}
5676
5678 QualType modifiedType,
5679 QualType equivalentType,
5680 const Attr *attr) const {
5681 llvm::FoldingSetNodeID id;
5682 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5683
5684 void *insertPos = nullptr;
5685 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5686 if (type) return QualType(type, 0);
5687
5688 assert(!attr || attr->getKind() == attrKind);
5689
5690 QualType canon = getCanonicalType(equivalentType);
5691 type = new (*this, alignof(AttributedType))
5692 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5693
5694 Types.push_back(type);
5695 AttributedTypes.InsertNode(type, insertPos);
5696
5697 return QualType(type, 0);
5698}
5699
5701 QualType equivalentType) const {
5702 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5703}
5704
5706 QualType modifiedType,
5707 QualType equivalentType) {
5708 switch (nullability) {
5710 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5711
5713 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5714
5716 return getAttributedType(attr::TypeNullableResult, modifiedType,
5717 equivalentType);
5718
5720 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5721 equivalentType);
5722 }
5723
5724 llvm_unreachable("Unknown nullability kind");
5725}
5726
5727QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5728 QualType Wrapped) const {
5729 llvm::FoldingSetNodeID ID;
5730 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5731
5732 void *InsertPos = nullptr;
5733 BTFTagAttributedType *Ty =
5734 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5735 if (Ty)
5736 return QualType(Ty, 0);
5737
5738 QualType Canon = getCanonicalType(Wrapped);
5739 Ty = new (*this, alignof(BTFTagAttributedType))
5740 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5741
5742 Types.push_back(Ty);
5743 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5744
5745 return QualType(Ty, 0);
5746}
5747
5749 QualType Wrapped, QualType Contained,
5750 const HLSLAttributedResourceType::Attributes &Attrs) {
5751
5752 llvm::FoldingSetNodeID ID;
5753 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5754
5755 void *InsertPos = nullptr;
5756 HLSLAttributedResourceType *Ty =
5757 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5758 if (Ty)
5759 return QualType(Ty, 0);
5760
5761 Ty = new (*this, alignof(HLSLAttributedResourceType))
5762 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5763
5764 Types.push_back(Ty);
5765 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5766
5767 return QualType(Ty, 0);
5768}
5769
5770QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5771 uint32_t Alignment,
5772 ArrayRef<SpirvOperand> Operands) {
5773 llvm::FoldingSetNodeID ID;
5774 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5775
5776 void *InsertPos = nullptr;
5777 HLSLInlineSpirvType *Ty =
5778 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5779 if (Ty)
5780 return QualType(Ty, 0);
5781
5782 void *Mem = Allocate(
5783 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5784 alignof(HLSLInlineSpirvType));
5785
5786 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5787
5788 Types.push_back(Ty);
5789 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5790
5791 return QualType(Ty, 0);
5792}
5793
5794/// Retrieve a substitution-result type.
5796 Decl *AssociatedDecl,
5797 unsigned Index,
5798 UnsignedOrNone PackIndex,
5799 bool Final) const {
5800 llvm::FoldingSetNodeID ID;
5801 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5802 PackIndex, Final);
5803 void *InsertPos = nullptr;
5804 SubstTemplateTypeParmType *SubstParm =
5805 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5806
5807 if (!SubstParm) {
5808 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5809 !Replacement.isCanonical()),
5810 alignof(SubstTemplateTypeParmType));
5811 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5812 Index, PackIndex, Final);
5813 Types.push_back(SubstParm);
5814 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5815 }
5816
5817 return QualType(SubstParm, 0);
5818}
5819
5822 unsigned Index, bool Final,
5823 const TemplateArgument &ArgPack) {
5824#ifndef NDEBUG
5825 for (const auto &P : ArgPack.pack_elements())
5826 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5827#endif
5828
5829 llvm::FoldingSetNodeID ID;
5830 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5831 ArgPack);
5832 void *InsertPos = nullptr;
5833 if (SubstTemplateTypeParmPackType *SubstParm =
5834 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5835 return QualType(SubstParm, 0);
5836
5837 QualType Canon;
5838 {
5839 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5840 if (!AssociatedDecl->isCanonicalDecl() ||
5841 !CanonArgPack.structurallyEquals(ArgPack)) {
5843 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5844 [[maybe_unused]] const auto *Nothing =
5845 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5846 assert(!Nothing);
5847 }
5848 }
5849
5850 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5851 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5852 ArgPack);
5853 Types.push_back(SubstParm);
5854 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5855 return QualType(SubstParm, 0);
5856}
5857
5860 assert(llvm::all_of(ArgPack.pack_elements(),
5861 [](const auto &P) {
5862 return P.getKind() == TemplateArgument::Type;
5863 }) &&
5864 "Pack contains a non-type");
5865
5866 llvm::FoldingSetNodeID ID;
5867 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5868
5869 void *InsertPos = nullptr;
5870 if (auto *T =
5871 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5872 return QualType(T, 0);
5873
5874 QualType Canon;
5875 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5876 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5877 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5878 // Refresh InsertPos, in case the recursive call above caused rehashing,
5879 // which would invalidate the bucket pointer.
5880 [[maybe_unused]] const auto *Nothing =
5881 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5882 assert(!Nothing);
5883 }
5884
5885 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5886 SubstBuiltinTemplatePackType(Canon, ArgPack);
5887 Types.push_back(PackType);
5888 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5889 return QualType(PackType, 0);
5890}
5891
5892/// Retrieve the template type parameter type for a template
5893/// parameter or parameter pack with the given depth, index, and (optionally)
5894/// name.
5895QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5896 bool ParameterPack,
5897 TemplateTypeParmDecl *TTPDecl) const {
5898 llvm::FoldingSetNodeID ID;
5899 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5900 void *InsertPos = nullptr;
5901 TemplateTypeParmType *TypeParm
5902 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5903
5904 if (TypeParm)
5905 return QualType(TypeParm, 0);
5906
5907 if (TTPDecl) {
5908 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5909 TypeParm = new (*this, alignof(TemplateTypeParmType))
5910 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5911
5912 TemplateTypeParmType *TypeCheck
5913 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5914 assert(!TypeCheck && "Template type parameter canonical type broken");
5915 (void)TypeCheck;
5916 } else
5917 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5918 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5919
5920 Types.push_back(TypeParm);
5921 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5922
5923 return QualType(TypeParm, 0);
5924}
5925
5928 switch (Keyword) {
5929 // These are just themselves.
5935 return Keyword;
5936
5937 // These are equivalent.
5940
5941 // These are functionally equivalent, so relying on their equivalence is
5942 // IFNDR. By making them equivalent, we disallow overloading, which at least
5943 // can produce a diagnostic.
5946 }
5947 llvm_unreachable("unexpected keyword kind");
5948}
5949
5951 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5952 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5953 TemplateName Name, SourceLocation NameLoc,
5954 const TemplateArgumentListInfo &SpecifiedArgs,
5955 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5957 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5958
5961 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5962 SpecifiedArgs);
5963 return DI;
5964}
5965
5968 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5969 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5970 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5971 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5972 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5973 SpecifiedArgVec.push_back(Arg.getArgument());
5974
5975 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5976 CanonicalArgs, Underlying);
5977}
5978
5979[[maybe_unused]] static bool
5981 for (const TemplateArgument &Arg : Args)
5982 if (Arg.isPackExpansion())
5983 return true;
5984 return false;
5985}
5986
5989 ArrayRef<TemplateArgument> Args) const {
5990 assert(Template ==
5991 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5993 Template.getAsDependentTemplateName()));
5994#ifndef NDEBUG
5995 for (const auto &Arg : Args)
5996 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5997#endif
5998
5999 llvm::FoldingSetNodeID ID;
6000 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6001 *this);
6002 void *InsertPos = nullptr;
6003 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6004 return QualType(T, 0);
6005
6006 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6007 sizeof(TemplateArgument) * Args.size(),
6008 alignof(TemplateSpecializationType));
6009 auto *Spec =
6010 new (Mem) TemplateSpecializationType(Keyword, Template,
6011 /*IsAlias=*/false, Args, QualType());
6012 assert(Spec->isDependentType() &&
6013 "canonical template specialization must be dependent");
6014 Types.push_back(Spec);
6015 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6016 return QualType(Spec, 0);
6017}
6018
6021 ArrayRef<TemplateArgument> SpecifiedArgs,
6022 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6023 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6024 bool IsTypeAlias = TD && TD->isTypeAlias();
6025 if (Underlying.isNull()) {
6026 TemplateName CanonTemplate =
6027 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6028 ElaboratedTypeKeyword CanonKeyword =
6029 CanonTemplate.getAsDependentTemplateName()
6032 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6034 if (CanonicalArgs.empty()) {
6035 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6036 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6037 CanonicalArgs = CanonArgsVec;
6038 } else {
6039 NonCanonical |= !llvm::equal(
6040 SpecifiedArgs, CanonicalArgs,
6041 [](const TemplateArgument &A, const TemplateArgument &B) {
6042 return A.structurallyEquals(B);
6043 });
6044 }
6045
6046 // We can get here with an alias template when the specialization
6047 // contains a pack expansion that does not match up with a parameter
6048 // pack, or a builtin template which cannot be resolved due to dependency.
6049 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6050 hasAnyPackExpansions(CanonicalArgs)) &&
6051 "Caller must compute aliased type");
6052 IsTypeAlias = false;
6053
6055 CanonKeyword, CanonTemplate, CanonicalArgs);
6056 if (!NonCanonical)
6057 return Underlying;
6058 }
6059 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6060 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6061 (IsTypeAlias ? sizeof(QualType) : 0),
6062 alignof(TemplateSpecializationType));
6063 auto *Spec = new (Mem) TemplateSpecializationType(
6064 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6065 Types.push_back(Spec);
6066 return QualType(Spec, 0);
6067}
6068
6071 llvm::FoldingSetNodeID ID;
6072 ParenType::Profile(ID, InnerType);
6073
6074 void *InsertPos = nullptr;
6075 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6076 if (T)
6077 return QualType(T, 0);
6078
6079 QualType Canon = InnerType;
6080 if (!Canon.isCanonical()) {
6081 Canon = getCanonicalType(InnerType);
6082 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6083 assert(!CheckT && "Paren canonical type broken");
6084 (void)CheckT;
6085 }
6086
6087 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6088 Types.push_back(T);
6089 ParenTypes.InsertNode(T, InsertPos);
6090 return QualType(T, 0);
6091}
6092
6095 const IdentifierInfo *MacroII) const {
6096 QualType Canon = UnderlyingTy;
6097 if (!Canon.isCanonical())
6098 Canon = getCanonicalType(UnderlyingTy);
6099
6100 auto *newType = new (*this, alignof(MacroQualifiedType))
6101 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6102 Types.push_back(newType);
6103 return QualType(newType, 0);
6104}
6105
6108 const IdentifierInfo *Name) const {
6109 llvm::FoldingSetNodeID ID;
6110 DependentNameType::Profile(ID, Keyword, NNS, Name);
6111
6112 void *InsertPos = nullptr;
6113 if (DependentNameType *T =
6114 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6115 return QualType(T, 0);
6116
6117 ElaboratedTypeKeyword CanonKeyword =
6119 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6120
6121 QualType Canon;
6122 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6123 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6124 [[maybe_unused]] DependentNameType *T =
6125 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6126 assert(!T && "broken canonicalization");
6127 assert(Canon.isCanonical());
6128 }
6129
6130 DependentNameType *T = new (*this, alignof(DependentNameType))
6131 DependentNameType(Keyword, NNS, Name, Canon);
6132 Types.push_back(T);
6133 DependentNameTypes.InsertNode(T, InsertPos);
6134 return QualType(T, 0);
6135}
6136
6138 TemplateArgument Arg;
6139 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6141 if (TTP->isParameterPack())
6142 ArgType = getPackExpansionType(ArgType, std::nullopt);
6143
6145 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6146 QualType T =
6147 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6148 // For class NTTPs, ensure we include the 'const' so the type matches that
6149 // of a real template argument.
6150 // FIXME: It would be more faithful to model this as something like an
6151 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6153 if (T->isRecordType()) {
6154 // C++ [temp.param]p8: An id-expression naming a non-type
6155 // template-parameter of class type T denotes a static storage duration
6156 // object of type const T.
6157 T.addConst();
6158 VK = VK_LValue;
6159 } else {
6160 VK = Expr::getValueKindForType(NTTP->getType());
6161 }
6162 Expr *E = new (*this)
6163 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6164 T, VK, NTTP->getLocation());
6165
6166 if (NTTP->isParameterPack())
6167 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6168 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6169 } else {
6170 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6172 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6173 TemplateName(TTP));
6174 if (TTP->isParameterPack())
6175 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6176 else
6177 Arg = TemplateArgument(Name);
6178 }
6179
6180 if (Param->isTemplateParameterPack())
6181 Arg =
6182 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6183
6184 return Arg;
6185}
6186
6188 UnsignedOrNone NumExpansions,
6189 bool ExpectPackInType) const {
6190 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6191 "Pack expansions must expand one or more parameter packs");
6192
6193 llvm::FoldingSetNodeID ID;
6194 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6195
6196 void *InsertPos = nullptr;
6197 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6198 if (T)
6199 return QualType(T, 0);
6200
6201 QualType Canon;
6202 if (!Pattern.isCanonical()) {
6203 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6204 /*ExpectPackInType=*/false);
6205
6206 // Find the insert position again, in case we inserted an element into
6207 // PackExpansionTypes and invalidated our insert position.
6208 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6209 }
6210
6211 T = new (*this, alignof(PackExpansionType))
6212 PackExpansionType(Pattern, Canon, NumExpansions);
6213 Types.push_back(T);
6214 PackExpansionTypes.InsertNode(T, InsertPos);
6215 return QualType(T, 0);
6216}
6217
6218/// CmpProtocolNames - Comparison predicate for sorting protocols
6219/// alphabetically.
6220static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6221 ObjCProtocolDecl *const *RHS) {
6222 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6223}
6224
6226 if (Protocols.empty()) return true;
6227
6228 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6229 return false;
6230
6231 for (unsigned i = 1; i != Protocols.size(); ++i)
6232 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6233 Protocols[i]->getCanonicalDecl() != Protocols[i])
6234 return false;
6235 return true;
6236}
6237
6238static void
6240 // Sort protocols, keyed by name.
6241 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6242
6243 // Canonicalize.
6244 for (ObjCProtocolDecl *&P : Protocols)
6245 P = P->getCanonicalDecl();
6246
6247 // Remove duplicates.
6248 auto ProtocolsEnd = llvm::unique(Protocols);
6249 Protocols.erase(ProtocolsEnd, Protocols.end());
6250}
6251
6253 ObjCProtocolDecl * const *Protocols,
6254 unsigned NumProtocols) const {
6255 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6256 /*isKindOf=*/false);
6257}
6258
6260 QualType baseType,
6261 ArrayRef<QualType> typeArgs,
6263 bool isKindOf) const {
6264 // If the base type is an interface and there aren't any protocols or
6265 // type arguments to add, then the interface type will do just fine.
6266 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6267 isa<ObjCInterfaceType>(baseType))
6268 return baseType;
6269
6270 // Look in the folding set for an existing type.
6271 llvm::FoldingSetNodeID ID;
6272 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6273 void *InsertPos = nullptr;
6274 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6275 return QualType(QT, 0);
6276
6277 // Determine the type arguments to be used for canonicalization,
6278 // which may be explicitly specified here or written on the base
6279 // type.
6280 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6281 if (effectiveTypeArgs.empty()) {
6282 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6283 effectiveTypeArgs = baseObject->getTypeArgs();
6284 }
6285
6286 // Build the canonical type, which has the canonical base type and a
6287 // sorted-and-uniqued list of protocols and the type arguments
6288 // canonicalized.
6289 QualType canonical;
6290 bool typeArgsAreCanonical = llvm::all_of(
6291 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6292 bool protocolsSorted = areSortedAndUniqued(protocols);
6293 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6294 // Determine the canonical type arguments.
6295 ArrayRef<QualType> canonTypeArgs;
6296 SmallVector<QualType, 4> canonTypeArgsVec;
6297 if (!typeArgsAreCanonical) {
6298 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6299 for (auto typeArg : effectiveTypeArgs)
6300 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6301 canonTypeArgs = canonTypeArgsVec;
6302 } else {
6303 canonTypeArgs = effectiveTypeArgs;
6304 }
6305
6306 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6307 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6308 if (!protocolsSorted) {
6309 canonProtocolsVec.append(protocols.begin(), protocols.end());
6310 SortAndUniqueProtocols(canonProtocolsVec);
6311 canonProtocols = canonProtocolsVec;
6312 } else {
6313 canonProtocols = protocols;
6314 }
6315
6316 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6317 canonProtocols, isKindOf);
6318
6319 // Regenerate InsertPos.
6320 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6321 }
6322
6323 unsigned size = sizeof(ObjCObjectTypeImpl);
6324 size += typeArgs.size() * sizeof(QualType);
6325 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6326 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6327 auto *T =
6328 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6329 isKindOf);
6330
6331 Types.push_back(T);
6332 ObjCObjectTypes.InsertNode(T, InsertPos);
6333 return QualType(T, 0);
6334}
6335
6336/// Apply Objective-C protocol qualifiers to the given type.
6337/// If this is for the canonical type of a type parameter, we can apply
6338/// protocol qualifiers on the ObjCObjectPointerType.
6341 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6342 bool allowOnPointerType) const {
6343 hasError = false;
6344
6345 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6346 return getObjCTypeParamType(objT->getDecl(), protocols);
6347 }
6348
6349 // Apply protocol qualifiers to ObjCObjectPointerType.
6350 if (allowOnPointerType) {
6351 if (const auto *objPtr =
6352 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6353 const ObjCObjectType *objT = objPtr->getObjectType();
6354 // Merge protocol lists and construct ObjCObjectType.
6356 protocolsVec.append(objT->qual_begin(),
6357 objT->qual_end());
6358 protocolsVec.append(protocols.begin(), protocols.end());
6359 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6361 objT->getBaseType(),
6362 objT->getTypeArgsAsWritten(),
6363 protocols,
6364 objT->isKindOfTypeAsWritten());
6366 }
6367 }
6368
6369 // Apply protocol qualifiers to ObjCObjectType.
6370 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6371 // FIXME: Check for protocols to which the class type is already
6372 // known to conform.
6373
6374 return getObjCObjectType(objT->getBaseType(),
6375 objT->getTypeArgsAsWritten(),
6376 protocols,
6377 objT->isKindOfTypeAsWritten());
6378 }
6379
6380 // If the canonical type is ObjCObjectType, ...
6381 if (type->isObjCObjectType()) {
6382 // Silently overwrite any existing protocol qualifiers.
6383 // TODO: determine whether that's the right thing to do.
6384
6385 // FIXME: Check for protocols to which the class type is already
6386 // known to conform.
6387 return getObjCObjectType(type, {}, protocols, false);
6388 }
6389
6390 // id<protocol-list>
6391 if (type->isObjCIdType()) {
6392 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6393 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6394 objPtr->isKindOfType());
6396 }
6397
6398 // Class<protocol-list>
6399 if (type->isObjCClassType()) {
6400 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6401 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6402 objPtr->isKindOfType());
6404 }
6405
6406 hasError = true;
6407 return type;
6408}
6409
6412 ArrayRef<ObjCProtocolDecl *> protocols) const {
6413 // Look in the folding set for an existing type.
6414 llvm::FoldingSetNodeID ID;
6415 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6416 void *InsertPos = nullptr;
6417 if (ObjCTypeParamType *TypeParam =
6418 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6419 return QualType(TypeParam, 0);
6420
6421 // We canonicalize to the underlying type.
6422 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6423 if (!protocols.empty()) {
6424 // Apply the protocol qualifers.
6425 bool hasError;
6427 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6428 assert(!hasError && "Error when apply protocol qualifier to bound type");
6429 }
6430
6431 unsigned size = sizeof(ObjCTypeParamType);
6432 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6433 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6434 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6435
6436 Types.push_back(newType);
6437 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6438 return QualType(newType, 0);
6439}
6440
6442 ObjCTypeParamDecl *New) const {
6443 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6444 // Update TypeForDecl after updating TypeSourceInfo.
6445 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6447 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6448 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6449 New->TypeForDecl = UpdatedTy.getTypePtr();
6450}
6451
6452/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6453/// protocol list adopt all protocols in QT's qualified-id protocol
6454/// list.
6456 ObjCInterfaceDecl *IC) {
6457 if (!QT->isObjCQualifiedIdType())
6458 return false;
6459
6460 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6461 // If both the right and left sides have qualifiers.
6462 for (auto *Proto : OPT->quals()) {
6463 if (!IC->ClassImplementsProtocol(Proto, false))
6464 return false;
6465 }
6466 return true;
6467 }
6468 return false;
6469}
6470
6471/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6472/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6473/// of protocols.
6475 ObjCInterfaceDecl *IDecl) {
6476 if (!QT->isObjCQualifiedIdType())
6477 return false;
6478 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6479 if (!OPT)
6480 return false;
6481 if (!IDecl->hasDefinition())
6482 return false;
6484 CollectInheritedProtocols(IDecl, InheritedProtocols);
6485 if (InheritedProtocols.empty())
6486 return false;
6487 // Check that if every protocol in list of id<plist> conforms to a protocol
6488 // of IDecl's, then bridge casting is ok.
6489 bool Conforms = false;
6490 for (auto *Proto : OPT->quals()) {
6491 Conforms = false;
6492 for (auto *PI : InheritedProtocols) {
6493 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6494 Conforms = true;
6495 break;
6496 }
6497 }
6498 if (!Conforms)
6499 break;
6500 }
6501 if (Conforms)
6502 return true;
6503
6504 for (auto *PI : InheritedProtocols) {
6505 // If both the right and left sides have qualifiers.
6506 bool Adopts = false;
6507 for (auto *Proto : OPT->quals()) {
6508 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6509 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6510 break;
6511 }
6512 if (!Adopts)
6513 return false;
6514 }
6515 return true;
6516}
6517
6518/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6519/// the given object type.
6521 llvm::FoldingSetNodeID ID;
6522 ObjCObjectPointerType::Profile(ID, ObjectT);
6523
6524 void *InsertPos = nullptr;
6525 if (ObjCObjectPointerType *QT =
6526 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6527 return QualType(QT, 0);
6528
6529 // Find the canonical object type.
6530 QualType Canonical;
6531 if (!ObjectT.isCanonical()) {
6532 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6533
6534 // Regenerate InsertPos.
6535 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6536 }
6537
6538 // No match.
6539 void *Mem =
6541 auto *QType =
6542 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6543
6544 Types.push_back(QType);
6545 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6546 return QualType(QType, 0);
6547}
6548
6549/// getObjCInterfaceType - Return the unique reference to the type for the
6550/// specified ObjC interface decl. The list of protocols is optional.
6552 ObjCInterfaceDecl *PrevDecl) const {
6553 if (Decl->TypeForDecl)
6554 return QualType(Decl->TypeForDecl, 0);
6555
6556 if (PrevDecl) {
6557 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6558 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6559 return QualType(PrevDecl->TypeForDecl, 0);
6560 }
6561
6562 // Prefer the definition, if there is one.
6563 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6564 Decl = Def;
6565
6566 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6567 auto *T = new (Mem) ObjCInterfaceType(Decl);
6568 Decl->TypeForDecl = T;
6569 Types.push_back(T);
6570 return QualType(T, 0);
6571}
6572
6573/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6574/// TypeOfExprType AST's (since expression's are never shared). For example,
6575/// multiple declarations that refer to "typeof(x)" all contain different
6576/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6577/// on canonical type's (which are always unique).
6579 TypeOfExprType *toe;
6580 if (tofExpr->isTypeDependent()) {
6581 llvm::FoldingSetNodeID ID;
6582 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6583 Kind == TypeOfKind::Unqualified);
6584
6585 void *InsertPos = nullptr;
6587 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6588 if (Canon) {
6589 // We already have a "canonical" version of an identical, dependent
6590 // typeof(expr) type. Use that as our canonical type.
6591 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6592 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6593 } else {
6594 // Build a new, canonical typeof(expr) type.
6595 Canon = new (*this, alignof(DependentTypeOfExprType))
6596 DependentTypeOfExprType(*this, tofExpr, Kind);
6597 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6598 toe = Canon;
6599 }
6600 } else {
6601 QualType Canonical = getCanonicalType(tofExpr->getType());
6602 toe = new (*this, alignof(TypeOfExprType))
6603 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6604 }
6605 Types.push_back(toe);
6606 return QualType(toe, 0);
6607}
6608
6609/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6610/// TypeOfType nodes. The only motivation to unique these nodes would be
6611/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6612/// an issue. This doesn't affect the type checker, since it operates
6613/// on canonical types (which are always unique).
6615 QualType Canonical = getCanonicalType(tofType);
6616 auto *tot = new (*this, alignof(TypeOfType))
6617 TypeOfType(*this, tofType, Canonical, Kind);
6618 Types.push_back(tot);
6619 return QualType(tot, 0);
6620}
6621
6622/// getReferenceQualifiedType - Given an expr, will return the type for
6623/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6624/// and class member access into account.
6626 // C++11 [dcl.type.simple]p4:
6627 // [...]
6628 QualType T = E->getType();
6629 switch (E->getValueKind()) {
6630 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6631 // type of e;
6632 case VK_XValue:
6633 return getRValueReferenceType(T);
6634 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6635 // type of e;
6636 case VK_LValue:
6637 return getLValueReferenceType(T);
6638 // - otherwise, decltype(e) is the type of e.
6639 case VK_PRValue:
6640 return T;
6641 }
6642 llvm_unreachable("Unknown value kind");
6643}
6644
6645/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6646/// nodes. This would never be helpful, since each such type has its own
6647/// expression, and would not give a significant memory saving, since there
6648/// is an Expr tree under each such type.
6650 // C++11 [temp.type]p2:
6651 // If an expression e involves a template parameter, decltype(e) denotes a
6652 // unique dependent type. Two such decltype-specifiers refer to the same
6653 // type only if their expressions are equivalent (14.5.6.1).
6654 QualType CanonType;
6655 if (!E->isInstantiationDependent()) {
6656 CanonType = getCanonicalType(UnderlyingType);
6657 } else if (!UnderlyingType.isNull()) {
6658 CanonType = getDecltypeType(E, QualType());
6659 } else {
6660 llvm::FoldingSetNodeID ID;
6661 DependentDecltypeType::Profile(ID, *this, E);
6662
6663 void *InsertPos = nullptr;
6664 if (DependentDecltypeType *Canon =
6665 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6666 return QualType(Canon, 0);
6667
6668 // Build a new, canonical decltype(expr) type.
6669 auto *DT =
6670 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6671 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6672 Types.push_back(DT);
6673 return QualType(DT, 0);
6674 }
6675 auto *DT = new (*this, alignof(DecltypeType))
6676 DecltypeType(E, UnderlyingType, CanonType);
6677 Types.push_back(DT);
6678 return QualType(DT, 0);
6679}
6680
6682 bool FullySubstituted,
6683 ArrayRef<QualType> Expansions,
6684 UnsignedOrNone Index) const {
6685 QualType Canonical;
6686 if (FullySubstituted && Index) {
6687 Canonical = getCanonicalType(Expansions[*Index]);
6688 } else {
6689 llvm::FoldingSetNodeID ID;
6690 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6691 FullySubstituted, Expansions);
6692 void *InsertPos = nullptr;
6693 PackIndexingType *Canon =
6694 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6695 if (!Canon) {
6696 void *Mem = Allocate(
6697 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6699 Canon =
6700 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6701 IndexExpr, FullySubstituted, Expansions);
6702 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6703 }
6704 Canonical = QualType(Canon, 0);
6705 }
6706
6707 void *Mem =
6708 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6710 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6711 FullySubstituted, Expansions);
6712 Types.push_back(T);
6713 return QualType(T, 0);
6714}
6715
6716/// getUnaryTransformationType - We don't unique these, since the memory
6717/// savings are minimal and these are rare.
6720 UnaryTransformType::UTTKind Kind) const {
6721
6722 llvm::FoldingSetNodeID ID;
6723 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6724
6725 void *InsertPos = nullptr;
6726 if (UnaryTransformType *UT =
6727 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6728 return QualType(UT, 0);
6729
6730 QualType CanonType;
6731 if (!BaseType->isDependentType()) {
6732 CanonType = UnderlyingType.getCanonicalType();
6733 } else {
6734 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6735 UnderlyingType = QualType();
6736 if (QualType CanonBase = BaseType.getCanonicalType();
6737 BaseType != CanonBase) {
6738 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6739 assert(CanonType.isCanonical());
6740
6741 // Find the insertion position again.
6742 [[maybe_unused]] UnaryTransformType *UT =
6743 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6744 assert(!UT && "broken canonicalization");
6745 }
6746 }
6747
6748 auto *UT = new (*this, alignof(UnaryTransformType))
6749 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6750 UnaryTransformTypes.InsertNode(UT, InsertPos);
6751 Types.push_back(UT);
6752 return QualType(UT, 0);
6753}
6754
6755QualType ASTContext::getAutoTypeInternal(
6756 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6757 bool IsPack, TemplateDecl *TypeConstraintConcept,
6758 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6759 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6760 !TypeConstraintConcept && !IsDependent)
6761 return getAutoDeductType();
6762
6763 // Look in the folding set for an existing type.
6764 llvm::FoldingSetNodeID ID;
6765 bool IsDeducedDependent =
6766 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6767 (!DeducedType.isNull() && DeducedType->isDependentType());
6768 AutoType::Profile(ID, *this, DeducedType, Keyword,
6769 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6770 TypeConstraintArgs);
6771 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6772 return QualType(AT_iter->getSecond(), 0);
6773
6774 QualType Canon;
6775 if (!IsCanon) {
6776 if (!DeducedType.isNull()) {
6777 Canon = DeducedType.getCanonicalType();
6778 } else if (TypeConstraintConcept) {
6779 bool AnyNonCanonArgs = false;
6780 auto *CanonicalConcept =
6781 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6782 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6783 *this, TypeConstraintArgs, AnyNonCanonArgs);
6784 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6785 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6786 CanonicalConcept, CanonicalConceptArgs,
6787 /*IsCanon=*/true);
6788 }
6789 }
6790 }
6791
6792 void *Mem = Allocate(sizeof(AutoType) +
6793 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6794 alignof(AutoType));
6795 auto *AT = new (Mem) AutoType(
6796 DeducedType, Keyword,
6797 (IsDependent ? TypeDependence::DependentInstantiation
6798 : TypeDependence::None) |
6799 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6800 Canon, TypeConstraintConcept, TypeConstraintArgs);
6801#ifndef NDEBUG
6802 llvm::FoldingSetNodeID InsertedID;
6803 AT->Profile(InsertedID, *this);
6804 assert(InsertedID == ID && "ID does not match");
6805#endif
6806 Types.push_back(AT);
6807 AutoTypes.try_emplace(ID, AT);
6808 return QualType(AT, 0);
6809}
6810
6811/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6812/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6813/// canonical deduced-but-dependent 'auto' type.
6814QualType
6816 bool IsDependent, bool IsPack,
6817 TemplateDecl *TypeConstraintConcept,
6818 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6819 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6820 assert((!IsDependent || DeducedType.isNull()) &&
6821 "A dependent auto should be undeduced");
6822 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6823 TypeConstraintConcept, TypeConstraintArgs);
6824}
6825
6827 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6828
6829 // Remove a type-constraint from a top-level auto or decltype(auto).
6830 if (auto *AT = CanonT->getAs<AutoType>()) {
6831 if (!AT->isConstrained())
6832 return T;
6833 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6834 AT->isDependentType(),
6835 AT->containsUnexpandedParameterPack()),
6836 T.getQualifiers());
6837 }
6838
6839 // FIXME: We only support constrained auto at the top level in the type of a
6840 // non-type template parameter at the moment. Once we lift that restriction,
6841 // we'll need to recursively build types containing auto here.
6842 assert(!CanonT->getContainedAutoType() ||
6843 !CanonT->getContainedAutoType()->isConstrained());
6844 return T;
6845}
6846
6847QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6849 bool IsDependent, QualType Canon) const {
6850 // Look in the folding set for an existing type.
6851 void *InsertPos = nullptr;
6852 llvm::FoldingSetNodeID ID;
6853 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6854 IsDependent);
6855 if (DeducedTemplateSpecializationType *DTST =
6856 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6857 return QualType(DTST, 0);
6858
6859 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6860 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6861 IsDependent, Canon);
6862
6863#ifndef NDEBUG
6864 llvm::FoldingSetNodeID TempID;
6865 DTST->Profile(TempID);
6866 assert(ID == TempID && "ID does not match");
6867#endif
6868 Types.push_back(DTST);
6869 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6870 return QualType(DTST, 0);
6871}
6872
6873/// Return the uniqued reference to the deduced template specialization type
6874/// which has been deduced to the given type, or to the canonical undeduced
6875/// such type, or the canonical deduced-but-dependent such type.
6878 bool IsDependent) const {
6879 // FIXME: This could save an extra hash table lookup if it handled all the
6880 // parameters already being canonical.
6881 // FIXME: Can this be formed from a DependentTemplateName, such that the
6882 // keyword should be part of the canonical type?
6883 QualType Canon =
6884 DeducedType.isNull()
6885 ? getDeducedTemplateSpecializationTypeInternal(
6887 QualType(), IsDependent, QualType())
6888 : DeducedType.getCanonicalType();
6889 return getDeducedTemplateSpecializationTypeInternal(
6890 Keyword, Template, DeducedType, IsDependent, Canon);
6891}
6892
6893/// getAtomicType - Return the uniqued reference to the atomic type for
6894/// the given value type.
6896 // Unique pointers, to guarantee there is only one pointer of a particular
6897 // structure.
6898 llvm::FoldingSetNodeID ID;
6900
6901 void *InsertPos = nullptr;
6902 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6903 return QualType(AT, 0);
6904
6905 // If the atomic value type isn't canonical, this won't be a canonical type
6906 // either, so fill in the canonical type field.
6907 QualType Canonical;
6908 if (!T.isCanonical()) {
6909 Canonical = getAtomicType(getCanonicalType(T));
6910
6911 // Get the new insert position for the node we care about.
6912 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6913 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6914 }
6915 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6916 Types.push_back(New);
6917 AtomicTypes.InsertNode(New, InsertPos);
6918 return QualType(New, 0);
6919}
6920
6921/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6923 if (AutoDeductTy.isNull())
6924 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6925 AutoType(QualType(), AutoTypeKeyword::Auto,
6926 TypeDependence::None, QualType(),
6927 /*concept*/ nullptr, /*args*/ {}),
6928 0);
6929 return AutoDeductTy;
6930}
6931
6932/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6934 if (AutoRRefDeductTy.isNull())
6936 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6937 return AutoRRefDeductTy;
6938}
6939
6940/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6941/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6942/// needs to agree with the definition in <stddef.h>.
6946
6948 return getFromTargetType(Target->getSizeType());
6949}
6950
6951/// Return the unique signed counterpart of the integer type
6952/// corresponding to size_t.
6956
6957/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6958/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6962
6963/// Return the unique unsigned counterpart of "ptrdiff_t"
6964/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6965/// in the definition of %tu format specifier.
6967 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6968}
6969
6970/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6972 return getFromTargetType(Target->getIntMaxType());
6973}
6974
6975/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6977 return getFromTargetType(Target->getUIntMaxType());
6978}
6979
6980/// getSignedWCharType - Return the type of "signed wchar_t".
6981/// Used when in C++, as a GCC extension.
6983 // FIXME: derive from "Target" ?
6984 return WCharTy;
6985}
6986
6987/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6988/// Used when in C++, as a GCC extension.
6990 // FIXME: derive from "Target" ?
6991 return UnsignedIntTy;
6992}
6993
6995 return getFromTargetType(Target->getIntPtrType());
6996}
6997
7001
7002/// Return the unique type for "pid_t" defined in
7003/// <sys/types.h>. We need this to compute the correct type for vfork().
7005 return getFromTargetType(Target->getProcessIDType());
7006}
7007
7008//===----------------------------------------------------------------------===//
7009// Type Operators
7010//===----------------------------------------------------------------------===//
7011
7013 // Push qualifiers into arrays, and then discard any remaining
7014 // qualifiers.
7015 T = getCanonicalType(T);
7017 const Type *Ty = T.getTypePtr();
7021 } else if (isa<ArrayType>(Ty)) {
7023 } else if (isa<FunctionType>(Ty)) {
7024 Result = getPointerType(QualType(Ty, 0));
7025 } else {
7026 Result = QualType(Ty, 0);
7027 }
7028
7030}
7031
7033 Qualifiers &quals) const {
7034 SplitQualType splitType = type.getSplitUnqualifiedType();
7035
7036 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7037 // the unqualified desugared type and then drops it on the floor.
7038 // We then have to strip that sugar back off with
7039 // getUnqualifiedDesugaredType(), which is silly.
7040 const auto *AT =
7041 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7042
7043 // If we don't have an array, just use the results in splitType.
7044 if (!AT) {
7045 quals = splitType.Quals;
7046 return QualType(splitType.Ty, 0);
7047 }
7048
7049 // Otherwise, recurse on the array's element type.
7050 QualType elementType = AT->getElementType();
7051 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7052
7053 // If that didn't change the element type, AT has no qualifiers, so we
7054 // can just use the results in splitType.
7055 if (elementType == unqualElementType) {
7056 assert(quals.empty()); // from the recursive call
7057 quals = splitType.Quals;
7058 return QualType(splitType.Ty, 0);
7059 }
7060
7061 // Otherwise, add in the qualifiers from the outermost type, then
7062 // build the type back up.
7063 quals.addConsistentQualifiers(splitType.Quals);
7064
7065 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7066 return getConstantArrayType(unqualElementType, CAT->getSize(),
7067 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7068 }
7069
7070 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7071 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7072 }
7073
7074 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7075 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7076 VAT->getSizeModifier(),
7077 VAT->getIndexTypeCVRQualifiers());
7078 }
7079
7080 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7081 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7082 DSAT->getSizeModifier(), 0);
7083}
7084
7085/// Attempt to unwrap two types that may both be array types with the same bound
7086/// (or both be array types of unknown bound) for the purpose of comparing the
7087/// cv-decomposition of two types per C++ [conv.qual].
7088///
7089/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7090/// C++20 [conv.qual], if permitted by the current language mode.
7092 bool AllowPiMismatch) const {
7093 while (true) {
7094 auto *AT1 = getAsArrayType(T1);
7095 if (!AT1)
7096 return;
7097
7098 auto *AT2 = getAsArrayType(T2);
7099 if (!AT2)
7100 return;
7101
7102 // If we don't have two array types with the same constant bound nor two
7103 // incomplete array types, we've unwrapped everything we can.
7104 // C++20 also permits one type to be a constant array type and the other
7105 // to be an incomplete array type.
7106 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7107 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7108 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7109 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7110 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7112 return;
7113 } else if (isa<IncompleteArrayType>(AT1)) {
7114 if (!(isa<IncompleteArrayType>(AT2) ||
7115 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7117 return;
7118 } else {
7119 return;
7120 }
7121
7122 T1 = AT1->getElementType();
7123 T2 = AT2->getElementType();
7124 }
7125}
7126
7127/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7128///
7129/// If T1 and T2 are both pointer types of the same kind, or both array types
7130/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7131/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7132///
7133/// This function will typically be called in a loop that successively
7134/// "unwraps" pointer and pointer-to-member types to compare them at each
7135/// level.
7136///
7137/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7138/// C++20 [conv.qual], if permitted by the current language mode.
7139///
7140/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7141/// pair of types that can't be unwrapped further.
7143 bool AllowPiMismatch) const {
7144 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7145
7146 const auto *T1PtrType = T1->getAs<PointerType>();
7147 const auto *T2PtrType = T2->getAs<PointerType>();
7148 if (T1PtrType && T2PtrType) {
7149 T1 = T1PtrType->getPointeeType();
7150 T2 = T2PtrType->getPointeeType();
7151 return true;
7152 }
7153
7154 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7155 *T2MPType = T2->getAs<MemberPointerType>();
7156 T1MPType && T2MPType) {
7157 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7158 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7159 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7160 return false;
7161 if (T1MPType->getQualifier().getCanonical() !=
7162 T2MPType->getQualifier().getCanonical())
7163 return false;
7164 T1 = T1MPType->getPointeeType();
7165 T2 = T2MPType->getPointeeType();
7166 return true;
7167 }
7168
7169 if (getLangOpts().ObjC) {
7170 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7171 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7172 if (T1OPType && T2OPType) {
7173 T1 = T1OPType->getPointeeType();
7174 T2 = T2OPType->getPointeeType();
7175 return true;
7176 }
7177 }
7178
7179 // FIXME: Block pointers, too?
7180
7181 return false;
7182}
7183
7185 while (true) {
7186 Qualifiers Quals;
7187 T1 = getUnqualifiedArrayType(T1, Quals);
7188 T2 = getUnqualifiedArrayType(T2, Quals);
7189 if (hasSameType(T1, T2))
7190 return true;
7191 if (!UnwrapSimilarTypes(T1, T2))
7192 return false;
7193 }
7194}
7195
7197 while (true) {
7198 Qualifiers Quals1, Quals2;
7199 T1 = getUnqualifiedArrayType(T1, Quals1);
7200 T2 = getUnqualifiedArrayType(T2, Quals2);
7201
7202 Quals1.removeCVRQualifiers();
7203 Quals2.removeCVRQualifiers();
7204 if (Quals1 != Quals2)
7205 return false;
7206
7207 if (hasSameType(T1, T2))
7208 return true;
7209
7210 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7211 return false;
7212 }
7213}
7214
7217 SourceLocation NameLoc) const {
7218 switch (Name.getKind()) {
7221 // DNInfo work in progress: CHECKME: what about DNLoc?
7223 NameLoc);
7224
7227 // DNInfo work in progress: CHECKME: what about DNLoc?
7228 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7229 }
7230
7233 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7234 }
7235
7239 DeclarationName DName;
7240 if (const IdentifierInfo *II = TN.getIdentifier()) {
7241 DName = DeclarationNames.getIdentifier(II);
7242 return DeclarationNameInfo(DName, NameLoc);
7243 } else {
7244 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7245 // DNInfo work in progress: FIXME: source locations?
7246 DeclarationNameLoc DNLoc =
7248 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7249 }
7250 }
7251
7255 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7256 NameLoc);
7257 }
7258
7263 NameLoc);
7264 }
7267 NameLoc);
7270 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7271 }
7272 }
7273
7274 llvm_unreachable("bad template name kind!");
7275}
7276
7277static const TemplateArgument *
7279 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7280 if (!TP->hasDefaultArgument())
7281 return nullptr;
7282 return &TP->getDefaultArgument().getArgument();
7283 };
7284 switch (P->getKind()) {
7285 case NamedDecl::TemplateTypeParm:
7286 return handleParam(cast<TemplateTypeParmDecl>(P));
7287 case NamedDecl::NonTypeTemplateParm:
7288 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7289 case NamedDecl::TemplateTemplateParm:
7290 return handleParam(cast<TemplateTemplateParmDecl>(P));
7291 default:
7292 llvm_unreachable("Unexpected template parameter kind");
7293 }
7294}
7295
7297 bool IgnoreDeduced) const {
7298 while (std::optional<TemplateName> UnderlyingOrNone =
7299 Name.desugar(IgnoreDeduced))
7300 Name = *UnderlyingOrNone;
7301
7302 switch (Name.getKind()) {
7305 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7307
7308 // The canonical template name is the canonical template declaration.
7309 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7310 }
7311
7314 llvm_unreachable("cannot canonicalize unresolved template");
7315
7318 assert(DTN && "Non-dependent template names must refer to template decls.");
7319 NestedNameSpecifier Qualifier = DTN->getQualifier();
7320 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7321 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7322 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7323 /*HasTemplateKeyword=*/true});
7324 return Name;
7325 }
7326
7330 TemplateArgument canonArgPack =
7333 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7334 subst->getIndex(), subst->getFinal());
7335 }
7337 assert(IgnoreDeduced == false);
7339 DefaultArguments DefArgs = DTS->getDefaultArguments();
7340 TemplateName Underlying = DTS->getUnderlying();
7341
7342 TemplateName CanonUnderlying =
7343 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7344 bool NonCanonical = CanonUnderlying != Underlying;
7345 auto CanonArgs =
7346 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7347
7348 ArrayRef<NamedDecl *> Params =
7349 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7350 assert(CanonArgs.size() <= Params.size());
7351 // A deduced template name which deduces the same default arguments already
7352 // declared in the underlying template is the same template as the
7353 // underlying template. We need need to note any arguments which differ from
7354 // the corresponding declaration. If any argument differs, we must build a
7355 // deduced template name.
7356 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7358 if (!A)
7359 break;
7360 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7361 TemplateArgument &CanonDefArg = CanonArgs[I];
7362 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7363 continue;
7364 // Keep popping from the back any deault arguments which are the same.
7365 if (I == int(CanonArgs.size() - 1))
7366 CanonArgs.pop_back();
7367 NonCanonical = true;
7368 }
7369 return NonCanonical ? getDeducedTemplateName(
7370 CanonUnderlying,
7371 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7372 : Name;
7373 }
7377 llvm_unreachable("always sugar node");
7378 }
7379
7380 llvm_unreachable("bad template name!");
7381}
7382
7384 const TemplateName &Y,
7385 bool IgnoreDeduced) const {
7386 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7387 getCanonicalTemplateName(Y, IgnoreDeduced);
7388}
7389
7391 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7392 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7393 return false;
7395 return false;
7396 return true;
7397}
7398
7399bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7400 if (!XCE != !YCE)
7401 return false;
7402
7403 if (!XCE)
7404 return true;
7405
7406 llvm::FoldingSetNodeID XCEID, YCEID;
7407 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7408 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7409 return XCEID == YCEID;
7410}
7411
7413 const TypeConstraint *YTC) const {
7414 if (!XTC != !YTC)
7415 return false;
7416
7417 if (!XTC)
7418 return true;
7419
7420 auto *NCX = XTC->getNamedConcept();
7421 auto *NCY = YTC->getNamedConcept();
7422 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7423 return false;
7426 return false;
7428 if (XTC->getConceptReference()
7430 ->NumTemplateArgs !=
7432 return false;
7433
7434 // Compare slowly by profiling.
7435 //
7436 // We couldn't compare the profiling result for the template
7437 // args here. Consider the following example in different modules:
7438 //
7439 // template <__integer_like _Tp, C<_Tp> Sentinel>
7440 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7441 // return __t;
7442 // }
7443 //
7444 // When we compare the profiling result for `C<_Tp>` in different
7445 // modules, it will compare the type of `_Tp` in different modules.
7446 // However, the type of `_Tp` in different modules refer to different
7447 // types here naturally. So we couldn't compare the profiling result
7448 // for the template args directly.
7451}
7452
7454 const NamedDecl *Y) const {
7455 if (X->getKind() != Y->getKind())
7456 return false;
7457
7458 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7459 auto *TY = cast<TemplateTypeParmDecl>(Y);
7460 if (TX->isParameterPack() != TY->isParameterPack())
7461 return false;
7462 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7463 return false;
7464 return isSameTypeConstraint(TX->getTypeConstraint(),
7465 TY->getTypeConstraint());
7466 }
7467
7468 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7469 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7470 return TX->isParameterPack() == TY->isParameterPack() &&
7471 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7472 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7473 TY->getPlaceholderTypeConstraint());
7474 }
7475
7477 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7478 return TX->isParameterPack() == TY->isParameterPack() &&
7479 isSameTemplateParameterList(TX->getTemplateParameters(),
7480 TY->getTemplateParameters());
7481}
7482
7484 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7485 if (X->size() != Y->size())
7486 return false;
7487
7488 for (unsigned I = 0, N = X->size(); I != N; ++I)
7489 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7490 return false;
7491
7492 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7493}
7494
7496 const NamedDecl *Y) const {
7497 // If the type parameter isn't the same already, we don't need to check the
7498 // default argument further.
7499 if (!isSameTemplateParameter(X, Y))
7500 return false;
7501
7502 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7503 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7504 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7505 return false;
7506
7507 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7508 TTPY->getDefaultArgument().getArgument().getAsType());
7509 }
7510
7511 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7512 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7513 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7514 return false;
7515
7516 Expr *DefaultArgumentX =
7517 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7518 Expr *DefaultArgumentY =
7519 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7520 llvm::FoldingSetNodeID XID, YID;
7521 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7522 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7523 return XID == YID;
7524 }
7525
7526 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7527 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7528
7529 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7530 return false;
7531
7532 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7533 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7534 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7535}
7536
7538 const NestedNameSpecifier Y) {
7539 if (X == Y)
7540 return true;
7541 if (!X || !Y)
7542 return false;
7543
7544 auto Kind = X.getKind();
7545 if (Kind != Y.getKind())
7546 return false;
7547
7548 // FIXME: For namespaces and types, we're permitted to check that the entity
7549 // is named via the same tokens. We should probably do so.
7550 switch (Kind) {
7552 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7553 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7554 if (!declaresSameEntity(NamespaceX->getNamespace(),
7555 NamespaceY->getNamespace()))
7556 return false;
7557 return isSameQualifier(PrefixX, PrefixY);
7558 }
7560 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7561 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7562 return false;
7563 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7564 }
7568 return true;
7569 }
7570 llvm_unreachable("unhandled qualifier kind");
7571}
7572
7573static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7574 if (!A->getASTContext().getLangOpts().CUDA)
7575 return true; // Target attributes are overloadable in CUDA compilation only.
7576 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7577 return false;
7578 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7579 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7580 return true; // unattributed and __host__ functions are the same.
7581}
7582
7583/// Determine whether the attributes we can overload on are identical for A and
7584/// B. Will ignore any overloadable attrs represented in the type of A and B.
7586 const FunctionDecl *B) {
7587 // Note that pass_object_size attributes are represented in the function's
7588 // ExtParameterInfo, so we don't need to check them here.
7589
7590 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7591 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7592 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7593
7594 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7595 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7596 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7597
7598 // Return false if the number of enable_if attributes is different.
7599 if (!Cand1A || !Cand2A)
7600 return false;
7601
7602 Cand1ID.clear();
7603 Cand2ID.clear();
7604
7605 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7606 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7607
7608 // Return false if any of the enable_if expressions of A and B are
7609 // different.
7610 if (Cand1ID != Cand2ID)
7611 return false;
7612 }
7613 return hasSameCudaAttrs(A, B);
7614}
7615
7616bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7617 // Caution: this function is called by the AST reader during deserialization,
7618 // so it cannot rely on AST invariants being met. Non-trivial accessors
7619 // should be avoided, along with any traversal of redeclaration chains.
7620
7621 if (X == Y)
7622 return true;
7623
7624 if (X->getDeclName() != Y->getDeclName())
7625 return false;
7626
7627 // Must be in the same context.
7628 //
7629 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7630 // could be two different declarations of the same function. (We will fix the
7631 // semantic DC to refer to the primary definition after merging.)
7632 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7634 return false;
7635
7636 // If either X or Y are local to the owning module, they are only possible to
7637 // be the same entity if they are in the same module.
7638 if (X->isModuleLocal() || Y->isModuleLocal())
7639 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7640 return false;
7641
7642 // Two typedefs refer to the same entity if they have the same underlying
7643 // type.
7644 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7645 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7646 return hasSameType(TypedefX->getUnderlyingType(),
7647 TypedefY->getUnderlyingType());
7648
7649 // Must have the same kind.
7650 if (X->getKind() != Y->getKind())
7651 return false;
7652
7653 // Objective-C classes and protocols with the same name always match.
7655 return true;
7656
7658 // No need to handle these here: we merge them when adding them to the
7659 // template.
7660 return false;
7661 }
7662
7663 // Compatible tags match.
7664 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7665 const auto *TagY = cast<TagDecl>(Y);
7666 return (TagX->getTagKind() == TagY->getTagKind()) ||
7667 ((TagX->getTagKind() == TagTypeKind::Struct ||
7668 TagX->getTagKind() == TagTypeKind::Class ||
7669 TagX->getTagKind() == TagTypeKind::Interface) &&
7670 (TagY->getTagKind() == TagTypeKind::Struct ||
7671 TagY->getTagKind() == TagTypeKind::Class ||
7672 TagY->getTagKind() == TagTypeKind::Interface));
7673 }
7674
7675 // Functions with the same type and linkage match.
7676 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7677 // functions, etc.
7678 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7679 const auto *FuncY = cast<FunctionDecl>(Y);
7680 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7681 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7682 if (CtorX->getInheritedConstructor() &&
7683 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7684 CtorY->getInheritedConstructor().getConstructor()))
7685 return false;
7686 }
7687
7688 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7689 return false;
7690
7691 // Multiversioned functions with different feature strings are represented
7692 // as separate declarations.
7693 if (FuncX->isMultiVersion()) {
7694 const auto *TAX = FuncX->getAttr<TargetAttr>();
7695 const auto *TAY = FuncY->getAttr<TargetAttr>();
7696 assert(TAX && TAY && "Multiversion Function without target attribute");
7697
7698 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7699 return false;
7700 }
7701
7702 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7703 // not the same entity if they are constrained.
7704 if ((FuncX->isMemberLikeConstrainedFriend() ||
7705 FuncY->isMemberLikeConstrainedFriend()) &&
7706 !FuncX->getLexicalDeclContext()->Equals(
7707 FuncY->getLexicalDeclContext())) {
7708 return false;
7709 }
7710
7711 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7712 FuncY->getTrailingRequiresClause()))
7713 return false;
7714
7715 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7716 // Map to the first declaration that we've already merged into this one.
7717 // The TSI of redeclarations might not match (due to calling conventions
7718 // being inherited onto the type but not the TSI), but the TSI type of
7719 // the first declaration of the function should match across modules.
7720 FD = FD->getCanonicalDecl();
7721 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7722 : FD->getType();
7723 };
7724 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7725 if (!hasSameType(XT, YT)) {
7726 // We can get functions with different types on the redecl chain in C++17
7727 // if they have differing exception specifications and at least one of
7728 // the excpetion specs is unresolved.
7729 auto *XFPT = XT->getAs<FunctionProtoType>();
7730 auto *YFPT = YT->getAs<FunctionProtoType>();
7731 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7732 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7735 return true;
7736 return false;
7737 }
7738
7739 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7740 hasSameOverloadableAttrs(FuncX, FuncY);
7741 }
7742
7743 // Variables with the same type and linkage match.
7744 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7745 const auto *VarY = cast<VarDecl>(Y);
7746 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7747 // During deserialization, we might compare variables before we load
7748 // their types. Assume the types will end up being the same.
7749 if (VarX->getType().isNull() || VarY->getType().isNull())
7750 return true;
7751
7752 if (hasSameType(VarX->getType(), VarY->getType()))
7753 return true;
7754
7755 // We can get decls with different types on the redecl chain. Eg.
7756 // template <typename T> struct S { static T Var[]; }; // #1
7757 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7758 // Only? happens when completing an incomplete array type. In this case
7759 // when comparing #1 and #2 we should go through their element type.
7760 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7761 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7762 if (!VarXTy || !VarYTy)
7763 return false;
7764 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7765 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7766 }
7767 return false;
7768 }
7769
7770 // Namespaces with the same name and inlinedness match.
7771 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7772 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7773 return NamespaceX->isInline() == NamespaceY->isInline();
7774 }
7775
7776 // Identical template names and kinds match if their template parameter lists
7777 // and patterns match.
7778 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7779 const auto *TemplateY = cast<TemplateDecl>(Y);
7780
7781 // ConceptDecl wouldn't be the same if their constraint expression differs.
7782 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7783 const auto *ConceptY = cast<ConceptDecl>(Y);
7784 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7785 ConceptY->getConstraintExpr()))
7786 return false;
7787 }
7788
7789 return isSameEntity(TemplateX->getTemplatedDecl(),
7790 TemplateY->getTemplatedDecl()) &&
7791 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7792 TemplateY->getTemplateParameters());
7793 }
7794
7795 // Fields with the same name and the same type match.
7796 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7797 const auto *FDY = cast<FieldDecl>(Y);
7798 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7799 return hasSameType(FDX->getType(), FDY->getType());
7800 }
7801
7802 // Indirect fields with the same target field match.
7803 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7804 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7805 return IFDX->getAnonField()->getCanonicalDecl() ==
7806 IFDY->getAnonField()->getCanonicalDecl();
7807 }
7808
7809 // Enumerators with the same name match.
7811 // FIXME: Also check the value is odr-equivalent.
7812 return true;
7813
7814 // Using shadow declarations with the same target match.
7815 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7816 const auto *USY = cast<UsingShadowDecl>(Y);
7817 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7818 }
7819
7820 // Using declarations with the same qualifier match. (We already know that
7821 // the name matches.)
7822 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7823 const auto *UY = cast<UsingDecl>(Y);
7824 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7825 UX->hasTypename() == UY->hasTypename() &&
7826 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7827 }
7828 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7829 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7830 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7831 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7832 }
7833 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7834 return isSameQualifier(
7835 UX->getQualifier(),
7836 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7837 }
7838
7839 // Using-pack declarations are only created by instantiation, and match if
7840 // they're instantiated from matching UnresolvedUsing...Decls.
7841 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7842 return declaresSameEntity(
7843 UX->getInstantiatedFromUsingDecl(),
7844 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7845 }
7846
7847 // Namespace alias definitions with the same target match.
7848 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7849 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7850 return NAX->getNamespace()->Equals(NAY->getNamespace());
7851 }
7852
7853 return false;
7854}
7855
7858 switch (Arg.getKind()) {
7860 return Arg;
7861
7863 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7864 Arg.getIsDefaulted());
7865
7867 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7869 Arg.getIsDefaulted());
7870 }
7871
7874 /*isNullPtr*/ true, Arg.getIsDefaulted());
7875
7878 Arg.getIsDefaulted());
7879
7881 return TemplateArgument(
7884
7887
7889 return TemplateArgument(*this,
7892
7895 /*isNullPtr*/ false, Arg.getIsDefaulted());
7896
7898 bool AnyNonCanonArgs = false;
7899 auto CanonArgs = ::getCanonicalTemplateArguments(
7900 *this, Arg.pack_elements(), AnyNonCanonArgs);
7901 if (!AnyNonCanonArgs)
7902 return Arg;
7904 const_cast<ASTContext &>(*this), CanonArgs);
7905 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7906 return NewArg;
7907 }
7908 }
7909
7910 // Silence GCC warning
7911 llvm_unreachable("Unhandled template argument kind");
7912}
7913
7915 const TemplateArgument &Arg2) const {
7916 if (Arg1.getKind() != Arg2.getKind())
7917 return false;
7918
7919 switch (Arg1.getKind()) {
7921 llvm_unreachable("Comparing NULL template argument");
7922
7924 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7925
7927 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7929
7931 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7932
7937
7939 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7940 Arg2.getAsIntegral());
7941
7943 return Arg1.structurallyEquals(Arg2);
7944
7946 llvm::FoldingSetNodeID ID1, ID2;
7947 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7948 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7949 return ID1 == ID2;
7950 }
7951
7953 return llvm::equal(
7954 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7955 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7956 return isSameTemplateArgument(Arg1, Arg2);
7957 });
7958 }
7959
7960 llvm_unreachable("Unhandled template argument kind");
7961}
7962
7964 // Handle the non-qualified case efficiently.
7965 if (!T.hasLocalQualifiers()) {
7966 // Handle the common positive case fast.
7967 if (const auto *AT = dyn_cast<ArrayType>(T))
7968 return AT;
7969 }
7970
7971 // Handle the common negative case fast.
7972 if (!isa<ArrayType>(T.getCanonicalType()))
7973 return nullptr;
7974
7975 // Apply any qualifiers from the array type to the element type. This
7976 // implements C99 6.7.3p8: "If the specification of an array type includes
7977 // any type qualifiers, the element type is so qualified, not the array type."
7978
7979 // If we get here, we either have type qualifiers on the type, or we have
7980 // sugar such as a typedef in the way. If we have type qualifiers on the type
7981 // we must propagate them down into the element type.
7982
7983 SplitQualType split = T.getSplitDesugaredType();
7984 Qualifiers qs = split.Quals;
7985
7986 // If we have a simple case, just return now.
7987 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7988 if (!ATy || qs.empty())
7989 return ATy;
7990
7991 // Otherwise, we have an array and we have qualifiers on it. Push the
7992 // qualifiers into the array element type and return a new array type.
7993 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7994
7995 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7996 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7997 CAT->getSizeExpr(),
7998 CAT->getSizeModifier(),
7999 CAT->getIndexTypeCVRQualifiers()));
8000 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8002 IAT->getSizeModifier(),
8003 IAT->getIndexTypeCVRQualifiers()));
8004
8005 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8007 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8008 DSAT->getIndexTypeCVRQualifiers()));
8009
8010 const auto *VAT = cast<VariableArrayType>(ATy);
8011 return cast<ArrayType>(
8012 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8013 VAT->getIndexTypeCVRQualifiers()));
8014}
8015
8017 if (getLangOpts().HLSL && T->isConstantArrayType())
8018 return getArrayParameterType(T);
8019 if (T->isArrayType() || T->isFunctionType())
8020 return getDecayedType(T);
8021 return T;
8022}
8023
8027 return T.getUnqualifiedType();
8028}
8029
8031 // C++ [except.throw]p3:
8032 // A throw-expression initializes a temporary object, called the exception
8033 // object, the type of which is determined by removing any top-level
8034 // cv-qualifiers from the static type of the operand of throw and adjusting
8035 // the type from "array of T" or "function returning T" to "pointer to T"
8036 // or "pointer to function returning T", [...]
8038 if (T->isArrayType() || T->isFunctionType())
8039 T = getDecayedType(T);
8040 return T.getUnqualifiedType();
8041}
8042
8043/// getArrayDecayedType - Return the properly qualified result of decaying the
8044/// specified array type to a pointer. This operation is non-trivial when
8045/// handling typedefs etc. The canonical type of "T" must be an array type,
8046/// this returns a pointer to a properly qualified element of the array.
8047///
8048/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8050 // Get the element type with 'getAsArrayType' so that we don't lose any
8051 // typedefs in the element type of the array. This also handles propagation
8052 // of type qualifiers from the array type into the element type if present
8053 // (C99 6.7.3p8).
8054 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8055 assert(PrettyArrayType && "Not an array type!");
8056
8057 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8058
8059 // int x[restrict 4] -> int *restrict
8061 PrettyArrayType->getIndexTypeQualifiers());
8062
8063 // int x[_Nullable] -> int * _Nullable
8064 if (auto Nullability = Ty->getNullability()) {
8065 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8066 Result, Result);
8067 }
8068 return Result;
8069}
8070
8072 return getBaseElementType(array->getElementType());
8073}
8074
8076 Qualifiers qs;
8077 while (true) {
8078 SplitQualType split = type.getSplitDesugaredType();
8079 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8080 if (!array) break;
8081
8082 type = array->getElementType();
8084 }
8085
8086 return getQualifiedType(type, qs);
8087}
8088
8089/// getConstantArrayElementCount - Returns number of constant array elements.
8090uint64_t
8092 uint64_t ElementCount = 1;
8093 do {
8094 ElementCount *= CA->getZExtSize();
8095 CA = dyn_cast_or_null<ConstantArrayType>(
8097 } while (CA);
8098 return ElementCount;
8099}
8100
8102 const ArrayInitLoopExpr *AILE) const {
8103 if (!AILE)
8104 return 0;
8105
8106 uint64_t ElementCount = 1;
8107
8108 do {
8109 ElementCount *= AILE->getArraySize().getZExtValue();
8110 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8111 } while (AILE);
8112
8113 return ElementCount;
8114}
8115
8116/// getFloatingRank - Return a relative rank for floating point types.
8117/// This routine will assert if passed a built-in type that isn't a float.
8119 if (const auto *CT = T->getAs<ComplexType>())
8120 return getFloatingRank(CT->getElementType());
8121
8122 switch (T->castAs<BuiltinType>()->getKind()) {
8123 default: llvm_unreachable("getFloatingRank(): not a floating type");
8124 case BuiltinType::Float16: return Float16Rank;
8125 case BuiltinType::Half: return HalfRank;
8126 case BuiltinType::Float: return FloatRank;
8127 case BuiltinType::Double: return DoubleRank;
8128 case BuiltinType::LongDouble: return LongDoubleRank;
8129 case BuiltinType::Float128: return Float128Rank;
8130 case BuiltinType::BFloat16: return BFloat16Rank;
8131 case BuiltinType::Ibm128: return Ibm128Rank;
8132 }
8133}
8134
8135/// getFloatingTypeOrder - Compare the rank of the two specified floating
8136/// point types, ignoring the domain of the type (i.e. 'double' ==
8137/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8138/// LHS < RHS, return -1.
8140 FloatingRank LHSR = getFloatingRank(LHS);
8141 FloatingRank RHSR = getFloatingRank(RHS);
8142
8143 if (LHSR == RHSR)
8144 return 0;
8145 if (LHSR > RHSR)
8146 return 1;
8147 return -1;
8148}
8149
8152 return 0;
8153 return getFloatingTypeOrder(LHS, RHS);
8154}
8155
8156/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8157/// routine will assert if passed a built-in type that isn't an integer or enum,
8158/// or if it is not canonicalized.
8159unsigned ASTContext::getIntegerRank(const Type *T) const {
8160 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8161
8162 // Results in this 'losing' to any type of the same size, but winning if
8163 // larger.
8164 if (const auto *EIT = dyn_cast<BitIntType>(T))
8165 return 0 + (EIT->getNumBits() << 3);
8166
8167 switch (cast<BuiltinType>(T)->getKind()) {
8168 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8169 case BuiltinType::Bool:
8170 return 1 + (getIntWidth(BoolTy) << 3);
8171 case BuiltinType::Char_S:
8172 case BuiltinType::Char_U:
8173 case BuiltinType::SChar:
8174 case BuiltinType::UChar:
8175 return 2 + (getIntWidth(CharTy) << 3);
8176 case BuiltinType::Short:
8177 case BuiltinType::UShort:
8178 return 3 + (getIntWidth(ShortTy) << 3);
8179 case BuiltinType::Int:
8180 case BuiltinType::UInt:
8181 return 4 + (getIntWidth(IntTy) << 3);
8182 case BuiltinType::Long:
8183 case BuiltinType::ULong:
8184 return 5 + (getIntWidth(LongTy) << 3);
8185 case BuiltinType::LongLong:
8186 case BuiltinType::ULongLong:
8187 return 6 + (getIntWidth(LongLongTy) << 3);
8188 case BuiltinType::Int128:
8189 case BuiltinType::UInt128:
8190 return 7 + (getIntWidth(Int128Ty) << 3);
8191
8192 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8193 // their underlying types" [c++20 conv.rank]
8194 case BuiltinType::Char8:
8195 return getIntegerRank(UnsignedCharTy.getTypePtr());
8196 case BuiltinType::Char16:
8197 return getIntegerRank(
8198 getFromTargetType(Target->getChar16Type()).getTypePtr());
8199 case BuiltinType::Char32:
8200 return getIntegerRank(
8201 getFromTargetType(Target->getChar32Type()).getTypePtr());
8202 case BuiltinType::WChar_S:
8203 case BuiltinType::WChar_U:
8204 return getIntegerRank(
8205 getFromTargetType(Target->getWCharType()).getTypePtr());
8206 }
8207}
8208
8209/// Whether this is a promotable bitfield reference according
8210/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8211///
8212/// \returns the type this bit-field will promote to, or NULL if no
8213/// promotion occurs.
8215 if (E->isTypeDependent() || E->isValueDependent())
8216 return {};
8217
8218 // C++ [conv.prom]p5:
8219 // If the bit-field has an enumerated type, it is treated as any other
8220 // value of that type for promotion purposes.
8222 return {};
8223
8224 // FIXME: We should not do this unless E->refersToBitField() is true. This
8225 // matters in C where getSourceBitField() will find bit-fields for various
8226 // cases where the source expression is not a bit-field designator.
8227
8228 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8229 if (!Field)
8230 return {};
8231
8232 QualType FT = Field->getType();
8233
8234 uint64_t BitWidth = Field->getBitWidthValue();
8235 uint64_t IntSize = getTypeSize(IntTy);
8236 // C++ [conv.prom]p5:
8237 // A prvalue for an integral bit-field can be converted to a prvalue of type
8238 // int if int can represent all the values of the bit-field; otherwise, it
8239 // can be converted to unsigned int if unsigned int can represent all the
8240 // values of the bit-field. If the bit-field is larger yet, no integral
8241 // promotion applies to it.
8242 // C11 6.3.1.1/2:
8243 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8244 // If an int can represent all values of the original type (as restricted by
8245 // the width, for a bit-field), the value is converted to an int; otherwise,
8246 // it is converted to an unsigned int.
8247 //
8248 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8249 // We perform that promotion here to match GCC and C++.
8250 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8251 // greater than that of 'int'. We perform that promotion to match GCC.
8252 //
8253 // C23 6.3.1.1p2:
8254 // The value from a bit-field of a bit-precise integer type is converted to
8255 // the corresponding bit-precise integer type. (The rest is the same as in
8256 // C11.)
8257 if (QualType QT = Field->getType(); QT->isBitIntType())
8258 return QT;
8259
8260 if (BitWidth < IntSize)
8261 return IntTy;
8262
8263 if (BitWidth == IntSize)
8264 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8265
8266 // Bit-fields wider than int are not subject to promotions, and therefore act
8267 // like the base type. GCC has some weird bugs in this area that we
8268 // deliberately do not follow (GCC follows a pre-standard resolution to
8269 // C's DR315 which treats bit-width as being part of the type, and this leaks
8270 // into their semantics in some cases).
8271 return {};
8272}
8273
8274/// getPromotedIntegerType - Returns the type that Promotable will
8275/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8276/// integer type.
8278 assert(!Promotable.isNull());
8279 assert(isPromotableIntegerType(Promotable));
8280 if (const auto *ED = Promotable->getAsEnumDecl())
8281 return ED->getPromotionType();
8282
8283 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8284 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8285 // (3.9.1) can be converted to a prvalue of the first of the following
8286 // types that can represent all the values of its underlying type:
8287 // int, unsigned int, long int, unsigned long int, long long int, or
8288 // unsigned long long int [...]
8289 // FIXME: Is there some better way to compute this?
8290 if (BT->getKind() == BuiltinType::WChar_S ||
8291 BT->getKind() == BuiltinType::WChar_U ||
8292 BT->getKind() == BuiltinType::Char8 ||
8293 BT->getKind() == BuiltinType::Char16 ||
8294 BT->getKind() == BuiltinType::Char32) {
8295 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8296 uint64_t FromSize = getTypeSize(BT);
8297 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8299 for (const auto &PT : PromoteTypes) {
8300 uint64_t ToSize = getTypeSize(PT);
8301 if (FromSize < ToSize ||
8302 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8303 return PT;
8304 }
8305 llvm_unreachable("char type should fit into long long");
8306 }
8307 }
8308
8309 // At this point, we should have a signed or unsigned integer type.
8310 if (Promotable->isSignedIntegerType())
8311 return IntTy;
8312 uint64_t PromotableSize = getIntWidth(Promotable);
8313 uint64_t IntSize = getIntWidth(IntTy);
8314 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8315 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8316}
8317
8318/// Recurses in pointer/array types until it finds an objc retainable
8319/// type and returns its ownership.
8321 while (!T.isNull()) {
8322 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8323 return T.getObjCLifetime();
8324 if (T->isArrayType())
8326 else if (const auto *PT = T->getAs<PointerType>())
8327 T = PT->getPointeeType();
8328 else if (const auto *RT = T->getAs<ReferenceType>())
8329 T = RT->getPointeeType();
8330 else
8331 break;
8332 }
8333
8334 return Qualifiers::OCL_None;
8335}
8336
8337static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8338 // Incomplete enum types are not treated as integer types.
8339 // FIXME: In C++, enum types are never integer types.
8340 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8341 if (ED->isComplete() && !ED->isScoped())
8342 return ED->getIntegerType().getTypePtr();
8343 return nullptr;
8344}
8345
8346/// getIntegerTypeOrder - Returns the highest ranked integer type:
8347/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8348/// LHS < RHS, return -1.
8350 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8351 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8352
8353 // Unwrap enums to their underlying type.
8354 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8355 LHSC = getIntegerTypeForEnum(ET);
8356 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8357 RHSC = getIntegerTypeForEnum(ET);
8358
8359 if (LHSC == RHSC) return 0;
8360
8361 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8362 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8363
8364 unsigned LHSRank = getIntegerRank(LHSC);
8365 unsigned RHSRank = getIntegerRank(RHSC);
8366
8367 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8368 if (LHSRank == RHSRank) return 0;
8369 return LHSRank > RHSRank ? 1 : -1;
8370 }
8371
8372 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8373 if (LHSUnsigned) {
8374 // If the unsigned [LHS] type is larger, return it.
8375 if (LHSRank >= RHSRank)
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
8384 // If the unsigned [RHS] type is larger, return it.
8385 if (RHSRank >= LHSRank)
8386 return -1;
8387
8388 // If the signed type can represent all values of the unsigned type, it
8389 // wins. Because we are dealing with 2's complement and types that are
8390 // powers of two larger than each other, this is always safe.
8391 return 1;
8392}
8393
8395 if (CFConstantStringTypeDecl)
8396 return CFConstantStringTypeDecl;
8397
8398 assert(!CFConstantStringTagDecl &&
8399 "tag and typedef should be initialized together");
8400 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8401 CFConstantStringTagDecl->startDefinition();
8402
8403 struct {
8404 QualType Type;
8405 const char *Name;
8406 } Fields[5];
8407 unsigned Count = 0;
8408
8409 /// Objective-C ABI
8410 ///
8411 /// typedef struct __NSConstantString_tag {
8412 /// const int *isa;
8413 /// int flags;
8414 /// const char *str;
8415 /// long length;
8416 /// } __NSConstantString;
8417 ///
8418 /// Swift ABI (4.1, 4.2)
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 /// uint32_t _length;
8426 /// } __NSConstantString;
8427 ///
8428 /// Swift ABI (5.0)
8429 ///
8430 /// typedef struct __NSConstantString_tag {
8431 /// uintptr_t _cfisa;
8432 /// uintptr_t _swift_rc;
8433 /// _Atomic(uint64_t) _cfinfoa;
8434 /// const char *_ptr;
8435 /// uintptr_t _length;
8436 /// } __NSConstantString;
8437
8438 const auto CFRuntime = getLangOpts().CFRuntime;
8439 if (static_cast<unsigned>(CFRuntime) <
8440 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8441 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8442 Fields[Count++] = { IntTy, "flags" };
8443 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8444 Fields[Count++] = { LongTy, "length" };
8445 } else {
8446 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8447 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8448 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8449 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8452 Fields[Count++] = { IntTy, "_ptr" };
8453 else
8454 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8455 }
8456
8457 // Create fields
8458 for (unsigned i = 0; i < Count; ++i) {
8459 FieldDecl *Field =
8460 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8461 SourceLocation(), &Idents.get(Fields[i].Name),
8462 Fields[i].Type, /*TInfo=*/nullptr,
8463 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8464 Field->setAccess(AS_public);
8465 CFConstantStringTagDecl->addDecl(Field);
8466 }
8467
8468 CFConstantStringTagDecl->completeDefinition();
8469 // This type is designed to be compatible with NSConstantString, but cannot
8470 // use the same name, since NSConstantString is an interface.
8471 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8472 CFConstantStringTypeDecl =
8473 buildImplicitTypedef(tagType, "__NSConstantString");
8474
8475 return CFConstantStringTypeDecl;
8476}
8477
8479 if (!CFConstantStringTagDecl)
8480 getCFConstantStringDecl(); // Build the tag and the typedef.
8481 return CFConstantStringTagDecl;
8482}
8483
8484// getCFConstantStringType - Return the type used for constant CFStrings.
8489
8491 if (ObjCSuperType.isNull()) {
8492 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8493 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8494 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8495 }
8496 return ObjCSuperType;
8497}
8498
8500 const auto *TT = T->castAs<TypedefType>();
8501 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8502 CFConstantStringTagDecl = TT->castAsRecordDecl();
8503}
8504
8506 if (BlockDescriptorType)
8507 return getCanonicalTagType(BlockDescriptorType);
8508
8509 RecordDecl *RD;
8510 // FIXME: Needs the FlagAppleBlock bit.
8511 RD = buildImplicitRecord("__block_descriptor");
8512 RD->startDefinition();
8513
8514 QualType FieldTypes[] = {
8517 };
8518
8519 static const char *const FieldNames[] = {
8520 "reserved",
8521 "Size"
8522 };
8523
8524 for (size_t i = 0; i < 2; ++i) {
8526 *this, RD, SourceLocation(), SourceLocation(),
8527 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8528 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8529 Field->setAccess(AS_public);
8530 RD->addDecl(Field);
8531 }
8532
8533 RD->completeDefinition();
8534
8535 BlockDescriptorType = RD;
8536
8537 return getCanonicalTagType(BlockDescriptorType);
8538}
8539
8541 if (BlockDescriptorExtendedType)
8542 return getCanonicalTagType(BlockDescriptorExtendedType);
8543
8544 RecordDecl *RD;
8545 // FIXME: Needs the FlagAppleBlock bit.
8546 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8547 RD->startDefinition();
8548
8549 QualType FieldTypes[] = {
8554 };
8555
8556 static const char *const FieldNames[] = {
8557 "reserved",
8558 "Size",
8559 "CopyFuncPtr",
8560 "DestroyFuncPtr"
8561 };
8562
8563 for (size_t i = 0; i < 4; ++i) {
8565 *this, RD, SourceLocation(), SourceLocation(),
8566 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8567 /*BitWidth=*/nullptr,
8568 /*Mutable=*/false, ICIS_NoInit);
8569 Field->setAccess(AS_public);
8570 RD->addDecl(Field);
8571 }
8572
8573 RD->completeDefinition();
8574
8575 BlockDescriptorExtendedType = RD;
8576 return getCanonicalTagType(BlockDescriptorExtendedType);
8577}
8578
8580 const auto *BT = dyn_cast<BuiltinType>(T);
8581
8582 if (!BT) {
8583 if (isa<PipeType>(T))
8584 return OCLTK_Pipe;
8585
8586 return OCLTK_Default;
8587 }
8588
8589 switch (BT->getKind()) {
8590#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8591 case BuiltinType::Id: \
8592 return OCLTK_Image;
8593#include "clang/Basic/OpenCLImageTypes.def"
8594
8595 case BuiltinType::OCLClkEvent:
8596 return OCLTK_ClkEvent;
8597
8598 case BuiltinType::OCLEvent:
8599 return OCLTK_Event;
8600
8601 case BuiltinType::OCLQueue:
8602 return OCLTK_Queue;
8603
8604 case BuiltinType::OCLReserveID:
8605 return OCLTK_ReserveID;
8606
8607 case BuiltinType::OCLSampler:
8608 return OCLTK_Sampler;
8609
8610 default:
8611 return OCLTK_Default;
8612 }
8613}
8614
8616 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8617}
8618
8619/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8620/// requires copy/dispose. Note that this must match the logic
8621/// in buildByrefHelpers.
8623 const VarDecl *D) {
8624 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8625 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8626 if (!copyExpr && record->hasTrivialDestructor()) return false;
8627
8628 return true;
8629 }
8630
8632 return true;
8633
8634 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8635 // move or destroy.
8637 return true;
8638
8639 if (!Ty->isObjCRetainableType()) return false;
8640
8641 Qualifiers qs = Ty.getQualifiers();
8642
8643 // If we have lifetime, that dominates.
8644 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8645 switch (lifetime) {
8646 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8647
8648 // These are just bits as far as the runtime is concerned.
8651 return false;
8652
8653 // These cases should have been taken care of when checking the type's
8654 // non-triviality.
8657 llvm_unreachable("impossible");
8658 }
8659 llvm_unreachable("fell out of lifetime switch!");
8660 }
8661 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8663}
8664
8666 Qualifiers::ObjCLifetime &LifeTime,
8667 bool &HasByrefExtendedLayout) const {
8668 if (!getLangOpts().ObjC ||
8669 getLangOpts().getGC() != LangOptions::NonGC)
8670 return false;
8671
8672 HasByrefExtendedLayout = false;
8673 if (Ty->isRecordType()) {
8674 HasByrefExtendedLayout = true;
8675 LifeTime = Qualifiers::OCL_None;
8676 } else if ((LifeTime = Ty.getObjCLifetime())) {
8677 // Honor the ARC qualifiers.
8678 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8679 // The MRR rule.
8681 } else {
8682 LifeTime = Qualifiers::OCL_None;
8683 }
8684 return true;
8685}
8686
8688 assert(Target && "Expected target to be initialized");
8689 const llvm::Triple &T = Target->getTriple();
8690 // Windows is LLP64 rather than LP64
8691 if (T.isOSWindows() && T.isArch64Bit())
8692 return UnsignedLongLongTy;
8693 return UnsignedLongTy;
8694}
8695
8697 assert(Target && "Expected target to be initialized");
8698 const llvm::Triple &T = Target->getTriple();
8699 // Windows is LLP64 rather than LP64
8700 if (T.isOSWindows() && T.isArch64Bit())
8701 return LongLongTy;
8702 return LongTy;
8703}
8704
8706 if (!ObjCInstanceTypeDecl)
8707 ObjCInstanceTypeDecl =
8708 buildImplicitTypedef(getObjCIdType(), "instancetype");
8709 return ObjCInstanceTypeDecl;
8710}
8711
8712// This returns true if a type has been typedefed to BOOL:
8713// typedef <type> BOOL;
8715 if (const auto *TT = dyn_cast<TypedefType>(T))
8716 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8717 return II->isStr("BOOL");
8718
8719 return false;
8720}
8721
8722/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8723/// purpose.
8725 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8726 return CharUnits::Zero();
8727
8729
8730 // Make all integer and enum types at least as large as an int
8731 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8732 sz = std::max(sz, getTypeSizeInChars(IntTy));
8733 // Treat arrays as pointers, since that's how they're passed in.
8734 else if (type->isArrayType())
8736 return sz;
8737}
8738
8745
8748 if (!VD->isInline())
8750
8751 // In almost all cases, it's a weak definition.
8752 auto *First = VD->getFirstDecl();
8753 if (First->isInlineSpecified() || !First->isStaticDataMember())
8755
8756 // If there's a file-context declaration in this translation unit, it's a
8757 // non-discardable definition.
8758 for (auto *D : VD->redecls())
8760 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8762
8763 // If we've not seen one yet, we don't know.
8765}
8766
8767static std::string charUnitsToString(const CharUnits &CU) {
8768 return llvm::itostr(CU.getQuantity());
8769}
8770
8771/// getObjCEncodingForBlock - Return the encoded type for this block
8772/// declaration.
8774 std::string S;
8775
8776 const BlockDecl *Decl = Expr->getBlockDecl();
8777 QualType BlockTy =
8779 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8780 // Encode result type.
8781 if (getLangOpts().EncodeExtendedBlockSig)
8783 true /*Extended*/);
8784 else
8785 getObjCEncodingForType(BlockReturnTy, S);
8786 // Compute size of all parameters.
8787 // Start with computing size of a pointer in number of bytes.
8788 // FIXME: There might(should) be a better way of doing this computation!
8790 CharUnits ParmOffset = PtrSize;
8791 for (auto *PI : Decl->parameters()) {
8792 QualType PType = PI->getType();
8794 if (sz.isZero())
8795 continue;
8796 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8797 ParmOffset += sz;
8798 }
8799 // Size of the argument frame
8800 S += charUnitsToString(ParmOffset);
8801 // Block pointer and offset.
8802 S += "@?0";
8803
8804 // Argument types.
8805 ParmOffset = PtrSize;
8806 for (auto *PVDecl : Decl->parameters()) {
8807 QualType PType = PVDecl->getOriginalType();
8808 if (const auto *AT =
8809 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8810 // Use array's original type only if it has known number of
8811 // elements.
8812 if (!isa<ConstantArrayType>(AT))
8813 PType = PVDecl->getType();
8814 } else if (PType->isFunctionType())
8815 PType = PVDecl->getType();
8816 if (getLangOpts().EncodeExtendedBlockSig)
8818 S, true /*Extended*/);
8819 else
8820 getObjCEncodingForType(PType, S);
8821 S += charUnitsToString(ParmOffset);
8822 ParmOffset += getObjCEncodingTypeSize(PType);
8823 }
8824
8825 return S;
8826}
8827
8828std::string
8830 std::string S;
8831 // Encode result type.
8832 getObjCEncodingForType(Decl->getReturnType(), S);
8833 CharUnits ParmOffset;
8834 // Compute size of all parameters.
8835 for (auto *PI : Decl->parameters()) {
8836 QualType PType = PI->getType();
8838 if (sz.isZero())
8839 continue;
8840
8841 assert(sz.isPositive() &&
8842 "getObjCEncodingForFunctionDecl - Incomplete param type");
8843 ParmOffset += sz;
8844 }
8845 S += charUnitsToString(ParmOffset);
8846 ParmOffset = CharUnits::Zero();
8847
8848 // Argument types.
8849 for (auto *PVDecl : Decl->parameters()) {
8850 QualType PType = PVDecl->getOriginalType();
8851 if (const auto *AT =
8852 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8853 // Use array's original type only if it has known number of
8854 // elements.
8855 if (!isa<ConstantArrayType>(AT))
8856 PType = PVDecl->getType();
8857 } else if (PType->isFunctionType())
8858 PType = PVDecl->getType();
8859 getObjCEncodingForType(PType, S);
8860 S += charUnitsToString(ParmOffset);
8861 ParmOffset += getObjCEncodingTypeSize(PType);
8862 }
8863
8864 return S;
8865}
8866
8867/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8868/// method parameter or return type. If Extended, include class names and
8869/// block object types.
8871 QualType T, std::string& S,
8872 bool Extended) const {
8873 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8875 // Encode parameter type.
8876 ObjCEncOptions Options = ObjCEncOptions()
8877 .setExpandPointedToStructures()
8878 .setExpandStructures()
8879 .setIsOutermostType();
8880 if (Extended)
8881 Options.setEncodeBlockParameters().setEncodeClassNames();
8882 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8883}
8884
8885/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8886/// declaration.
8888 bool Extended) const {
8889 // FIXME: This is not very efficient.
8890 // Encode return type.
8891 std::string S;
8892 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8893 Decl->getReturnType(), S, Extended);
8894 // Compute size of all parameters.
8895 // Start with computing size of a pointer in number of bytes.
8896 // FIXME: There might(should) be a better way of doing this computation!
8898 // The first two arguments (self and _cmd) are pointers; account for
8899 // their size.
8900 CharUnits ParmOffset = 2 * PtrSize;
8901 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8902 E = Decl->sel_param_end(); PI != E; ++PI) {
8903 QualType PType = (*PI)->getType();
8905 if (sz.isZero())
8906 continue;
8907
8908 assert(sz.isPositive() &&
8909 "getObjCEncodingForMethodDecl - Incomplete param type");
8910 ParmOffset += sz;
8911 }
8912 S += charUnitsToString(ParmOffset);
8913 S += "@0:";
8914 S += charUnitsToString(PtrSize);
8915
8916 // Argument types.
8917 ParmOffset = 2 * PtrSize;
8918 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8919 E = Decl->sel_param_end(); PI != E; ++PI) {
8920 const ParmVarDecl *PVDecl = *PI;
8921 QualType PType = PVDecl->getOriginalType();
8922 if (const auto *AT =
8923 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8924 // Use array's original type only if it has known number of
8925 // elements.
8926 if (!isa<ConstantArrayType>(AT))
8927 PType = PVDecl->getType();
8928 } else if (PType->isFunctionType())
8929 PType = PVDecl->getType();
8931 PType, S, Extended);
8932 S += charUnitsToString(ParmOffset);
8933 ParmOffset += getObjCEncodingTypeSize(PType);
8934 }
8935
8936 return S;
8937}
8938
8941 const ObjCPropertyDecl *PD,
8942 const Decl *Container) const {
8943 if (!Container)
8944 return nullptr;
8945 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8946 for (auto *PID : CID->property_impls())
8947 if (PID->getPropertyDecl() == PD)
8948 return PID;
8949 } else {
8950 const auto *OID = cast<ObjCImplementationDecl>(Container);
8951 for (auto *PID : OID->property_impls())
8952 if (PID->getPropertyDecl() == PD)
8953 return PID;
8954 }
8955 return nullptr;
8956}
8957
8958/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8959/// property declaration. If non-NULL, Container must be either an
8960/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8961/// NULL when getting encodings for protocol properties.
8962/// Property attributes are stored as a comma-delimited C string. The simple
8963/// attributes readonly and bycopy are encoded as single characters. The
8964/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8965/// encoded as single characters, followed by an identifier. Property types
8966/// are also encoded as a parametrized attribute. The characters used to encode
8967/// these attributes are defined by the following enumeration:
8968/// @code
8969/// enum PropertyAttributes {
8970/// kPropertyReadOnly = 'R', // property is read-only.
8971/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8972/// kPropertyByref = '&', // property is a reference to the value last assigned
8973/// kPropertyDynamic = 'D', // property is dynamic
8974/// kPropertyGetter = 'G', // followed by getter selector name
8975/// kPropertySetter = 'S', // followed by setter selector name
8976/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8977/// kPropertyType = 'T' // followed by old-style type encoding.
8978/// kPropertyWeak = 'W' // 'weak' property
8979/// kPropertyStrong = 'P' // property GC'able
8980/// kPropertyNonAtomic = 'N' // property non-atomic
8981/// kPropertyOptional = '?' // property optional
8982/// };
8983/// @endcode
8984std::string
8986 const Decl *Container) const {
8987 // Collect information from the property implementation decl(s).
8988 bool Dynamic = false;
8989 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8990
8991 if (ObjCPropertyImplDecl *PropertyImpDecl =
8993 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8994 Dynamic = true;
8995 else
8996 SynthesizePID = PropertyImpDecl;
8997 }
8998
8999 // FIXME: This is not very efficient.
9000 std::string S = "T";
9001
9002 // Encode result type.
9003 // GCC has some special rules regarding encoding of properties which
9004 // closely resembles encoding of ivars.
9006
9007 if (PD->isOptional())
9008 S += ",?";
9009
9010 if (PD->isReadOnly()) {
9011 S += ",R";
9013 S += ",C";
9015 S += ",&";
9017 S += ",W";
9018 } else {
9019 switch (PD->getSetterKind()) {
9020 case ObjCPropertyDecl::Assign: break;
9021 case ObjCPropertyDecl::Copy: S += ",C"; break;
9022 case ObjCPropertyDecl::Retain: S += ",&"; break;
9023 case ObjCPropertyDecl::Weak: S += ",W"; break;
9024 }
9025 }
9026
9027 // It really isn't clear at all what this means, since properties
9028 // are "dynamic by default".
9029 if (Dynamic)
9030 S += ",D";
9031
9033 S += ",N";
9034
9036 S += ",G";
9037 S += PD->getGetterName().getAsString();
9038 }
9039
9041 S += ",S";
9042 S += PD->getSetterName().getAsString();
9043 }
9044
9045 if (SynthesizePID) {
9046 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9047 S += ",V";
9048 S += OID->getNameAsString();
9049 }
9050
9051 // FIXME: OBJCGC: weak & strong
9052 return S;
9053}
9054
9055/// getLegacyIntegralTypeEncoding -
9056/// Another legacy compatibility encoding: 32-bit longs are encoded as
9057/// 'l' or 'L' , but not always. For typedefs, we need to use
9058/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9060 if (PointeeTy->getAs<TypedefType>()) {
9061 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9062 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9063 PointeeTy = UnsignedIntTy;
9064 else
9065 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9066 PointeeTy = IntTy;
9067 }
9068 }
9069}
9070
9072 const FieldDecl *Field,
9073 QualType *NotEncodedT) const {
9074 // We follow the behavior of gcc, expanding structures which are
9075 // directly pointed to, and expanding embedded structures. Note that
9076 // these rules are sufficient to prevent recursive encoding of the
9077 // same type.
9078 getObjCEncodingForTypeImpl(T, S,
9079 ObjCEncOptions()
9080 .setExpandPointedToStructures()
9081 .setExpandStructures()
9082 .setIsOutermostType(),
9083 Field, NotEncodedT);
9084}
9085
9087 std::string& S) const {
9088 // Encode result type.
9089 // GCC has some special rules regarding encoding of properties which
9090 // closely resembles encoding of ivars.
9091 getObjCEncodingForTypeImpl(T, S,
9092 ObjCEncOptions()
9093 .setExpandPointedToStructures()
9094 .setExpandStructures()
9095 .setIsOutermostType()
9096 .setEncodingProperty(),
9097 /*Field=*/nullptr);
9098}
9099
9101 const BuiltinType *BT) {
9102 BuiltinType::Kind kind = BT->getKind();
9103 switch (kind) {
9104 case BuiltinType::Void: return 'v';
9105 case BuiltinType::Bool: return 'B';
9106 case BuiltinType::Char8:
9107 case BuiltinType::Char_U:
9108 case BuiltinType::UChar: return 'C';
9109 case BuiltinType::Char16:
9110 case BuiltinType::UShort: return 'S';
9111 case BuiltinType::Char32:
9112 case BuiltinType::UInt: return 'I';
9113 case BuiltinType::ULong:
9114 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9115 case BuiltinType::UInt128: return 'T';
9116 case BuiltinType::ULongLong: return 'Q';
9117 case BuiltinType::Char_S:
9118 case BuiltinType::SChar: return 'c';
9119 case BuiltinType::Short: return 's';
9120 case BuiltinType::WChar_S:
9121 case BuiltinType::WChar_U:
9122 case BuiltinType::Int: return 'i';
9123 case BuiltinType::Long:
9124 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9125 case BuiltinType::LongLong: return 'q';
9126 case BuiltinType::Int128: return 't';
9127 case BuiltinType::Float: return 'f';
9128 case BuiltinType::Double: return 'd';
9129 case BuiltinType::LongDouble: return 'D';
9130 case BuiltinType::NullPtr: return '*'; // like char*
9131
9132 case BuiltinType::BFloat16:
9133 case BuiltinType::Float16:
9134 case BuiltinType::Float128:
9135 case BuiltinType::Ibm128:
9136 case BuiltinType::Half:
9137 case BuiltinType::ShortAccum:
9138 case BuiltinType::Accum:
9139 case BuiltinType::LongAccum:
9140 case BuiltinType::UShortAccum:
9141 case BuiltinType::UAccum:
9142 case BuiltinType::ULongAccum:
9143 case BuiltinType::ShortFract:
9144 case BuiltinType::Fract:
9145 case BuiltinType::LongFract:
9146 case BuiltinType::UShortFract:
9147 case BuiltinType::UFract:
9148 case BuiltinType::ULongFract:
9149 case BuiltinType::SatShortAccum:
9150 case BuiltinType::SatAccum:
9151 case BuiltinType::SatLongAccum:
9152 case BuiltinType::SatUShortAccum:
9153 case BuiltinType::SatUAccum:
9154 case BuiltinType::SatULongAccum:
9155 case BuiltinType::SatShortFract:
9156 case BuiltinType::SatFract:
9157 case BuiltinType::SatLongFract:
9158 case BuiltinType::SatUShortFract:
9159 case BuiltinType::SatUFract:
9160 case BuiltinType::SatULongFract:
9161 // FIXME: potentially need @encodes for these!
9162 return ' ';
9163
9164#define SVE_TYPE(Name, Id, SingletonId) \
9165 case BuiltinType::Id:
9166#include "clang/Basic/AArch64ACLETypes.def"
9167#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9168#include "clang/Basic/RISCVVTypes.def"
9169#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9170#include "clang/Basic/WebAssemblyReferenceTypes.def"
9171#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9172#include "clang/Basic/AMDGPUTypes.def"
9173 {
9174 DiagnosticsEngine &Diags = C->getDiagnostics();
9175 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9176 "cannot yet @encode type %0");
9177 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9178 return ' ';
9179 }
9180
9181 case BuiltinType::ObjCId:
9182 case BuiltinType::ObjCClass:
9183 case BuiltinType::ObjCSel:
9184 llvm_unreachable("@encoding ObjC primitive type");
9185
9186 // OpenCL and placeholder types don't need @encodings.
9187#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9188 case BuiltinType::Id:
9189#include "clang/Basic/OpenCLImageTypes.def"
9190#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9191 case BuiltinType::Id:
9192#include "clang/Basic/OpenCLExtensionTypes.def"
9193 case BuiltinType::OCLEvent:
9194 case BuiltinType::OCLClkEvent:
9195 case BuiltinType::OCLQueue:
9196 case BuiltinType::OCLReserveID:
9197 case BuiltinType::OCLSampler:
9198 case BuiltinType::Dependent:
9199#define PPC_VECTOR_TYPE(Name, Id, Size) \
9200 case BuiltinType::Id:
9201#include "clang/Basic/PPCTypes.def"
9202#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9203#include "clang/Basic/HLSLIntangibleTypes.def"
9204#define BUILTIN_TYPE(KIND, ID)
9205#define PLACEHOLDER_TYPE(KIND, ID) \
9206 case BuiltinType::KIND:
9207#include "clang/AST/BuiltinTypes.def"
9208 llvm_unreachable("invalid builtin type for @encode");
9209 }
9210 llvm_unreachable("invalid BuiltinType::Kind value");
9211}
9212
9213static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9215
9216 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9217 if (!Enum->isFixed())
9218 return 'i';
9219
9220 // The encoding of a fixed enum type matches its fixed underlying type.
9221 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9223}
9224
9225static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9226 QualType T, const FieldDecl *FD) {
9227 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9228 S += 'b';
9229 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9230 // The GNU runtime requires more information; bitfields are encoded as b,
9231 // then the offset (in bits) of the first element, then the type of the
9232 // bitfield, then the size in bits. For example, in this structure:
9233 //
9234 // struct
9235 // {
9236 // int integer;
9237 // int flags:2;
9238 // };
9239 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9240 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9241 // information is not especially sensible, but we're stuck with it for
9242 // compatibility with GCC, although providing it breaks anything that
9243 // actually uses runtime introspection and wants to work on both runtimes...
9244 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9245 uint64_t Offset;
9246
9247 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9248 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9249 } else {
9250 const RecordDecl *RD = FD->getParent();
9251 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9252 Offset = RL.getFieldOffset(FD->getFieldIndex());
9253 }
9254
9255 S += llvm::utostr(Offset);
9256
9257 if (const auto *ET = T->getAsCanonical<EnumType>())
9258 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9259 else {
9260 const auto *BT = T->castAs<BuiltinType>();
9261 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9262 }
9263 }
9264 S += llvm::utostr(FD->getBitWidthValue());
9265}
9266
9267// Helper function for determining whether the encoded type string would include
9268// a template specialization type.
9270 bool VisitBasesAndFields) {
9271 T = T->getBaseElementTypeUnsafe();
9272
9273 if (auto *PT = T->getAs<PointerType>())
9275 PT->getPointeeType().getTypePtr(), false);
9276
9277 auto *CXXRD = T->getAsCXXRecordDecl();
9278
9279 if (!CXXRD)
9280 return false;
9281
9283 return true;
9284
9285 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9286 return false;
9287
9288 for (const auto &B : CXXRD->bases())
9289 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9290 true))
9291 return true;
9292
9293 for (auto *FD : CXXRD->fields())
9294 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9295 true))
9296 return true;
9297
9298 return false;
9299}
9300
9301// FIXME: Use SmallString for accumulating string.
9302void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9303 const ObjCEncOptions Options,
9304 const FieldDecl *FD,
9305 QualType *NotEncodedT) const {
9307 switch (CT->getTypeClass()) {
9308 case Type::Builtin:
9309 case Type::Enum:
9310 if (FD && FD->isBitField())
9311 return EncodeBitField(this, S, T, FD);
9312 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9313 S += getObjCEncodingForPrimitiveType(this, BT);
9314 else
9315 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9316 return;
9317
9318 case Type::Complex:
9319 S += 'j';
9320 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9321 ObjCEncOptions(),
9322 /*Field=*/nullptr);
9323 return;
9324
9325 case Type::Atomic:
9326 S += 'A';
9327 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9328 ObjCEncOptions(),
9329 /*Field=*/nullptr);
9330 return;
9331
9332 // encoding for pointer or reference types.
9333 case Type::Pointer:
9334 case Type::LValueReference:
9335 case Type::RValueReference: {
9336 QualType PointeeTy;
9337 if (isa<PointerType>(CT)) {
9338 const auto *PT = T->castAs<PointerType>();
9339 if (PT->isObjCSelType()) {
9340 S += ':';
9341 return;
9342 }
9343 PointeeTy = PT->getPointeeType();
9344 } else {
9345 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9346 }
9347
9348 bool isReadOnly = false;
9349 // For historical/compatibility reasons, the read-only qualifier of the
9350 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9351 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9352 // Also, do not emit the 'r' for anything but the outermost type!
9353 if (T->getAs<TypedefType>()) {
9354 if (Options.IsOutermostType() && T.isConstQualified()) {
9355 isReadOnly = true;
9356 S += 'r';
9357 }
9358 } else if (Options.IsOutermostType()) {
9359 QualType P = PointeeTy;
9360 while (auto PT = P->getAs<PointerType>())
9361 P = PT->getPointeeType();
9362 if (P.isConstQualified()) {
9363 isReadOnly = true;
9364 S += 'r';
9365 }
9366 }
9367 if (isReadOnly) {
9368 // Another legacy compatibility encoding. Some ObjC qualifier and type
9369 // combinations need to be rearranged.
9370 // Rewrite "in const" from "nr" to "rn"
9371 if (StringRef(S).ends_with("nr"))
9372 S.replace(S.end()-2, S.end(), "rn");
9373 }
9374
9375 if (PointeeTy->isCharType()) {
9376 // char pointer types should be encoded as '*' unless it is a
9377 // type that has been typedef'd to 'BOOL'.
9378 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9379 S += '*';
9380 return;
9381 }
9382 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9383 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9384 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9385 if (II == &Idents.get("objc_class")) {
9386 S += '#';
9387 return;
9388 }
9389 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9390 if (II == &Idents.get("objc_object")) {
9391 S += '@';
9392 return;
9393 }
9394 // If the encoded string for the class includes template names, just emit
9395 // "^v" for pointers to the class.
9396 if (getLangOpts().CPlusPlus &&
9397 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9399 RTy, Options.ExpandPointedToStructures()))) {
9400 S += "^v";
9401 return;
9402 }
9403 // fall through...
9404 }
9405 S += '^';
9407
9408 ObjCEncOptions NewOptions;
9409 if (Options.ExpandPointedToStructures())
9410 NewOptions.setExpandStructures();
9411 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9412 /*Field=*/nullptr, NotEncodedT);
9413 return;
9414 }
9415
9416 case Type::ConstantArray:
9417 case Type::IncompleteArray:
9418 case Type::VariableArray: {
9419 const auto *AT = cast<ArrayType>(CT);
9420
9421 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9422 // Incomplete arrays are encoded as a pointer to the array element.
9423 S += '^';
9424
9425 getObjCEncodingForTypeImpl(
9426 AT->getElementType(), S,
9427 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9428 } else {
9429 S += '[';
9430
9431 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9432 S += llvm::utostr(CAT->getZExtSize());
9433 else {
9434 //Variable length arrays are encoded as a regular array with 0 elements.
9436 "Unknown array type!");
9437 S += '0';
9438 }
9439
9440 getObjCEncodingForTypeImpl(
9441 AT->getElementType(), S,
9442 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9443 NotEncodedT);
9444 S += ']';
9445 }
9446 return;
9447 }
9448
9449 case Type::FunctionNoProto:
9450 case Type::FunctionProto:
9451 S += '?';
9452 return;
9453
9454 case Type::Record: {
9455 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9456 S += RDecl->isUnion() ? '(' : '{';
9457 // Anonymous structures print as '?'
9458 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9459 S += II->getName();
9460 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9461 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9462 llvm::raw_string_ostream OS(S);
9463 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9465 }
9466 } else {
9467 S += '?';
9468 }
9469 if (Options.ExpandStructures()) {
9470 S += '=';
9471 if (!RDecl->isUnion()) {
9472 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9473 } else {
9474 for (const auto *Field : RDecl->fields()) {
9475 if (FD) {
9476 S += '"';
9477 S += Field->getNameAsString();
9478 S += '"';
9479 }
9480
9481 // Special case bit-fields.
9482 if (Field->isBitField()) {
9483 getObjCEncodingForTypeImpl(Field->getType(), S,
9484 ObjCEncOptions().setExpandStructures(),
9485 Field);
9486 } else {
9487 QualType qt = Field->getType();
9489 getObjCEncodingForTypeImpl(
9490 qt, S,
9491 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9492 NotEncodedT);
9493 }
9494 }
9495 }
9496 }
9497 S += RDecl->isUnion() ? ')' : '}';
9498 return;
9499 }
9500
9501 case Type::BlockPointer: {
9502 const auto *BT = T->castAs<BlockPointerType>();
9503 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9504 if (Options.EncodeBlockParameters()) {
9505 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9506
9507 S += '<';
9508 // Block return type
9509 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9510 Options.forComponentType(), FD, NotEncodedT);
9511 // Block self
9512 S += "@?";
9513 // Block parameters
9514 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9515 for (const auto &I : FPT->param_types())
9516 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9517 NotEncodedT);
9518 }
9519 S += '>';
9520 }
9521 return;
9522 }
9523
9524 case Type::ObjCObject: {
9525 // hack to match legacy encoding of *id and *Class
9526 QualType Ty = getObjCObjectPointerType(CT);
9527 if (Ty->isObjCIdType()) {
9528 S += "{objc_object=}";
9529 return;
9530 }
9531 else if (Ty->isObjCClassType()) {
9532 S += "{objc_class=}";
9533 return;
9534 }
9535 // TODO: Double check to make sure this intentionally falls through.
9536 [[fallthrough]];
9537 }
9538
9539 case Type::ObjCInterface: {
9540 // Ignore protocol qualifiers when mangling at this level.
9541 // @encode(class_name)
9542 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9543 S += '{';
9544 S += OI->getObjCRuntimeNameAsString();
9545 if (Options.ExpandStructures()) {
9546 S += '=';
9547 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9548 DeepCollectObjCIvars(OI, true, Ivars);
9549 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9550 const FieldDecl *Field = Ivars[i];
9551 if (Field->isBitField())
9552 getObjCEncodingForTypeImpl(Field->getType(), S,
9553 ObjCEncOptions().setExpandStructures(),
9554 Field);
9555 else
9556 getObjCEncodingForTypeImpl(Field->getType(), S,
9557 ObjCEncOptions().setExpandStructures(), FD,
9558 NotEncodedT);
9559 }
9560 }
9561 S += '}';
9562 return;
9563 }
9564
9565 case Type::ObjCObjectPointer: {
9566 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9567 if (OPT->isObjCIdType()) {
9568 S += '@';
9569 return;
9570 }
9571
9572 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9573 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9574 // Since this is a binary compatibility issue, need to consult with
9575 // runtime folks. Fortunately, this is a *very* obscure construct.
9576 S += '#';
9577 return;
9578 }
9579
9580 if (OPT->isObjCQualifiedIdType()) {
9581 getObjCEncodingForTypeImpl(
9582 getObjCIdType(), S,
9583 Options.keepingOnly(ObjCEncOptions()
9584 .setExpandPointedToStructures()
9585 .setExpandStructures()),
9586 FD);
9587 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9588 // Note that we do extended encoding of protocol qualifier list
9589 // Only when doing ivar or property encoding.
9590 S += '"';
9591 for (const auto *I : OPT->quals()) {
9592 S += '<';
9593 S += I->getObjCRuntimeNameAsString();
9594 S += '>';
9595 }
9596 S += '"';
9597 }
9598 return;
9599 }
9600
9601 S += '@';
9602 if (OPT->getInterfaceDecl() &&
9603 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9604 S += '"';
9605 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9606 for (const auto *I : OPT->quals()) {
9607 S += '<';
9608 S += I->getObjCRuntimeNameAsString();
9609 S += '>';
9610 }
9611 S += '"';
9612 }
9613 return;
9614 }
9615
9616 // gcc just blithely ignores member pointers.
9617 // FIXME: we should do better than that. 'M' is available.
9618 case Type::MemberPointer:
9619 // This matches gcc's encoding, even though technically it is insufficient.
9620 //FIXME. We should do a better job than gcc.
9621 case Type::Vector:
9622 case Type::ExtVector:
9623 // Until we have a coherent encoding of these three types, issue warning.
9624 if (NotEncodedT)
9625 *NotEncodedT = T;
9626 return;
9627
9628 case Type::ConstantMatrix:
9629 if (NotEncodedT)
9630 *NotEncodedT = T;
9631 return;
9632
9633 case Type::BitInt:
9634 if (NotEncodedT)
9635 *NotEncodedT = T;
9636 return;
9637
9638 // We could see an undeduced auto type here during error recovery.
9639 // Just ignore it.
9640 case Type::Auto:
9641 case Type::DeducedTemplateSpecialization:
9642 return;
9643
9644 case Type::HLSLAttributedResource:
9645 case Type::HLSLInlineSpirv:
9646 llvm_unreachable("unexpected type");
9647
9648 case Type::ArrayParameter:
9649 case Type::Pipe:
9650#define ABSTRACT_TYPE(KIND, BASE)
9651#define TYPE(KIND, BASE)
9652#define DEPENDENT_TYPE(KIND, BASE) \
9653 case Type::KIND:
9654#define NON_CANONICAL_TYPE(KIND, BASE) \
9655 case Type::KIND:
9656#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9657 case Type::KIND:
9658#include "clang/AST/TypeNodes.inc"
9659 llvm_unreachable("@encode for dependent type!");
9660 }
9661 llvm_unreachable("bad type kind!");
9662}
9663
9664void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9665 std::string &S,
9666 const FieldDecl *FD,
9667 bool includeVBases,
9668 QualType *NotEncodedT) const {
9669 assert(RDecl && "Expected non-null RecordDecl");
9670 assert(!RDecl->isUnion() && "Should not be called for unions");
9671 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9672 return;
9673
9674 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9675 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9676 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9677
9678 if (CXXRec) {
9679 for (const auto &BI : CXXRec->bases()) {
9680 if (!BI.isVirtual()) {
9681 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9682 if (base->isEmpty())
9683 continue;
9684 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9685 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9686 std::make_pair(offs, base));
9687 }
9688 }
9689 }
9690
9691 for (FieldDecl *Field : RDecl->fields()) {
9692 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9693 continue;
9694 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9695 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9696 std::make_pair(offs, Field));
9697 }
9698
9699 if (CXXRec && includeVBases) {
9700 for (const auto &BI : CXXRec->vbases()) {
9701 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9702 if (base->isEmpty())
9703 continue;
9704 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9705 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9706 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9707 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9708 std::make_pair(offs, base));
9709 }
9710 }
9711
9712 CharUnits size;
9713 if (CXXRec) {
9714 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9715 } else {
9716 size = layout.getSize();
9717 }
9718
9719#ifndef NDEBUG
9720 uint64_t CurOffs = 0;
9721#endif
9722 std::multimap<uint64_t, NamedDecl *>::iterator
9723 CurLayObj = FieldOrBaseOffsets.begin();
9724
9725 if (CXXRec && CXXRec->isDynamicClass() &&
9726 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9727 if (FD) {
9728 S += "\"_vptr$";
9729 std::string recname = CXXRec->getNameAsString();
9730 if (recname.empty()) recname = "?";
9731 S += recname;
9732 S += '"';
9733 }
9734 S += "^^?";
9735#ifndef NDEBUG
9736 CurOffs += getTypeSize(VoidPtrTy);
9737#endif
9738 }
9739
9740 if (!RDecl->hasFlexibleArrayMember()) {
9741 // Mark the end of the structure.
9742 uint64_t offs = toBits(size);
9743 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9744 std::make_pair(offs, nullptr));
9745 }
9746
9747 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9748#ifndef NDEBUG
9749 assert(CurOffs <= CurLayObj->first);
9750 if (CurOffs < CurLayObj->first) {
9751 uint64_t padding = CurLayObj->first - CurOffs;
9752 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9753 // packing/alignment of members is different that normal, in which case
9754 // the encoding will be out-of-sync with the real layout.
9755 // If the runtime switches to just consider the size of types without
9756 // taking into account alignment, we could make padding explicit in the
9757 // encoding (e.g. using arrays of chars). The encoding strings would be
9758 // longer then though.
9759 CurOffs += padding;
9760 }
9761#endif
9762
9763 NamedDecl *dcl = CurLayObj->second;
9764 if (!dcl)
9765 break; // reached end of structure.
9766
9767 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9768 // We expand the bases without their virtual bases since those are going
9769 // in the initial structure. Note that this differs from gcc which
9770 // expands virtual bases each time one is encountered in the hierarchy,
9771 // making the encoding type bigger than it really is.
9772 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9773 NotEncodedT);
9774 assert(!base->isEmpty());
9775#ifndef NDEBUG
9776 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9777#endif
9778 } else {
9779 const auto *field = cast<FieldDecl>(dcl);
9780 if (FD) {
9781 S += '"';
9782 S += field->getNameAsString();
9783 S += '"';
9784 }
9785
9786 if (field->isBitField()) {
9787 EncodeBitField(this, S, field->getType(), field);
9788#ifndef NDEBUG
9789 CurOffs += field->getBitWidthValue();
9790#endif
9791 } else {
9792 QualType qt = field->getType();
9794 getObjCEncodingForTypeImpl(
9795 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9796 FD, NotEncodedT);
9797#ifndef NDEBUG
9798 CurOffs += getTypeSize(field->getType());
9799#endif
9800 }
9801 }
9802 }
9803}
9804
9806 std::string& S) const {
9807 if (QT & Decl::OBJC_TQ_In)
9808 S += 'n';
9809 if (QT & Decl::OBJC_TQ_Inout)
9810 S += 'N';
9811 if (QT & Decl::OBJC_TQ_Out)
9812 S += 'o';
9813 if (QT & Decl::OBJC_TQ_Bycopy)
9814 S += 'O';
9815 if (QT & Decl::OBJC_TQ_Byref)
9816 S += 'R';
9817 if (QT & Decl::OBJC_TQ_Oneway)
9818 S += 'V';
9819}
9820
9822 if (!ObjCIdDecl) {
9825 ObjCIdDecl = buildImplicitTypedef(T, "id");
9826 }
9827 return ObjCIdDecl;
9828}
9829
9831 if (!ObjCSelDecl) {
9833 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9834 }
9835 return ObjCSelDecl;
9836}
9837
9839 if (!ObjCClassDecl) {
9842 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9843 }
9844 return ObjCClassDecl;
9845}
9846
9848 if (!ObjCProtocolClassDecl) {
9849 ObjCProtocolClassDecl
9852 &Idents.get("Protocol"),
9853 /*typeParamList=*/nullptr,
9854 /*PrevDecl=*/nullptr,
9855 SourceLocation(), true);
9856 }
9857
9858 return ObjCProtocolClassDecl;
9859}
9860
9862 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9863 return PointerAuthQualifier();
9865 getLangOpts().PointerAuthObjcInterfaceSelKey,
9866 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9868 /*isIsaPointer=*/false,
9869 /*authenticatesNullValues=*/false);
9870}
9871
9872//===----------------------------------------------------------------------===//
9873// __builtin_va_list Construction Functions
9874//===----------------------------------------------------------------------===//
9875
9877 StringRef Name) {
9878 // typedef char* __builtin[_ms]_va_list;
9879 QualType T = Context->getPointerType(Context->CharTy);
9880 return Context->buildImplicitTypedef(T, Name);
9881}
9882
9884 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9885}
9886
9888 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9889}
9890
9892 // typedef void* __builtin_va_list;
9893 QualType T = Context->getPointerType(Context->VoidTy);
9894 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9895}
9896
9897static TypedefDecl *
9899 // struct __va_list
9900 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9901 if (Context->getLangOpts().CPlusPlus) {
9902 // namespace std { struct __va_list {
9903 auto *NS = NamespaceDecl::Create(
9904 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9905 /*Inline=*/false, SourceLocation(), SourceLocation(),
9906 &Context->Idents.get("std"),
9907 /*PrevDecl=*/nullptr, /*Nested=*/false);
9908 NS->setImplicit();
9910 }
9911
9912 VaListTagDecl->startDefinition();
9913
9914 const size_t NumFields = 5;
9915 QualType FieldTypes[NumFields];
9916 const char *FieldNames[NumFields];
9917
9918 // void *__stack;
9919 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9920 FieldNames[0] = "__stack";
9921
9922 // void *__gr_top;
9923 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9924 FieldNames[1] = "__gr_top";
9925
9926 // void *__vr_top;
9927 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9928 FieldNames[2] = "__vr_top";
9929
9930 // int __gr_offs;
9931 FieldTypes[3] = Context->IntTy;
9932 FieldNames[3] = "__gr_offs";
9933
9934 // int __vr_offs;
9935 FieldTypes[4] = Context->IntTy;
9936 FieldNames[4] = "__vr_offs";
9937
9938 // Create fields
9939 for (unsigned i = 0; i < NumFields; ++i) {
9940 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9944 &Context->Idents.get(FieldNames[i]),
9945 FieldTypes[i], /*TInfo=*/nullptr,
9946 /*BitWidth=*/nullptr,
9947 /*Mutable=*/false,
9948 ICIS_NoInit);
9949 Field->setAccess(AS_public);
9950 VaListTagDecl->addDecl(Field);
9951 }
9952 VaListTagDecl->completeDefinition();
9953 Context->VaListTagDecl = VaListTagDecl;
9954 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9955
9956 // } __builtin_va_list;
9957 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9958}
9959
9961 // typedef struct __va_list_tag {
9963
9964 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9965 VaListTagDecl->startDefinition();
9966
9967 const size_t NumFields = 5;
9968 QualType FieldTypes[NumFields];
9969 const char *FieldNames[NumFields];
9970
9971 // unsigned char gpr;
9972 FieldTypes[0] = Context->UnsignedCharTy;
9973 FieldNames[0] = "gpr";
9974
9975 // unsigned char fpr;
9976 FieldTypes[1] = Context->UnsignedCharTy;
9977 FieldNames[1] = "fpr";
9978
9979 // unsigned short reserved;
9980 FieldTypes[2] = Context->UnsignedShortTy;
9981 FieldNames[2] = "reserved";
9982
9983 // void* overflow_arg_area;
9984 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9985 FieldNames[3] = "overflow_arg_area";
9986
9987 // void* reg_save_area;
9988 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9989 FieldNames[4] = "reg_save_area";
9990
9991 // Create fields
9992 for (unsigned i = 0; i < NumFields; ++i) {
9993 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9996 &Context->Idents.get(FieldNames[i]),
9997 FieldTypes[i], /*TInfo=*/nullptr,
9998 /*BitWidth=*/nullptr,
9999 /*Mutable=*/false,
10000 ICIS_NoInit);
10001 Field->setAccess(AS_public);
10002 VaListTagDecl->addDecl(Field);
10003 }
10004 VaListTagDecl->completeDefinition();
10005 Context->VaListTagDecl = VaListTagDecl;
10006 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10007
10008 // } __va_list_tag;
10009 TypedefDecl *VaListTagTypedefDecl =
10010 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10011
10012 QualType VaListTagTypedefType =
10013 Context->getTypedefType(ElaboratedTypeKeyword::None,
10014 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10015
10016 // typedef __va_list_tag __builtin_va_list[1];
10017 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10018 QualType VaListTagArrayType = Context->getConstantArrayType(
10019 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10020 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10021}
10022
10023static TypedefDecl *
10025 // struct __va_list_tag {
10027 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10028 VaListTagDecl->startDefinition();
10029
10030 const size_t NumFields = 4;
10031 QualType FieldTypes[NumFields];
10032 const char *FieldNames[NumFields];
10033
10034 // unsigned gp_offset;
10035 FieldTypes[0] = Context->UnsignedIntTy;
10036 FieldNames[0] = "gp_offset";
10037
10038 // unsigned fp_offset;
10039 FieldTypes[1] = Context->UnsignedIntTy;
10040 FieldNames[1] = "fp_offset";
10041
10042 // void* overflow_arg_area;
10043 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10044 FieldNames[2] = "overflow_arg_area";
10045
10046 // void* reg_save_area;
10047 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10048 FieldNames[3] = "reg_save_area";
10049
10050 // Create fields
10051 for (unsigned i = 0; i < NumFields; ++i) {
10052 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10056 &Context->Idents.get(FieldNames[i]),
10057 FieldTypes[i], /*TInfo=*/nullptr,
10058 /*BitWidth=*/nullptr,
10059 /*Mutable=*/false,
10060 ICIS_NoInit);
10061 Field->setAccess(AS_public);
10062 VaListTagDecl->addDecl(Field);
10063 }
10064 VaListTagDecl->completeDefinition();
10065 Context->VaListTagDecl = VaListTagDecl;
10066 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10067
10068 // };
10069
10070 // typedef struct __va_list_tag __builtin_va_list[1];
10071 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10072 QualType VaListTagArrayType = Context->getConstantArrayType(
10073 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10074 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10075}
10076
10077static TypedefDecl *
10079 // struct __va_list
10080 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10081 if (Context->getLangOpts().CPlusPlus) {
10082 // namespace std { struct __va_list {
10083 NamespaceDecl *NS;
10084 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10085 Context->getTranslationUnitDecl(),
10086 /*Inline=*/false, SourceLocation(),
10087 SourceLocation(), &Context->Idents.get("std"),
10088 /*PrevDecl=*/nullptr, /*Nested=*/false);
10089 NS->setImplicit();
10090 VaListDecl->setDeclContext(NS);
10091 }
10092
10093 VaListDecl->startDefinition();
10094
10095 // void * __ap;
10096 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10097 VaListDecl,
10100 &Context->Idents.get("__ap"),
10101 Context->getPointerType(Context->VoidTy),
10102 /*TInfo=*/nullptr,
10103 /*BitWidth=*/nullptr,
10104 /*Mutable=*/false,
10105 ICIS_NoInit);
10106 Field->setAccess(AS_public);
10107 VaListDecl->addDecl(Field);
10108
10109 // };
10110 VaListDecl->completeDefinition();
10111 Context->VaListTagDecl = VaListDecl;
10112
10113 // typedef struct __va_list __builtin_va_list;
10114 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10115 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10116}
10117
10118static TypedefDecl *
10120 // struct __va_list_tag {
10122 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10123 VaListTagDecl->startDefinition();
10124
10125 const size_t NumFields = 4;
10126 QualType FieldTypes[NumFields];
10127 const char *FieldNames[NumFields];
10128
10129 // long __gpr;
10130 FieldTypes[0] = Context->LongTy;
10131 FieldNames[0] = "__gpr";
10132
10133 // long __fpr;
10134 FieldTypes[1] = Context->LongTy;
10135 FieldNames[1] = "__fpr";
10136
10137 // void *__overflow_arg_area;
10138 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10139 FieldNames[2] = "__overflow_arg_area";
10140
10141 // void *__reg_save_area;
10142 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10143 FieldNames[3] = "__reg_save_area";
10144
10145 // Create fields
10146 for (unsigned i = 0; i < NumFields; ++i) {
10147 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10151 &Context->Idents.get(FieldNames[i]),
10152 FieldTypes[i], /*TInfo=*/nullptr,
10153 /*BitWidth=*/nullptr,
10154 /*Mutable=*/false,
10155 ICIS_NoInit);
10156 Field->setAccess(AS_public);
10157 VaListTagDecl->addDecl(Field);
10158 }
10159 VaListTagDecl->completeDefinition();
10160 Context->VaListTagDecl = VaListTagDecl;
10161 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10162
10163 // };
10164
10165 // typedef __va_list_tag __builtin_va_list[1];
10166 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10167 QualType VaListTagArrayType = Context->getConstantArrayType(
10168 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10169
10170 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10171}
10172
10174 // typedef struct __va_list_tag {
10176 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10177 VaListTagDecl->startDefinition();
10178
10179 const size_t NumFields = 3;
10180 QualType FieldTypes[NumFields];
10181 const char *FieldNames[NumFields];
10182
10183 // void *CurrentSavedRegisterArea;
10184 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10185 FieldNames[0] = "__current_saved_reg_area_pointer";
10186
10187 // void *SavedRegAreaEnd;
10188 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10189 FieldNames[1] = "__saved_reg_area_end_pointer";
10190
10191 // void *OverflowArea;
10192 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10193 FieldNames[2] = "__overflow_area_pointer";
10194
10195 // Create fields
10196 for (unsigned i = 0; i < NumFields; ++i) {
10198 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10199 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10200 /*TInfo=*/nullptr,
10201 /*BitWidth=*/nullptr,
10202 /*Mutable=*/false, ICIS_NoInit);
10203 Field->setAccess(AS_public);
10204 VaListTagDecl->addDecl(Field);
10205 }
10206 VaListTagDecl->completeDefinition();
10207 Context->VaListTagDecl = VaListTagDecl;
10208 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10209
10210 // } __va_list_tag;
10211 TypedefDecl *VaListTagTypedefDecl =
10212 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10213
10214 QualType VaListTagTypedefType =
10215 Context->getTypedefType(ElaboratedTypeKeyword::None,
10216 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10217
10218 // typedef __va_list_tag __builtin_va_list[1];
10219 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10220 QualType VaListTagArrayType = Context->getConstantArrayType(
10221 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10222
10223 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10224}
10225
10226static TypedefDecl *
10228 // typedef struct __va_list_tag {
10229 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10230
10231 VaListTagDecl->startDefinition();
10232
10233 // int* __va_stk;
10234 // int* __va_reg;
10235 // int __va_ndx;
10236 constexpr size_t NumFields = 3;
10237 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10238 Context->getPointerType(Context->IntTy),
10239 Context->IntTy};
10240 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10241
10242 // Create fields
10243 for (unsigned i = 0; i < NumFields; ++i) {
10246 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10247 /*BitWidth=*/nullptr,
10248 /*Mutable=*/false, ICIS_NoInit);
10249 Field->setAccess(AS_public);
10250 VaListTagDecl->addDecl(Field);
10251 }
10252 VaListTagDecl->completeDefinition();
10253 Context->VaListTagDecl = VaListTagDecl;
10254 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10255
10256 // } __va_list_tag;
10257 TypedefDecl *VaListTagTypedefDecl =
10258 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10259
10260 return VaListTagTypedefDecl;
10261}
10262
10265 switch (Kind) {
10267 return CreateCharPtrBuiltinVaListDecl(Context);
10269 return CreateVoidPtrBuiltinVaListDecl(Context);
10271 return CreateAArch64ABIBuiltinVaListDecl(Context);
10273 return CreatePowerABIBuiltinVaListDecl(Context);
10275 return CreateX86_64ABIBuiltinVaListDecl(Context);
10277 return CreateAAPCSABIBuiltinVaListDecl(Context);
10279 return CreateSystemZBuiltinVaListDecl(Context);
10281 return CreateHexagonBuiltinVaListDecl(Context);
10283 return CreateXtensaABIBuiltinVaListDecl(Context);
10284 }
10285
10286 llvm_unreachable("Unhandled __builtin_va_list type kind");
10287}
10288
10290 if (!BuiltinVaListDecl) {
10291 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10292 assert(BuiltinVaListDecl->isImplicit());
10293 }
10294
10295 return BuiltinVaListDecl;
10296}
10297
10299 // Force the creation of VaListTagDecl by building the __builtin_va_list
10300 // declaration.
10301 if (!VaListTagDecl)
10302 (void)getBuiltinVaListDecl();
10303
10304 return VaListTagDecl;
10305}
10306
10308 if (!BuiltinMSVaListDecl)
10309 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10310
10311 return BuiltinMSVaListDecl;
10312}
10313
10315 // Allow redecl custom type checking builtin for HLSL.
10316 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10317 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10318 return true;
10319 // Allow redecl custom type checking builtin for SPIR-V.
10320 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10321 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10322 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10323 return true;
10324 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10325}
10326
10328 assert(ObjCConstantStringType.isNull() &&
10329 "'NSConstantString' type already set!");
10330
10331 ObjCConstantStringType = getObjCInterfaceType(Decl);
10332}
10333
10334/// Retrieve the template name that corresponds to a non-empty
10335/// lookup.
10338 UnresolvedSetIterator End) const {
10339 unsigned size = End - Begin;
10340 assert(size > 1 && "set is not overloaded!");
10341
10342 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10343 size * sizeof(FunctionTemplateDecl*));
10344 auto *OT = new (memory) OverloadedTemplateStorage(size);
10345
10346 NamedDecl **Storage = OT->getStorage();
10347 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10348 NamedDecl *D = *I;
10349 assert(isa<FunctionTemplateDecl>(D) ||
10353 *Storage++ = D;
10354 }
10355
10356 return TemplateName(OT);
10357}
10358
10359/// Retrieve a template name representing an unqualified-id that has been
10360/// assumed to name a template for ADL purposes.
10362 auto *OT = new (*this) AssumedTemplateStorage(Name);
10363 return TemplateName(OT);
10364}
10365
10366/// Retrieve the template name that represents a qualified
10367/// template name such as \c std::vector.
10369 bool TemplateKeyword,
10370 TemplateName Template) const {
10371 assert(Template.getKind() == TemplateName::Template ||
10373
10374 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10375 assert(!Qualifier && "unexpected qualified template template parameter");
10376 assert(TemplateKeyword == false);
10377 return Template;
10378 }
10379
10380 // FIXME: Canonicalization?
10381 llvm::FoldingSetNodeID ID;
10382 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10383
10384 void *InsertPos = nullptr;
10386 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10387 if (!QTN) {
10388 QTN = new (*this, alignof(QualifiedTemplateName))
10389 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10390 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10391 }
10392
10393 return TemplateName(QTN);
10394}
10395
10396/// Retrieve the template name that represents a dependent
10397/// template name such as \c MetaFun::template operator+.
10400 llvm::FoldingSetNodeID ID;
10401 S.Profile(ID);
10402
10403 void *InsertPos = nullptr;
10404 if (DependentTemplateName *QTN =
10405 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10406 return TemplateName(QTN);
10407
10409 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10410 DependentTemplateNames.InsertNode(QTN, InsertPos);
10411 return TemplateName(QTN);
10412}
10413
10415 Decl *AssociatedDecl,
10416 unsigned Index,
10417 UnsignedOrNone PackIndex,
10418 bool Final) const {
10419 llvm::FoldingSetNodeID ID;
10420 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10421 Index, PackIndex, Final);
10422
10423 void *insertPos = nullptr;
10425 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10426
10427 if (!subst) {
10428 subst = new (*this) SubstTemplateTemplateParmStorage(
10429 Replacement, AssociatedDecl, Index, PackIndex, Final);
10430 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10431 }
10432
10433 return TemplateName(subst);
10434}
10435
10438 Decl *AssociatedDecl,
10439 unsigned Index, bool Final) const {
10440 auto &Self = const_cast<ASTContext &>(*this);
10441 llvm::FoldingSetNodeID ID;
10443 AssociatedDecl, Index, Final);
10444
10445 void *InsertPos = nullptr;
10447 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10448
10449 if (!Subst) {
10450 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10451 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10452 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10453 }
10454
10455 return TemplateName(Subst);
10456}
10457
10458/// Retrieve the template name that represents a template name
10459/// deduced from a specialization.
10462 DefaultArguments DefaultArgs) const {
10463 if (!DefaultArgs)
10464 return Underlying;
10465
10466 llvm::FoldingSetNodeID ID;
10467 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10468
10469 void *InsertPos = nullptr;
10471 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10472 if (!DTS) {
10473 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10474 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10475 alignof(DeducedTemplateStorage));
10476 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10477 DeducedTemplates.InsertNode(DTS, InsertPos);
10478 }
10479 return TemplateName(DTS);
10480}
10481
10482/// getFromTargetType - Given one of the integer types provided by
10483/// TargetInfo, produce the corresponding type. The unsigned @p Type
10484/// is actually a value of type @c TargetInfo::IntType.
10485CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10486 switch (Type) {
10487 case TargetInfo::NoInt: return {};
10490 case TargetInfo::SignedShort: return ShortTy;
10492 case TargetInfo::SignedInt: return IntTy;
10494 case TargetInfo::SignedLong: return LongTy;
10498 }
10499
10500 llvm_unreachable("Unhandled TargetInfo::IntType value");
10501}
10502
10503//===----------------------------------------------------------------------===//
10504// Type Predicates.
10505//===----------------------------------------------------------------------===//
10506
10507/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10508/// garbage collection attribute.
10509///
10511 if (getLangOpts().getGC() == LangOptions::NonGC)
10512 return Qualifiers::GCNone;
10513
10514 assert(getLangOpts().ObjC);
10515 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10516
10517 // Default behaviour under objective-C's gc is for ObjC pointers
10518 // (or pointers to them) be treated as though they were declared
10519 // as __strong.
10520 if (GCAttrs == Qualifiers::GCNone) {
10522 return Qualifiers::Strong;
10523 else if (Ty->isPointerType())
10525 } else {
10526 // It's not valid to set GC attributes on anything that isn't a
10527 // pointer.
10528#ifndef NDEBUG
10530 while (const auto *AT = dyn_cast<ArrayType>(CT))
10531 CT = AT->getElementType();
10532 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10533#endif
10534 }
10535 return GCAttrs;
10536}
10537
10538//===----------------------------------------------------------------------===//
10539// Type Compatibility Testing
10540//===----------------------------------------------------------------------===//
10541
10542/// areCompatVectorTypes - Return true if the two specified vector types are
10543/// compatible.
10544static bool areCompatVectorTypes(const VectorType *LHS,
10545 const VectorType *RHS) {
10546 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10547 return LHS->getElementType() == RHS->getElementType() &&
10548 LHS->getNumElements() == RHS->getNumElements();
10549}
10550
10551/// areCompatMatrixTypes - Return true if the two specified matrix types are
10552/// compatible.
10554 const ConstantMatrixType *RHS) {
10555 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10556 return LHS->getElementType() == RHS->getElementType() &&
10557 LHS->getNumRows() == RHS->getNumRows() &&
10558 LHS->getNumColumns() == RHS->getNumColumns();
10559}
10560
10562 QualType SecondVec) {
10563 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10564 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10565
10566 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10567 return true;
10568
10569 // Treat Neon vector types and most AltiVec vector types as if they are the
10570 // equivalent GCC vector types.
10571 const auto *First = FirstVec->castAs<VectorType>();
10572 const auto *Second = SecondVec->castAs<VectorType>();
10573 if (First->getNumElements() == Second->getNumElements() &&
10574 hasSameType(First->getElementType(), Second->getElementType()) &&
10575 First->getVectorKind() != VectorKind::AltiVecPixel &&
10576 First->getVectorKind() != VectorKind::AltiVecBool &&
10579 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10580 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10583 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10585 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10587 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10589 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10591 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10593 return true;
10594
10595 return false;
10596}
10597
10598/// getRVVTypeSize - Return RVV vector register size.
10599static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10600 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10601 auto VScale = Context.getTargetInfo().getVScaleRange(
10602 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10603 if (!VScale)
10604 return 0;
10605
10606 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10607
10608 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10609 if (Info.ElementType == Context.BoolTy)
10610 EltSize = 1;
10611
10612 uint64_t MinElts = Info.EC.getKnownMinValue();
10613 return VScale->first * MinElts * EltSize;
10614}
10615
10617 QualType SecondType) {
10618 assert(
10619 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10620 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10621 "Expected RVV builtin type and vector type!");
10622
10623 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10624 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10625 if (const auto *VT = SecondType->getAs<VectorType>()) {
10626 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10628 return FirstType->isRVVVLSBuiltinType() &&
10629 Info.ElementType == BoolTy &&
10630 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10631 }
10632 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10634 return FirstType->isRVVVLSBuiltinType() &&
10635 Info.ElementType == BoolTy &&
10636 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10637 }
10638 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10640 return FirstType->isRVVVLSBuiltinType() &&
10641 Info.ElementType == BoolTy &&
10642 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10643 }
10644 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10646 return FirstType->isRVVVLSBuiltinType() &&
10647 Info.ElementType == BoolTy &&
10648 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10649 }
10650 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10651 VT->getVectorKind() == VectorKind::Generic)
10652 return FirstType->isRVVVLSBuiltinType() &&
10653 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10654 hasSameType(VT->getElementType(),
10655 getBuiltinVectorTypeInfo(BT).ElementType);
10656 }
10657 }
10658 return false;
10659 };
10660
10661 return IsValidCast(FirstType, SecondType) ||
10662 IsValidCast(SecondType, FirstType);
10663}
10664
10666 QualType SecondType) {
10667 assert(
10668 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10669 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10670 "Expected RVV builtin type and vector type!");
10671
10672 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10673 const auto *BT = FirstType->getAs<BuiltinType>();
10674 if (!BT)
10675 return false;
10676
10677 if (!BT->isRVVVLSBuiltinType())
10678 return false;
10679
10680 const auto *VecTy = SecondType->getAs<VectorType>();
10681 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10683 getLangOpts().getLaxVectorConversions();
10684
10685 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10686 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10687 return false;
10688
10689 // If -flax-vector-conversions=all is specified, the types are
10690 // certainly compatible.
10692 return true;
10693
10694 // If -flax-vector-conversions=integer is specified, the types are
10695 // compatible if the elements are integer types.
10697 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10698 FirstType->getRVVEltType(*this)->isIntegerType();
10699 }
10700
10701 return false;
10702 };
10703
10704 return IsLaxCompatible(FirstType, SecondType) ||
10705 IsLaxCompatible(SecondType, FirstType);
10706}
10707
10709 while (true) {
10710 // __strong id
10711 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10712 if (Attr->getAttrKind() == attr::ObjCOwnership)
10713 return true;
10714
10715 Ty = Attr->getModifiedType();
10716
10717 // X *__strong (...)
10718 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10719 Ty = Paren->getInnerType();
10720
10721 // We do not want to look through typedefs, typeof(expr),
10722 // typeof(type), or any other way that the type is somehow
10723 // abstracted.
10724 } else {
10725 return false;
10726 }
10727 }
10728}
10729
10730//===----------------------------------------------------------------------===//
10731// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10732//===----------------------------------------------------------------------===//
10733
10734/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10735/// inheritance hierarchy of 'rProto'.
10736bool
10738 ObjCProtocolDecl *rProto) const {
10739 if (declaresSameEntity(lProto, rProto))
10740 return true;
10741 for (auto *PI : rProto->protocols())
10742 if (ProtocolCompatibleWithProtocol(lProto, PI))
10743 return true;
10744 return false;
10745}
10746
10747/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10748/// Class<pr1, ...>.
10750 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10751 for (auto *lhsProto : lhs->quals()) {
10752 bool match = false;
10753 for (auto *rhsProto : rhs->quals()) {
10754 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10755 match = true;
10756 break;
10757 }
10758 }
10759 if (!match)
10760 return false;
10761 }
10762 return true;
10763}
10764
10765/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10766/// ObjCQualifiedIDType.
10768 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10769 bool compare) {
10770 // Allow id<P..> and an 'id' in all cases.
10771 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10772 return true;
10773
10774 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10775 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10777 return false;
10778
10779 if (lhs->isObjCQualifiedIdType()) {
10780 if (rhs->qual_empty()) {
10781 // If the RHS is a unqualified interface pointer "NSString*",
10782 // make sure we check the class hierarchy.
10783 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10784 for (auto *I : lhs->quals()) {
10785 // when comparing an id<P> on lhs with a static type on rhs,
10786 // see if static class implements all of id's protocols, directly or
10787 // through its super class and categories.
10788 if (!rhsID->ClassImplementsProtocol(I, true))
10789 return false;
10790 }
10791 }
10792 // If there are no qualifiers and no interface, we have an 'id'.
10793 return true;
10794 }
10795 // Both the right and left sides have qualifiers.
10796 for (auto *lhsProto : lhs->quals()) {
10797 bool match = false;
10798
10799 // when comparing an id<P> on lhs with a static type on rhs,
10800 // see if static class implements all of id's protocols, directly or
10801 // through its super class and categories.
10802 for (auto *rhsProto : rhs->quals()) {
10803 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10804 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10805 match = true;
10806 break;
10807 }
10808 }
10809 // If the RHS is a qualified interface pointer "NSString<P>*",
10810 // make sure we check the class hierarchy.
10811 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10812 for (auto *I : lhs->quals()) {
10813 // when comparing an id<P> on lhs with a static type on rhs,
10814 // see if static class implements all of id's protocols, directly or
10815 // through its super class and categories.
10816 if (rhsID->ClassImplementsProtocol(I, true)) {
10817 match = true;
10818 break;
10819 }
10820 }
10821 }
10822 if (!match)
10823 return false;
10824 }
10825
10826 return true;
10827 }
10828
10829 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10830
10831 if (lhs->getInterfaceType()) {
10832 // If both the right and left sides have qualifiers.
10833 for (auto *lhsProto : lhs->quals()) {
10834 bool match = false;
10835
10836 // when comparing an id<P> on rhs with a static type on lhs,
10837 // see if static class implements all of id's protocols, directly or
10838 // through its super class and categories.
10839 // First, lhs protocols in the qualifier list must be found, direct
10840 // or indirect in rhs's qualifier list or it is a mismatch.
10841 for (auto *rhsProto : rhs->quals()) {
10842 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10843 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10844 match = true;
10845 break;
10846 }
10847 }
10848 if (!match)
10849 return false;
10850 }
10851
10852 // Static class's protocols, or its super class or category protocols
10853 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10854 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10855 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10856 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10857 // This is rather dubious but matches gcc's behavior. If lhs has
10858 // no type qualifier and its class has no static protocol(s)
10859 // assume that it is mismatch.
10860 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10861 return false;
10862 for (auto *lhsProto : LHSInheritedProtocols) {
10863 bool match = false;
10864 for (auto *rhsProto : rhs->quals()) {
10865 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10866 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10867 match = true;
10868 break;
10869 }
10870 }
10871 if (!match)
10872 return false;
10873 }
10874 }
10875 return true;
10876 }
10877 return false;
10878}
10879
10880/// canAssignObjCInterfaces - Return true if the two interface types are
10881/// compatible for assignment from RHS to LHS. This handles validation of any
10882/// protocol qualifiers on the LHS or RHS.
10884 const ObjCObjectPointerType *RHSOPT) {
10885 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10886 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10887
10888 // If either type represents the built-in 'id' type, return true.
10889 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10890 return true;
10891
10892 // Function object that propagates a successful result or handles
10893 // __kindof types.
10894 auto finish = [&](bool succeeded) -> bool {
10895 if (succeeded)
10896 return true;
10897
10898 if (!RHS->isKindOfType())
10899 return false;
10900
10901 // Strip off __kindof and protocol qualifiers, then check whether
10902 // we can assign the other way.
10904 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10905 };
10906
10907 // Casts from or to id<P> are allowed when the other side has compatible
10908 // protocols.
10909 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10910 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10911 }
10912
10913 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10914 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10915 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10916 }
10917
10918 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10919 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10920 return true;
10921 }
10922
10923 // If we have 2 user-defined types, fall into that path.
10924 if (LHS->getInterface() && RHS->getInterface()) {
10925 return finish(canAssignObjCInterfaces(LHS, RHS));
10926 }
10927
10928 return false;
10929}
10930
10931/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10932/// for providing type-safety for objective-c pointers used to pass/return
10933/// arguments in block literals. When passed as arguments, passing 'A*' where
10934/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10935/// not OK. For the return type, the opposite is not OK.
10937 const ObjCObjectPointerType *LHSOPT,
10938 const ObjCObjectPointerType *RHSOPT,
10939 bool BlockReturnType) {
10940
10941 // Function object that propagates a successful result or handles
10942 // __kindof types.
10943 auto finish = [&](bool succeeded) -> bool {
10944 if (succeeded)
10945 return true;
10946
10947 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10948 if (!Expected->isKindOfType())
10949 return false;
10950
10951 // Strip off __kindof and protocol qualifiers, then check whether
10952 // we can assign the other way.
10954 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10955 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10956 BlockReturnType);
10957 };
10958
10959 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10960 return true;
10961
10962 if (LHSOPT->isObjCBuiltinType()) {
10963 return finish(RHSOPT->isObjCBuiltinType() ||
10964 RHSOPT->isObjCQualifiedIdType());
10965 }
10966
10967 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10968 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10969 // Use for block parameters previous type checking for compatibility.
10970 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10971 // Or corrected type checking as in non-compat mode.
10972 (!BlockReturnType &&
10973 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10974 else
10976 (BlockReturnType ? LHSOPT : RHSOPT),
10977 (BlockReturnType ? RHSOPT : LHSOPT), false));
10978 }
10979
10980 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10981 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10982 if (LHS && RHS) { // We have 2 user-defined types.
10983 if (LHS != RHS) {
10984 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10985 return finish(BlockReturnType);
10986 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10987 return finish(!BlockReturnType);
10988 }
10989 else
10990 return true;
10991 }
10992 return false;
10993}
10994
10995/// Comparison routine for Objective-C protocols to be used with
10996/// llvm::array_pod_sort.
10998 ObjCProtocolDecl * const *rhs) {
10999 return (*lhs)->getName().compare((*rhs)->getName());
11000}
11001
11002/// getIntersectionOfProtocols - This routine finds the intersection of set
11003/// of protocols inherited from two distinct objective-c pointer objects with
11004/// the given common base.
11005/// It is used to build composite qualifier list of the composite type of
11006/// the conditional expression involving two objective-c pointer objects.
11007static
11009 const ObjCInterfaceDecl *CommonBase,
11010 const ObjCObjectPointerType *LHSOPT,
11011 const ObjCObjectPointerType *RHSOPT,
11012 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11013
11014 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11015 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11016 assert(LHS->getInterface() && "LHS must have an interface base");
11017 assert(RHS->getInterface() && "RHS must have an interface base");
11018
11019 // Add all of the protocols for the LHS.
11021
11022 // Start with the protocol qualifiers.
11023 for (auto *proto : LHS->quals()) {
11024 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11025 }
11026
11027 // Also add the protocols associated with the LHS interface.
11028 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11029
11030 // Add all of the protocols for the RHS.
11032
11033 // Start with the protocol qualifiers.
11034 for (auto *proto : RHS->quals()) {
11035 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11036 }
11037
11038 // Also add the protocols associated with the RHS interface.
11039 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11040
11041 // Compute the intersection of the collected protocol sets.
11042 for (auto *proto : LHSProtocolSet) {
11043 if (RHSProtocolSet.count(proto))
11044 IntersectionSet.push_back(proto);
11045 }
11046
11047 // Compute the set of protocols that is implied by either the common type or
11048 // the protocols within the intersection.
11050 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11051
11052 // Remove any implied protocols from the list of inherited protocols.
11053 if (!ImpliedProtocols.empty()) {
11054 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11055 return ImpliedProtocols.contains(proto);
11056 });
11057 }
11058
11059 // Sort the remaining protocols by name.
11060 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11062}
11063
11064/// Determine whether the first type is a subtype of the second.
11066 QualType rhs) {
11067 // Common case: two object pointers.
11068 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11069 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11070 if (lhsOPT && rhsOPT)
11071 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11072
11073 // Two block pointers.
11074 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11075 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11076 if (lhsBlock && rhsBlock)
11077 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11078
11079 // If either is an unqualified 'id' and the other is a block, it's
11080 // acceptable.
11081 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11082 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11083 return true;
11084
11085 return false;
11086}
11087
11088// Check that the given Objective-C type argument lists are equivalent.
11090 const ObjCInterfaceDecl *iface,
11091 ArrayRef<QualType> lhsArgs,
11092 ArrayRef<QualType> rhsArgs,
11093 bool stripKindOf) {
11094 if (lhsArgs.size() != rhsArgs.size())
11095 return false;
11096
11097 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11098 if (!typeParams)
11099 return false;
11100
11101 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11102 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11103 continue;
11104
11105 switch (typeParams->begin()[i]->getVariance()) {
11107 if (!stripKindOf ||
11108 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11109 rhsArgs[i].stripObjCKindOfType(ctx))) {
11110 return false;
11111 }
11112 break;
11113
11115 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11116 return false;
11117 break;
11118
11120 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11121 return false;
11122 break;
11123 }
11124 }
11125
11126 return true;
11127}
11128
11130 const ObjCObjectPointerType *Lptr,
11131 const ObjCObjectPointerType *Rptr) {
11132 const ObjCObjectType *LHS = Lptr->getObjectType();
11133 const ObjCObjectType *RHS = Rptr->getObjectType();
11134 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11135 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11136
11137 if (!LDecl || !RDecl)
11138 return {};
11139
11140 // When either LHS or RHS is a kindof type, we should return a kindof type.
11141 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11142 // kindof(A).
11143 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11144
11145 // Follow the left-hand side up the class hierarchy until we either hit a
11146 // root or find the RHS. Record the ancestors in case we don't find it.
11147 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11148 LHSAncestors;
11149 while (true) {
11150 // Record this ancestor. We'll need this if the common type isn't in the
11151 // path from the LHS to the root.
11152 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11153
11154 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11155 // Get the type arguments.
11156 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11157 bool anyChanges = false;
11158 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11159 // Both have type arguments, compare them.
11160 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11161 LHS->getTypeArgs(), RHS->getTypeArgs(),
11162 /*stripKindOf=*/true))
11163 return {};
11164 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11165 // If only one has type arguments, the result will not have type
11166 // arguments.
11167 LHSTypeArgs = {};
11168 anyChanges = true;
11169 }
11170
11171 // Compute the intersection of protocols.
11173 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11174 Protocols);
11175 if (!Protocols.empty())
11176 anyChanges = true;
11177
11178 // If anything in the LHS will have changed, build a new result type.
11179 // If we need to return a kindof type but LHS is not a kindof type, we
11180 // build a new result type.
11181 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11182 QualType Result = getObjCInterfaceType(LHS->getInterface());
11183 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11184 anyKindOf || LHS->isKindOfType());
11186 }
11187
11188 return getObjCObjectPointerType(QualType(LHS, 0));
11189 }
11190
11191 // Find the superclass.
11192 QualType LHSSuperType = LHS->getSuperClassType();
11193 if (LHSSuperType.isNull())
11194 break;
11195
11196 LHS = LHSSuperType->castAs<ObjCObjectType>();
11197 }
11198
11199 // We didn't find anything by following the LHS to its root; now check
11200 // the RHS against the cached set of ancestors.
11201 while (true) {
11202 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11203 if (KnownLHS != LHSAncestors.end()) {
11204 LHS = KnownLHS->second;
11205
11206 // Get the type arguments.
11207 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11208 bool anyChanges = false;
11209 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11210 // Both have type arguments, compare them.
11211 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11212 LHS->getTypeArgs(), RHS->getTypeArgs(),
11213 /*stripKindOf=*/true))
11214 return {};
11215 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11216 // If only one has type arguments, the result will not have type
11217 // arguments.
11218 RHSTypeArgs = {};
11219 anyChanges = true;
11220 }
11221
11222 // Compute the intersection of protocols.
11224 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11225 Protocols);
11226 if (!Protocols.empty())
11227 anyChanges = true;
11228
11229 // If we need to return a kindof type but RHS is not a kindof type, we
11230 // build a new result type.
11231 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11232 QualType Result = getObjCInterfaceType(RHS->getInterface());
11233 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11234 anyKindOf || RHS->isKindOfType());
11236 }
11237
11238 return getObjCObjectPointerType(QualType(RHS, 0));
11239 }
11240
11241 // Find the superclass of the RHS.
11242 QualType RHSSuperType = RHS->getSuperClassType();
11243 if (RHSSuperType.isNull())
11244 break;
11245
11246 RHS = RHSSuperType->castAs<ObjCObjectType>();
11247 }
11248
11249 return {};
11250}
11251
11253 const ObjCObjectType *RHS) {
11254 assert(LHS->getInterface() && "LHS is not an interface type");
11255 assert(RHS->getInterface() && "RHS is not an interface type");
11256
11257 // Verify that the base decls are compatible: the RHS must be a subclass of
11258 // the LHS.
11259 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11260 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11261 if (!IsSuperClass)
11262 return false;
11263
11264 // If the LHS has protocol qualifiers, determine whether all of them are
11265 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11266 // LHS).
11267 if (LHS->getNumProtocols() > 0) {
11268 // OK if conversion of LHS to SuperClass results in narrowing of types
11269 // ; i.e., SuperClass may implement at least one of the protocols
11270 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11271 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11272 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11273 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11274 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11275 // qualifiers.
11276 for (auto *RHSPI : RHS->quals())
11277 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11278 // If there is no protocols associated with RHS, it is not a match.
11279 if (SuperClassInheritedProtocols.empty())
11280 return false;
11281
11282 for (const auto *LHSProto : LHS->quals()) {
11283 bool SuperImplementsProtocol = false;
11284 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11285 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11286 SuperImplementsProtocol = true;
11287 break;
11288 }
11289 if (!SuperImplementsProtocol)
11290 return false;
11291 }
11292 }
11293
11294 // If the LHS is specialized, we may need to check type arguments.
11295 if (LHS->isSpecialized()) {
11296 // Follow the superclass chain until we've matched the LHS class in the
11297 // hierarchy. This substitutes type arguments through.
11298 const ObjCObjectType *RHSSuper = RHS;
11299 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11300 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11301
11302 // If the RHS is specializd, compare type arguments.
11303 if (RHSSuper->isSpecialized() &&
11304 !sameObjCTypeArgs(*this, LHS->getInterface(),
11305 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11306 /*stripKindOf=*/true)) {
11307 return false;
11308 }
11309 }
11310
11311 return true;
11312}
11313
11315 // get the "pointed to" types
11316 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11317 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11318
11319 if (!LHSOPT || !RHSOPT)
11320 return false;
11321
11322 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11323 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11324}
11325
11328 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11329 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11330}
11331
11332/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11333/// both shall have the identically qualified version of a compatible type.
11334/// C99 6.2.7p1: Two types have compatible types if their types are the
11335/// same. See 6.7.[2,3,5] for additional rules.
11337 bool CompareUnqualified) {
11338 if (getLangOpts().CPlusPlus)
11339 return hasSameType(LHS, RHS);
11340
11341 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11342}
11343
11345 return typesAreCompatible(LHS, RHS);
11346}
11347
11349 return !mergeTypes(LHS, RHS, true).isNull();
11350}
11351
11352/// mergeTransparentUnionType - if T is a transparent union type and a member
11353/// of T is compatible with SubType, return the merged type, else return
11354/// QualType()
11356 bool OfBlockPointer,
11357 bool Unqualified) {
11358 if (const RecordType *UT = T->getAsUnionType()) {
11359 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11360 if (UD->hasAttr<TransparentUnionAttr>()) {
11361 for (const auto *I : UD->fields()) {
11362 QualType ET = I->getType().getUnqualifiedType();
11363 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11364 if (!MT.isNull())
11365 return MT;
11366 }
11367 }
11368 }
11369
11370 return {};
11371}
11372
11373/// mergeFunctionParameterTypes - merge two types which appear as function
11374/// parameter types
11376 bool OfBlockPointer,
11377 bool Unqualified) {
11378 // GNU extension: two types are compatible if they appear as a function
11379 // argument, one of the types is a transparent union type and the other
11380 // type is compatible with a union member
11381 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11382 Unqualified);
11383 if (!lmerge.isNull())
11384 return lmerge;
11385
11386 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11387 Unqualified);
11388 if (!rmerge.isNull())
11389 return rmerge;
11390
11391 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11392}
11393
11395 bool OfBlockPointer, bool Unqualified,
11396 bool AllowCXX,
11397 bool IsConditionalOperator) {
11398 const auto *lbase = lhs->castAs<FunctionType>();
11399 const auto *rbase = rhs->castAs<FunctionType>();
11400 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11401 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11402 bool allLTypes = true;
11403 bool allRTypes = true;
11404
11405 // Check return type
11406 QualType retType;
11407 if (OfBlockPointer) {
11408 QualType RHS = rbase->getReturnType();
11409 QualType LHS = lbase->getReturnType();
11410 bool UnqualifiedResult = Unqualified;
11411 if (!UnqualifiedResult)
11412 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11413 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11414 }
11415 else
11416 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11417 Unqualified);
11418 if (retType.isNull())
11419 return {};
11420
11421 if (Unqualified)
11422 retType = retType.getUnqualifiedType();
11423
11424 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11425 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11426 if (Unqualified) {
11427 LRetType = LRetType.getUnqualifiedType();
11428 RRetType = RRetType.getUnqualifiedType();
11429 }
11430
11431 if (getCanonicalType(retType) != LRetType)
11432 allLTypes = false;
11433 if (getCanonicalType(retType) != RRetType)
11434 allRTypes = false;
11435
11436 // FIXME: double check this
11437 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11438 // rbase->getRegParmAttr() != 0 &&
11439 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11440 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11441 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11442
11443 // Compatible functions must have compatible calling conventions
11444 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11445 return {};
11446
11447 // Regparm is part of the calling convention.
11448 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11449 return {};
11450 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11451 return {};
11452
11453 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11454 return {};
11455 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11456 return {};
11457 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11458 return {};
11459
11460 // When merging declarations, it's common for supplemental information like
11461 // attributes to only be present in one of the declarations, and we generally
11462 // want type merging to preserve the union of information. So a merged
11463 // function type should be noreturn if it was noreturn in *either* operand
11464 // type.
11465 //
11466 // But for the conditional operator, this is backwards. The result of the
11467 // operator could be either operand, and its type should conservatively
11468 // reflect that. So a function type in a composite type is noreturn only
11469 // if it's noreturn in *both* operand types.
11470 //
11471 // Arguably, noreturn is a kind of subtype, and the conditional operator
11472 // ought to produce the most specific common supertype of its operand types.
11473 // That would differ from this rule in contravariant positions. However,
11474 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11475 // as a practical matter, it would only affect C code that does abstraction of
11476 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11477 // say the least. So we use the simpler rule.
11478 bool NoReturn = IsConditionalOperator
11479 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11480 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11481 if (lbaseInfo.getNoReturn() != NoReturn)
11482 allLTypes = false;
11483 if (rbaseInfo.getNoReturn() != NoReturn)
11484 allRTypes = false;
11485
11486 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11487
11488 std::optional<FunctionEffectSet> MergedFX;
11489
11490 if (lproto && rproto) { // two C99 style function prototypes
11491 assert((AllowCXX ||
11492 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11493 "C++ shouldn't be here");
11494 // Compatible functions must have the same number of parameters
11495 if (lproto->getNumParams() != rproto->getNumParams())
11496 return {};
11497
11498 // Variadic and non-variadic functions aren't compatible
11499 if (lproto->isVariadic() != rproto->isVariadic())
11500 return {};
11501
11502 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11503 return {};
11504
11505 // Function protos with different 'cfi_salt' values aren't compatible.
11506 if (lproto->getExtraAttributeInfo().CFISalt !=
11507 rproto->getExtraAttributeInfo().CFISalt)
11508 return {};
11509
11510 // Function effects are handled similarly to noreturn, see above.
11511 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11512 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11513 if (LHSFX != RHSFX) {
11514 if (IsConditionalOperator)
11515 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11516 else {
11518 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11519 // Here we're discarding a possible error due to conflicts in the effect
11520 // sets. But we're not in a context where we can report it. The
11521 // operation does however guarantee maintenance of invariants.
11522 }
11523 if (*MergedFX != LHSFX)
11524 allLTypes = false;
11525 if (*MergedFX != RHSFX)
11526 allRTypes = false;
11527 }
11528
11530 bool canUseLeft, canUseRight;
11531 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11532 newParamInfos))
11533 return {};
11534
11535 if (!canUseLeft)
11536 allLTypes = false;
11537 if (!canUseRight)
11538 allRTypes = false;
11539
11540 // Check parameter type compatibility
11542 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11543 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11544 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11546 lParamType, rParamType, OfBlockPointer, Unqualified);
11547 if (paramType.isNull())
11548 return {};
11549
11550 if (Unqualified)
11551 paramType = paramType.getUnqualifiedType();
11552
11553 types.push_back(paramType);
11554 if (Unqualified) {
11555 lParamType = lParamType.getUnqualifiedType();
11556 rParamType = rParamType.getUnqualifiedType();
11557 }
11558
11559 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11560 allLTypes = false;
11561 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11562 allRTypes = false;
11563 }
11564
11565 if (allLTypes) return lhs;
11566 if (allRTypes) return rhs;
11567
11568 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11569 EPI.ExtInfo = einfo;
11570 EPI.ExtParameterInfos =
11571 newParamInfos.empty() ? nullptr : newParamInfos.data();
11572 if (MergedFX)
11573 EPI.FunctionEffects = *MergedFX;
11574 return getFunctionType(retType, types, EPI);
11575 }
11576
11577 if (lproto) allRTypes = false;
11578 if (rproto) allLTypes = false;
11579
11580 const FunctionProtoType *proto = lproto ? lproto : rproto;
11581 if (proto) {
11582 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11583 if (proto->isVariadic())
11584 return {};
11585 // Check that the types are compatible with the types that
11586 // would result from default argument promotions (C99 6.7.5.3p15).
11587 // The only types actually affected are promotable integer
11588 // types and floats, which would be passed as a different
11589 // type depending on whether the prototype is visible.
11590 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11591 QualType paramTy = proto->getParamType(i);
11592
11593 // Look at the converted type of enum types, since that is the type used
11594 // to pass enum values.
11595 if (const auto *ED = paramTy->getAsEnumDecl()) {
11596 paramTy = ED->getIntegerType();
11597 if (paramTy.isNull())
11598 return {};
11599 }
11600
11601 if (isPromotableIntegerType(paramTy) ||
11602 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11603 return {};
11604 }
11605
11606 if (allLTypes) return lhs;
11607 if (allRTypes) return rhs;
11608
11610 EPI.ExtInfo = einfo;
11611 if (MergedFX)
11612 EPI.FunctionEffects = *MergedFX;
11613 return getFunctionType(retType, proto->getParamTypes(), EPI);
11614 }
11615
11616 if (allLTypes) return lhs;
11617 if (allRTypes) return rhs;
11618 return getFunctionNoProtoType(retType, einfo);
11619}
11620
11621/// Given that we have an enum type and a non-enum type, try to merge them.
11622static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11623 QualType other, bool isBlockReturnType) {
11624 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11625 // a signed integer type, or an unsigned integer type.
11626 // Compatibility is based on the underlying type, not the promotion
11627 // type.
11628 QualType underlyingType =
11629 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11630 if (underlyingType.isNull())
11631 return {};
11632 if (Context.hasSameType(underlyingType, other))
11633 return other;
11634
11635 // In block return types, we're more permissive and accept any
11636 // integral type of the same size.
11637 if (isBlockReturnType && other->isIntegerType() &&
11638 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11639 return other;
11640
11641 return {};
11642}
11643
11645 // C17 and earlier and C++ disallow two tag definitions within the same TU
11646 // from being compatible.
11647 if (LangOpts.CPlusPlus || !LangOpts.C23)
11648 return {};
11649
11650 // C23, on the other hand, requires the members to be "the same enough", so
11651 // we use a structural equivalence check.
11654 getLangOpts(), *this, *this, NonEquivalentDecls,
11655 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11656 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11657 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11658}
11659
11660QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11661 bool Unqualified, bool BlockReturnType,
11662 bool IsConditionalOperator) {
11663 // For C++ we will not reach this code with reference types (see below),
11664 // for OpenMP variant call overloading we might.
11665 //
11666 // C++ [expr]: If an expression initially has the type "reference to T", the
11667 // type is adjusted to "T" prior to any further analysis, the expression
11668 // designates the object or function denoted by the reference, and the
11669 // expression is an lvalue unless the reference is an rvalue reference and
11670 // the expression is a function call (possibly inside parentheses).
11671 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11672 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11673 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11674 LHS->getTypeClass() == RHS->getTypeClass())
11675 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11676 OfBlockPointer, Unqualified, BlockReturnType);
11677 if (LHSRefTy || RHSRefTy)
11678 return {};
11679
11680 if (Unqualified) {
11681 LHS = LHS.getUnqualifiedType();
11682 RHS = RHS.getUnqualifiedType();
11683 }
11684
11685 QualType LHSCan = getCanonicalType(LHS),
11686 RHSCan = getCanonicalType(RHS);
11687
11688 // If two types are identical, they are compatible.
11689 if (LHSCan == RHSCan)
11690 return LHS;
11691
11692 // If the qualifiers are different, the types aren't compatible... mostly.
11693 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11694 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11695 if (LQuals != RQuals) {
11696 // If any of these qualifiers are different, we have a type
11697 // mismatch.
11698 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11699 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11700 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11701 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11702 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11703 return {};
11704
11705 // Exactly one GC qualifier difference is allowed: __strong is
11706 // okay if the other type has no GC qualifier but is an Objective
11707 // C object pointer (i.e. implicitly strong by default). We fix
11708 // this by pretending that the unqualified type was actually
11709 // qualified __strong.
11710 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11711 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11712 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11713
11714 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11715 return {};
11716
11717 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11719 }
11720 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11722 }
11723 return {};
11724 }
11725
11726 // Okay, qualifiers are equal.
11727
11728 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11729 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11730
11731 // We want to consider the two function types to be the same for these
11732 // comparisons, just force one to the other.
11733 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11734 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11735
11736 // Same as above for arrays
11737 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11738 LHSClass = Type::ConstantArray;
11739 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11740 RHSClass = Type::ConstantArray;
11741
11742 // ObjCInterfaces are just specialized ObjCObjects.
11743 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11744 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11745
11746 // Canonicalize ExtVector -> Vector.
11747 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11748 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11749
11750 // If the canonical type classes don't match.
11751 if (LHSClass != RHSClass) {
11752 // Note that we only have special rules for turning block enum
11753 // returns into block int returns, not vice-versa.
11754 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11755 return mergeEnumWithInteger(*this, ETy, RHS, false);
11756 }
11757 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11758 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11759 }
11760 // allow block pointer type to match an 'id' type.
11761 if (OfBlockPointer && !BlockReturnType) {
11762 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11763 return LHS;
11764 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11765 return RHS;
11766 }
11767 // Allow __auto_type to match anything; it merges to the type with more
11768 // information.
11769 if (const auto *AT = LHS->getAs<AutoType>()) {
11770 if (!AT->isDeduced() && AT->isGNUAutoType())
11771 return RHS;
11772 }
11773 if (const auto *AT = RHS->getAs<AutoType>()) {
11774 if (!AT->isDeduced() && AT->isGNUAutoType())
11775 return LHS;
11776 }
11777 return {};
11778 }
11779
11780 // The canonical type classes match.
11781 switch (LHSClass) {
11782#define TYPE(Class, Base)
11783#define ABSTRACT_TYPE(Class, Base)
11784#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11785#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11786#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11787#include "clang/AST/TypeNodes.inc"
11788 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11789
11790 case Type::Auto:
11791 case Type::DeducedTemplateSpecialization:
11792 case Type::LValueReference:
11793 case Type::RValueReference:
11794 case Type::MemberPointer:
11795 llvm_unreachable("C++ should never be in mergeTypes");
11796
11797 case Type::ObjCInterface:
11798 case Type::IncompleteArray:
11799 case Type::VariableArray:
11800 case Type::FunctionProto:
11801 case Type::ExtVector:
11802 llvm_unreachable("Types are eliminated above");
11803
11804 case Type::Pointer:
11805 {
11806 // Merge two pointer types, while trying to preserve typedef info
11807 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11808 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11809 if (Unqualified) {
11810 LHSPointee = LHSPointee.getUnqualifiedType();
11811 RHSPointee = RHSPointee.getUnqualifiedType();
11812 }
11813 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11814 Unqualified);
11815 if (ResultType.isNull())
11816 return {};
11817 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11818 return LHS;
11819 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11820 return RHS;
11821 return getPointerType(ResultType);
11822 }
11823 case Type::BlockPointer:
11824 {
11825 // Merge two block pointer types, while trying to preserve typedef info
11826 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11827 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11828 if (Unqualified) {
11829 LHSPointee = LHSPointee.getUnqualifiedType();
11830 RHSPointee = RHSPointee.getUnqualifiedType();
11831 }
11832 if (getLangOpts().OpenCL) {
11833 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11834 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11835 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11836 // 6.12.5) thus the following check is asymmetric.
11837 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11838 return {};
11839 LHSPteeQual.removeAddressSpace();
11840 RHSPteeQual.removeAddressSpace();
11841 LHSPointee =
11842 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11843 RHSPointee =
11844 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11845 }
11846 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11847 Unqualified);
11848 if (ResultType.isNull())
11849 return {};
11850 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11851 return LHS;
11852 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11853 return RHS;
11854 return getBlockPointerType(ResultType);
11855 }
11856 case Type::Atomic:
11857 {
11858 // Merge two pointer types, while trying to preserve typedef info
11859 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11860 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11861 if (Unqualified) {
11862 LHSValue = LHSValue.getUnqualifiedType();
11863 RHSValue = RHSValue.getUnqualifiedType();
11864 }
11865 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11866 Unqualified);
11867 if (ResultType.isNull())
11868 return {};
11869 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11870 return LHS;
11871 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11872 return RHS;
11873 return getAtomicType(ResultType);
11874 }
11875 case Type::ConstantArray:
11876 {
11877 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11878 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11879 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11880 return {};
11881
11882 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11883 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11884 if (Unqualified) {
11885 LHSElem = LHSElem.getUnqualifiedType();
11886 RHSElem = RHSElem.getUnqualifiedType();
11887 }
11888
11889 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11890 if (ResultType.isNull())
11891 return {};
11892
11893 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11894 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11895
11896 // If either side is a variable array, and both are complete, check whether
11897 // the current dimension is definite.
11898 if (LVAT || RVAT) {
11899 auto SizeFetch = [this](const VariableArrayType* VAT,
11900 const ConstantArrayType* CAT)
11901 -> std::pair<bool,llvm::APInt> {
11902 if (VAT) {
11903 std::optional<llvm::APSInt> TheInt;
11904 Expr *E = VAT->getSizeExpr();
11905 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11906 return std::make_pair(true, *TheInt);
11907 return std::make_pair(false, llvm::APSInt());
11908 }
11909 if (CAT)
11910 return std::make_pair(true, CAT->getSize());
11911 return std::make_pair(false, llvm::APInt());
11912 };
11913
11914 bool HaveLSize, HaveRSize;
11915 llvm::APInt LSize, RSize;
11916 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11917 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11918 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11919 return {}; // Definite, but unequal, array dimension
11920 }
11921
11922 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11923 return LHS;
11924 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11925 return RHS;
11926 if (LCAT)
11927 return getConstantArrayType(ResultType, LCAT->getSize(),
11928 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11929 if (RCAT)
11930 return getConstantArrayType(ResultType, RCAT->getSize(),
11931 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11932 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11933 return LHS;
11934 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11935 return RHS;
11936 if (LVAT) {
11937 // FIXME: This isn't correct! But tricky to implement because
11938 // the array's size has to be the size of LHS, but the type
11939 // has to be different.
11940 return LHS;
11941 }
11942 if (RVAT) {
11943 // FIXME: This isn't correct! But tricky to implement because
11944 // the array's size has to be the size of RHS, but the type
11945 // has to be different.
11946 return RHS;
11947 }
11948 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11949 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11950 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11951 }
11952 case Type::FunctionNoProto:
11953 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11954 /*AllowCXX=*/false, IsConditionalOperator);
11955 case Type::Record:
11956 case Type::Enum:
11957 return mergeTagDefinitions(LHS, RHS);
11958 case Type::Builtin:
11959 // Only exactly equal builtin types are compatible, which is tested above.
11960 return {};
11961 case Type::Complex:
11962 // Distinct complex types are incompatible.
11963 return {};
11964 case Type::Vector:
11965 // FIXME: The merged type should be an ExtVector!
11966 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11967 RHSCan->castAs<VectorType>()))
11968 return LHS;
11969 return {};
11970 case Type::ConstantMatrix:
11972 RHSCan->castAs<ConstantMatrixType>()))
11973 return LHS;
11974 return {};
11975 case Type::ObjCObject: {
11976 // Check if the types are assignment compatible.
11977 // FIXME: This should be type compatibility, e.g. whether
11978 // "LHS x; RHS x;" at global scope is legal.
11980 RHS->castAs<ObjCObjectType>()))
11981 return LHS;
11982 return {};
11983 }
11984 case Type::ObjCObjectPointer:
11985 if (OfBlockPointer) {
11988 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11989 return LHS;
11990 return {};
11991 }
11994 return LHS;
11995 return {};
11996 case Type::Pipe:
11997 assert(LHS != RHS &&
11998 "Equivalent pipe types should have already been handled!");
11999 return {};
12000 case Type::ArrayParameter:
12001 assert(LHS != RHS &&
12002 "Equivalent ArrayParameter types should have already been handled!");
12003 return {};
12004 case Type::BitInt: {
12005 // Merge two bit-precise int types, while trying to preserve typedef info.
12006 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12007 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12008 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12009 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12010
12011 // Like unsigned/int, shouldn't have a type if they don't match.
12012 if (LHSUnsigned != RHSUnsigned)
12013 return {};
12014
12015 if (LHSBits != RHSBits)
12016 return {};
12017 return LHS;
12018 }
12019 case Type::HLSLAttributedResource: {
12020 const HLSLAttributedResourceType *LHSTy =
12021 LHS->castAs<HLSLAttributedResourceType>();
12022 const HLSLAttributedResourceType *RHSTy =
12023 RHS->castAs<HLSLAttributedResourceType>();
12024 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12025 LHSTy->getWrappedType()->isHLSLResourceType() &&
12026 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12027
12028 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12029 LHSTy->getContainedType() == RHSTy->getContainedType())
12030 return LHS;
12031 return {};
12032 }
12033 case Type::HLSLInlineSpirv:
12034 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12035 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12036
12037 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12038 LHSTy->getSize() == RHSTy->getSize() &&
12039 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12040 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12041 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12042 return {};
12043
12044 return LHS;
12045 }
12046 return {};
12047 }
12048
12049 llvm_unreachable("Invalid Type::Class!");
12050}
12051
12053 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12054 bool &CanUseFirst, bool &CanUseSecond,
12056 assert(NewParamInfos.empty() && "param info list not empty");
12057 CanUseFirst = CanUseSecond = true;
12058 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12059 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12060
12061 // Fast path: if the first type doesn't have ext parameter infos,
12062 // we match if and only if the second type also doesn't have them.
12063 if (!FirstHasInfo && !SecondHasInfo)
12064 return true;
12065
12066 bool NeedParamInfo = false;
12067 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12068 : SecondFnType->getExtParameterInfos().size();
12069
12070 for (size_t I = 0; I < E; ++I) {
12071 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12072 if (FirstHasInfo)
12073 FirstParam = FirstFnType->getExtParameterInfo(I);
12074 if (SecondHasInfo)
12075 SecondParam = SecondFnType->getExtParameterInfo(I);
12076
12077 // Cannot merge unless everything except the noescape flag matches.
12078 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12079 return false;
12080
12081 bool FirstNoEscape = FirstParam.isNoEscape();
12082 bool SecondNoEscape = SecondParam.isNoEscape();
12083 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12084 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12085 if (NewParamInfos.back().getOpaqueValue())
12086 NeedParamInfo = true;
12087 if (FirstNoEscape != IsNoEscape)
12088 CanUseFirst = false;
12089 if (SecondNoEscape != IsNoEscape)
12090 CanUseSecond = false;
12091 }
12092
12093 if (!NeedParamInfo)
12094 NewParamInfos.clear();
12095
12096 return true;
12097}
12098
12100 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12101 It->second = nullptr;
12102 for (auto *SubClass : ObjCSubClasses[D])
12103 ResetObjCLayout(SubClass);
12104 }
12105}
12106
12107/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12108/// 'RHS' attributes and returns the merged version; including for function
12109/// return types.
12111 QualType LHSCan = getCanonicalType(LHS),
12112 RHSCan = getCanonicalType(RHS);
12113 // If two types are identical, they are compatible.
12114 if (LHSCan == RHSCan)
12115 return LHS;
12116 if (RHSCan->isFunctionType()) {
12117 if (!LHSCan->isFunctionType())
12118 return {};
12119 QualType OldReturnType =
12120 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12121 QualType NewReturnType =
12122 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12123 QualType ResReturnType =
12124 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12125 if (ResReturnType.isNull())
12126 return {};
12127 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12128 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12129 // In either case, use OldReturnType to build the new function type.
12130 const auto *F = LHS->castAs<FunctionType>();
12131 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12132 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12133 EPI.ExtInfo = getFunctionExtInfo(LHS);
12134 QualType ResultType =
12135 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12136 return ResultType;
12137 }
12138 }
12139 return {};
12140 }
12141
12142 // If the qualifiers are different, the types can still be merged.
12143 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12144 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12145 if (LQuals != RQuals) {
12146 // If any of these qualifiers are different, we have a type mismatch.
12147 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12148 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12149 return {};
12150
12151 // Exactly one GC qualifier difference is allowed: __strong is
12152 // okay if the other type has no GC qualifier but is an Objective
12153 // C object pointer (i.e. implicitly strong by default). We fix
12154 // this by pretending that the unqualified type was actually
12155 // qualified __strong.
12156 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12157 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12158 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12159
12160 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12161 return {};
12162
12163 if (GC_L == Qualifiers::Strong)
12164 return LHS;
12165 if (GC_R == Qualifiers::Strong)
12166 return RHS;
12167 return {};
12168 }
12169
12170 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12171 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12172 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12173 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12174 if (ResQT == LHSBaseQT)
12175 return LHS;
12176 if (ResQT == RHSBaseQT)
12177 return RHS;
12178 }
12179 return {};
12180}
12181
12182//===----------------------------------------------------------------------===//
12183// Integer Predicates
12184//===----------------------------------------------------------------------===//
12185
12187 if (const auto *ED = T->getAsEnumDecl())
12188 T = ED->getIntegerType();
12189 if (T->isBooleanType())
12190 return 1;
12191 if (const auto *EIT = T->getAs<BitIntType>())
12192 return EIT->getNumBits();
12193 // For builtin types, just use the standard type sizing method
12194 return (unsigned)getTypeSize(T);
12195}
12196
12198 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12199 T->isFixedPointType()) &&
12200 "Unexpected type");
12201
12202 // Turn <4 x signed int> -> <4 x unsigned int>
12203 if (const auto *VTy = T->getAs<VectorType>())
12204 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12205 VTy->getNumElements(), VTy->getVectorKind());
12206
12207 // For _BitInt, return an unsigned _BitInt with same width.
12208 if (const auto *EITy = T->getAs<BitIntType>())
12209 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12210
12211 // For enums, get the underlying integer type of the enum, and let the general
12212 // integer type signchanging code handle it.
12213 if (const auto *ED = T->getAsEnumDecl())
12214 T = ED->getIntegerType();
12215
12216 switch (T->castAs<BuiltinType>()->getKind()) {
12217 case BuiltinType::Char_U:
12218 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12219 case BuiltinType::Char_S:
12220 case BuiltinType::SChar:
12221 case BuiltinType::Char8:
12222 return UnsignedCharTy;
12223 case BuiltinType::Short:
12224 return UnsignedShortTy;
12225 case BuiltinType::Int:
12226 return UnsignedIntTy;
12227 case BuiltinType::Long:
12228 return UnsignedLongTy;
12229 case BuiltinType::LongLong:
12230 return UnsignedLongLongTy;
12231 case BuiltinType::Int128:
12232 return UnsignedInt128Ty;
12233 // wchar_t is special. It is either signed or not, but when it's signed,
12234 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12235 // version of its underlying type instead.
12236 case BuiltinType::WChar_S:
12237 return getUnsignedWCharType();
12238
12239 case BuiltinType::ShortAccum:
12240 return UnsignedShortAccumTy;
12241 case BuiltinType::Accum:
12242 return UnsignedAccumTy;
12243 case BuiltinType::LongAccum:
12244 return UnsignedLongAccumTy;
12245 case BuiltinType::SatShortAccum:
12247 case BuiltinType::SatAccum:
12248 return SatUnsignedAccumTy;
12249 case BuiltinType::SatLongAccum:
12251 case BuiltinType::ShortFract:
12252 return UnsignedShortFractTy;
12253 case BuiltinType::Fract:
12254 return UnsignedFractTy;
12255 case BuiltinType::LongFract:
12256 return UnsignedLongFractTy;
12257 case BuiltinType::SatShortFract:
12259 case BuiltinType::SatFract:
12260 return SatUnsignedFractTy;
12261 case BuiltinType::SatLongFract:
12263 default:
12264 assert((T->hasUnsignedIntegerRepresentation() ||
12265 T->isUnsignedFixedPointType()) &&
12266 "Unexpected signed integer or fixed point type");
12267 return T;
12268 }
12269}
12270
12272 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12273 T->isFixedPointType()) &&
12274 "Unexpected type");
12275
12276 // Turn <4 x unsigned int> -> <4 x signed int>
12277 if (const auto *VTy = T->getAs<VectorType>())
12278 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12279 VTy->getNumElements(), VTy->getVectorKind());
12280
12281 // For _BitInt, return a signed _BitInt with same width.
12282 if (const auto *EITy = T->getAs<BitIntType>())
12283 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12284
12285 // For enums, get the underlying integer type of the enum, and let the general
12286 // integer type signchanging code handle it.
12287 if (const auto *ED = T->getAsEnumDecl())
12288 T = ED->getIntegerType();
12289
12290 switch (T->castAs<BuiltinType>()->getKind()) {
12291 case BuiltinType::Char_S:
12292 // Plain `char` is mapped to `signed char` even if it's already signed
12293 case BuiltinType::Char_U:
12294 case BuiltinType::UChar:
12295 case BuiltinType::Char8:
12296 return SignedCharTy;
12297 case BuiltinType::UShort:
12298 return ShortTy;
12299 case BuiltinType::UInt:
12300 return IntTy;
12301 case BuiltinType::ULong:
12302 return LongTy;
12303 case BuiltinType::ULongLong:
12304 return LongLongTy;
12305 case BuiltinType::UInt128:
12306 return Int128Ty;
12307 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12308 // there's no matching "signed wchar_t". Therefore we return the signed
12309 // version of its underlying type instead.
12310 case BuiltinType::WChar_U:
12311 return getSignedWCharType();
12312
12313 case BuiltinType::UShortAccum:
12314 return ShortAccumTy;
12315 case BuiltinType::UAccum:
12316 return AccumTy;
12317 case BuiltinType::ULongAccum:
12318 return LongAccumTy;
12319 case BuiltinType::SatUShortAccum:
12320 return SatShortAccumTy;
12321 case BuiltinType::SatUAccum:
12322 return SatAccumTy;
12323 case BuiltinType::SatULongAccum:
12324 return SatLongAccumTy;
12325 case BuiltinType::UShortFract:
12326 return ShortFractTy;
12327 case BuiltinType::UFract:
12328 return FractTy;
12329 case BuiltinType::ULongFract:
12330 return LongFractTy;
12331 case BuiltinType::SatUShortFract:
12332 return SatShortFractTy;
12333 case BuiltinType::SatUFract:
12334 return SatFractTy;
12335 case BuiltinType::SatULongFract:
12336 return SatLongFractTy;
12337 default:
12338 assert(
12339 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12340 "Unexpected signed integer or fixed point type");
12341 return T;
12342 }
12343}
12344
12346
12349
12350//===----------------------------------------------------------------------===//
12351// Builtin Type Computation
12352//===----------------------------------------------------------------------===//
12353
12354/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12355/// pointer over the consumed characters. This returns the resultant type. If
12356/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12357/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12358/// a vector of "i*".
12359///
12360/// RequiresICE is filled in on return to indicate whether the value is required
12361/// to be an Integer Constant Expression.
12362static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12364 bool &RequiresICE,
12365 bool AllowTypeModifiers) {
12366 // Modifiers.
12367 int HowLong = 0;
12368 bool Signed = false, Unsigned = false;
12369 RequiresICE = false;
12370
12371 // Read the prefixed modifiers first.
12372 bool Done = false;
12373 #ifndef NDEBUG
12374 bool IsSpecial = false;
12375 #endif
12376 while (!Done) {
12377 switch (*Str++) {
12378 default: Done = true; --Str; break;
12379 case 'I':
12380 RequiresICE = true;
12381 break;
12382 case 'S':
12383 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12384 assert(!Signed && "Can't use 'S' modifier multiple times!");
12385 Signed = true;
12386 break;
12387 case 'U':
12388 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12389 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12390 Unsigned = true;
12391 break;
12392 case 'L':
12393 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12394 assert(HowLong <= 2 && "Can't have LLLL modifier");
12395 ++HowLong;
12396 break;
12397 case 'N':
12398 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12399 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12400 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12401 #ifndef NDEBUG
12402 IsSpecial = true;
12403 #endif
12404 if (Context.getTargetInfo().getLongWidth() == 32)
12405 ++HowLong;
12406 break;
12407 case 'W':
12408 // This modifier represents int64 type.
12409 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12410 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12411 #ifndef NDEBUG
12412 IsSpecial = true;
12413 #endif
12414 switch (Context.getTargetInfo().getInt64Type()) {
12415 default:
12416 llvm_unreachable("Unexpected integer type");
12418 HowLong = 1;
12419 break;
12421 HowLong = 2;
12422 break;
12423 }
12424 break;
12425 case 'Z':
12426 // This modifier represents int32 type.
12427 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12428 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12429 #ifndef NDEBUG
12430 IsSpecial = true;
12431 #endif
12432 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12433 default:
12434 llvm_unreachable("Unexpected integer type");
12436 HowLong = 0;
12437 break;
12439 HowLong = 1;
12440 break;
12442 HowLong = 2;
12443 break;
12444 }
12445 break;
12446 case 'O':
12447 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12448 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12449 #ifndef NDEBUG
12450 IsSpecial = true;
12451 #endif
12452 if (Context.getLangOpts().OpenCL)
12453 HowLong = 1;
12454 else
12455 HowLong = 2;
12456 break;
12457 }
12458 }
12459
12460 QualType Type;
12461
12462 // Read the base type.
12463 switch (*Str++) {
12464 default: llvm_unreachable("Unknown builtin type letter!");
12465 case 'x':
12466 assert(HowLong == 0 && !Signed && !Unsigned &&
12467 "Bad modifiers used with 'x'!");
12468 Type = Context.Float16Ty;
12469 break;
12470 case 'y':
12471 assert(HowLong == 0 && !Signed && !Unsigned &&
12472 "Bad modifiers used with 'y'!");
12473 Type = Context.BFloat16Ty;
12474 break;
12475 case 'v':
12476 assert(HowLong == 0 && !Signed && !Unsigned &&
12477 "Bad modifiers used with 'v'!");
12478 Type = Context.VoidTy;
12479 break;
12480 case 'h':
12481 assert(HowLong == 0 && !Signed && !Unsigned &&
12482 "Bad modifiers used with 'h'!");
12483 Type = Context.HalfTy;
12484 break;
12485 case 'f':
12486 assert(HowLong == 0 && !Signed && !Unsigned &&
12487 "Bad modifiers used with 'f'!");
12488 Type = Context.FloatTy;
12489 break;
12490 case 'd':
12491 assert(HowLong < 3 && !Signed && !Unsigned &&
12492 "Bad modifiers used with 'd'!");
12493 if (HowLong == 1)
12494 Type = Context.LongDoubleTy;
12495 else if (HowLong == 2)
12496 Type = Context.Float128Ty;
12497 else
12498 Type = Context.DoubleTy;
12499 break;
12500 case 's':
12501 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12502 if (Unsigned)
12503 Type = Context.UnsignedShortTy;
12504 else
12505 Type = Context.ShortTy;
12506 break;
12507 case 'i':
12508 if (HowLong == 3)
12509 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12510 else if (HowLong == 2)
12511 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12512 else if (HowLong == 1)
12513 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12514 else
12515 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12516 break;
12517 case 'c':
12518 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12519 if (Signed)
12520 Type = Context.SignedCharTy;
12521 else if (Unsigned)
12522 Type = Context.UnsignedCharTy;
12523 else
12524 Type = Context.CharTy;
12525 break;
12526 case 'b': // boolean
12527 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12528 Type = Context.BoolTy;
12529 break;
12530 case 'z': // size_t.
12531 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12532 Type = Context.getSizeType();
12533 break;
12534 case 'w': // wchar_t.
12535 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12536 Type = Context.getWideCharType();
12537 break;
12538 case 'F':
12539 Type = Context.getCFConstantStringType();
12540 break;
12541 case 'G':
12542 Type = Context.getObjCIdType();
12543 break;
12544 case 'H':
12545 Type = Context.getObjCSelType();
12546 break;
12547 case 'M':
12548 Type = Context.getObjCSuperType();
12549 break;
12550 case 'a':
12551 Type = Context.getBuiltinVaListType();
12552 assert(!Type.isNull() && "builtin va list type not initialized!");
12553 break;
12554 case 'A':
12555 // This is a "reference" to a va_list; however, what exactly
12556 // this means depends on how va_list is defined. There are two
12557 // different kinds of va_list: ones passed by value, and ones
12558 // passed by reference. An example of a by-value va_list is
12559 // x86, where va_list is a char*. An example of by-ref va_list
12560 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12561 // we want this argument to be a char*&; for x86-64, we want
12562 // it to be a __va_list_tag*.
12563 Type = Context.getBuiltinVaListType();
12564 assert(!Type.isNull() && "builtin va list type not initialized!");
12565 if (Type->isArrayType())
12566 Type = Context.getArrayDecayedType(Type);
12567 else
12568 Type = Context.getLValueReferenceType(Type);
12569 break;
12570 case 'q': {
12571 char *End;
12572 unsigned NumElements = strtoul(Str, &End, 10);
12573 assert(End != Str && "Missing vector size");
12574 Str = End;
12575
12576 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12577 RequiresICE, false);
12578 assert(!RequiresICE && "Can't require vector ICE");
12579
12580 Type = Context.getScalableVectorType(ElementType, NumElements);
12581 break;
12582 }
12583 case 'Q': {
12584 switch (*Str++) {
12585 case 'a': {
12586 Type = Context.SveCountTy;
12587 break;
12588 }
12589 case 'b': {
12590 Type = Context.AMDGPUBufferRsrcTy;
12591 break;
12592 }
12593 default:
12594 llvm_unreachable("Unexpected target builtin type");
12595 }
12596 break;
12597 }
12598 case 'V': {
12599 char *End;
12600 unsigned NumElements = strtoul(Str, &End, 10);
12601 assert(End != Str && "Missing vector size");
12602 Str = End;
12603
12604 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12605 RequiresICE, false);
12606 assert(!RequiresICE && "Can't require vector ICE");
12607
12608 // TODO: No way to make AltiVec vectors in builtins yet.
12609 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12610 break;
12611 }
12612 case 'E': {
12613 char *End;
12614
12615 unsigned NumElements = strtoul(Str, &End, 10);
12616 assert(End != Str && "Missing vector size");
12617
12618 Str = End;
12619
12620 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12621 false);
12622 Type = Context.getExtVectorType(ElementType, NumElements);
12623 break;
12624 }
12625 case 'X': {
12626 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12627 false);
12628 assert(!RequiresICE && "Can't require complex ICE");
12629 Type = Context.getComplexType(ElementType);
12630 break;
12631 }
12632 case 'Y':
12633 Type = Context.getPointerDiffType();
12634 break;
12635 case 'P':
12636 Type = Context.getFILEType();
12637 if (Type.isNull()) {
12639 return {};
12640 }
12641 break;
12642 case 'J':
12643 if (Signed)
12644 Type = Context.getsigjmp_bufType();
12645 else
12646 Type = Context.getjmp_bufType();
12647
12648 if (Type.isNull()) {
12650 return {};
12651 }
12652 break;
12653 case 'K':
12654 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12655 Type = Context.getucontext_tType();
12656
12657 if (Type.isNull()) {
12659 return {};
12660 }
12661 break;
12662 case 'p':
12663 Type = Context.getProcessIDType();
12664 break;
12665 case 'm':
12666 Type = Context.MFloat8Ty;
12667 break;
12668 }
12669
12670 // If there are modifiers and if we're allowed to parse them, go for it.
12671 Done = !AllowTypeModifiers;
12672 while (!Done) {
12673 switch (char c = *Str++) {
12674 default: Done = true; --Str; break;
12675 case '*':
12676 case '&': {
12677 // Both pointers and references can have their pointee types
12678 // qualified with an address space.
12679 char *End;
12680 unsigned AddrSpace = strtoul(Str, &End, 10);
12681 if (End != Str) {
12682 // Note AddrSpace == 0 is not the same as an unspecified address space.
12683 Type = Context.getAddrSpaceQualType(
12684 Type,
12685 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12686 Str = End;
12687 }
12688 if (c == '*')
12689 Type = Context.getPointerType(Type);
12690 else
12691 Type = Context.getLValueReferenceType(Type);
12692 break;
12693 }
12694 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12695 case 'C':
12696 Type = Type.withConst();
12697 break;
12698 case 'D':
12699 Type = Context.getVolatileType(Type);
12700 break;
12701 case 'R':
12702 Type = Type.withRestrict();
12703 break;
12704 }
12705 }
12706
12707 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12708 "Integer constant 'I' type must be an integer");
12709
12710 return Type;
12711}
12712
12713// On some targets such as PowerPC, some of the builtins are defined with custom
12714// type descriptors for target-dependent types. These descriptors are decoded in
12715// other functions, but it may be useful to be able to fall back to default
12716// descriptor decoding to define builtins mixing target-dependent and target-
12717// independent types. This function allows decoding one type descriptor with
12718// default decoding.
12719QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12720 GetBuiltinTypeError &Error, bool &RequireICE,
12721 bool AllowTypeModifiers) const {
12722 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12723}
12724
12725/// GetBuiltinType - Return the type for the specified builtin.
12728 unsigned *IntegerConstantArgs) const {
12729 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12730 if (TypeStr[0] == '\0') {
12732 return {};
12733 }
12734
12735 SmallVector<QualType, 8> ArgTypes;
12736
12737 bool RequiresICE = false;
12738 Error = GE_None;
12739 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12740 RequiresICE, true);
12741 if (Error != GE_None)
12742 return {};
12743
12744 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12745
12746 while (TypeStr[0] && TypeStr[0] != '.') {
12747 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12748 if (Error != GE_None)
12749 return {};
12750
12751 // If this argument is required to be an IntegerConstantExpression and the
12752 // caller cares, fill in the bitmask we return.
12753 if (RequiresICE && IntegerConstantArgs)
12754 *IntegerConstantArgs |= 1 << ArgTypes.size();
12755
12756 // Do array -> pointer decay. The builtin should use the decayed type.
12757 if (Ty->isArrayType())
12758 Ty = getArrayDecayedType(Ty);
12759
12760 ArgTypes.push_back(Ty);
12761 }
12762
12763 if (Id == Builtin::BI__GetExceptionInfo)
12764 return {};
12765
12766 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12767 "'.' should only occur at end of builtin type list!");
12768
12769 bool Variadic = (TypeStr[0] == '.');
12770
12771 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12772 if (BuiltinInfo.isNoReturn(Id))
12773 EI = EI.withNoReturn(true);
12774
12775 // We really shouldn't be making a no-proto type here.
12776 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12777 return getFunctionNoProtoType(ResType, EI);
12778
12780 EPI.ExtInfo = EI;
12781 EPI.Variadic = Variadic;
12782 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12783 EPI.ExceptionSpec.Type =
12785
12786 return getFunctionType(ResType, ArgTypes, EPI);
12787}
12788
12790 const FunctionDecl *FD) {
12791 if (!FD->isExternallyVisible())
12792 return GVA_Internal;
12793
12794 // Non-user-provided functions get emitted as weak definitions with every
12795 // use, no matter whether they've been explicitly instantiated etc.
12796 if (!FD->isUserProvided())
12797 return GVA_DiscardableODR;
12798
12800 switch (FD->getTemplateSpecializationKind()) {
12801 case TSK_Undeclared:
12804 break;
12805
12807 return GVA_StrongODR;
12808
12809 // C++11 [temp.explicit]p10:
12810 // [ Note: The intent is that an inline function that is the subject of
12811 // an explicit instantiation declaration will still be implicitly
12812 // instantiated when used so that the body can be considered for
12813 // inlining, but that no out-of-line copy of the inline function would be
12814 // generated in the translation unit. -- end note ]
12817
12820 break;
12821 }
12822
12823 if (!FD->isInlined())
12824 return External;
12825
12826 if ((!Context.getLangOpts().CPlusPlus &&
12827 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12828 !FD->hasAttr<DLLExportAttr>()) ||
12829 FD->hasAttr<GNUInlineAttr>()) {
12830 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12831
12832 // GNU or C99 inline semantics. Determine whether this symbol should be
12833 // externally visible.
12835 return External;
12836
12837 // C99 inline semantics, where the symbol is not externally visible.
12839 }
12840
12841 // Functions specified with extern and inline in -fms-compatibility mode
12842 // forcibly get emitted. While the body of the function cannot be later
12843 // replaced, the function definition cannot be discarded.
12844 if (FD->isMSExternInline())
12845 return GVA_StrongODR;
12846
12847 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12849 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12850 // Our approach to inheriting constructors is fundamentally different from
12851 // that used by the MS ABI, so keep our inheriting constructor thunks
12852 // internal rather than trying to pick an unambiguous mangling for them.
12853 return GVA_Internal;
12854
12855 return GVA_DiscardableODR;
12856}
12857
12859 const Decl *D, GVALinkage L) {
12860 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12861 // dllexport/dllimport on inline functions.
12862 if (D->hasAttr<DLLImportAttr>()) {
12863 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12865 } else if (D->hasAttr<DLLExportAttr>()) {
12866 if (L == GVA_DiscardableODR)
12867 return GVA_StrongODR;
12868 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12869 // Device-side functions with __global__ attribute must always be
12870 // visible externally so they can be launched from host.
12871 if (D->hasAttr<CUDAGlobalAttr>() &&
12872 (L == GVA_DiscardableODR || L == GVA_Internal))
12873 return GVA_StrongODR;
12874 // Single source offloading languages like CUDA/HIP need to be able to
12875 // access static device variables from host code of the same compilation
12876 // unit. This is done by externalizing the static variable with a shared
12877 // name between the host and device compilation which is the same for the
12878 // same compilation unit whereas different among different compilation
12879 // units.
12880 if (Context.shouldExternalize(D))
12881 return GVA_StrongExternal;
12882 }
12883 return L;
12884}
12885
12886/// Adjust the GVALinkage for a declaration based on what an external AST source
12887/// knows about whether there can be other definitions of this declaration.
12888static GVALinkage
12890 GVALinkage L) {
12891 ExternalASTSource *Source = Ctx.getExternalSource();
12892 if (!Source)
12893 return L;
12894
12895 switch (Source->hasExternalDefinitions(D)) {
12897 // Other translation units rely on us to provide the definition.
12898 if (L == GVA_DiscardableODR)
12899 return GVA_StrongODR;
12900 break;
12901
12904
12906 break;
12907 }
12908 return L;
12909}
12910
12916
12918 const VarDecl *VD) {
12919 // As an extension for interactive REPLs, make sure constant variables are
12920 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12921 // marking them as internal.
12922 if (Context.getLangOpts().CPlusPlus &&
12923 Context.getLangOpts().IncrementalExtensions &&
12924 VD->getType().isConstQualified() &&
12925 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12927 return GVA_DiscardableODR;
12928
12929 if (!VD->isExternallyVisible())
12930 return GVA_Internal;
12931
12932 if (VD->isStaticLocal()) {
12933 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12934 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12935 LexicalContext = LexicalContext->getLexicalParent();
12936
12937 // ObjC Blocks can create local variables that don't have a FunctionDecl
12938 // LexicalContext.
12939 if (!LexicalContext)
12940 return GVA_DiscardableODR;
12941
12942 // Otherwise, let the static local variable inherit its linkage from the
12943 // nearest enclosing function.
12944 auto StaticLocalLinkage =
12945 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12946
12947 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12948 // be emitted in any object with references to the symbol for the object it
12949 // contains, whether inline or out-of-line."
12950 // Similar behavior is observed with MSVC. An alternative ABI could use
12951 // StrongODR/AvailableExternally to match the function, but none are
12952 // known/supported currently.
12953 if (StaticLocalLinkage == GVA_StrongODR ||
12954 StaticLocalLinkage == GVA_AvailableExternally)
12955 return GVA_DiscardableODR;
12956 return StaticLocalLinkage;
12957 }
12958
12959 // MSVC treats in-class initialized static data members as definitions.
12960 // By giving them non-strong linkage, out-of-line definitions won't
12961 // cause link errors.
12962 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12963 return GVA_DiscardableODR;
12964
12965 // Most non-template variables have strong linkage; inline variables are
12966 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12967 GVALinkage StrongLinkage;
12968 switch (Context.getInlineVariableDefinitionKind(VD)) {
12970 StrongLinkage = GVA_StrongExternal;
12971 break;
12974 StrongLinkage = GVA_DiscardableODR;
12975 break;
12977 StrongLinkage = GVA_StrongODR;
12978 break;
12979 }
12980
12981 switch (VD->getTemplateSpecializationKind()) {
12982 case TSK_Undeclared:
12983 return StrongLinkage;
12984
12986 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12987 VD->isStaticDataMember()
12989 : StrongLinkage;
12990
12992 return GVA_StrongODR;
12993
12996
12998 return GVA_DiscardableODR;
12999 }
13000
13001 llvm_unreachable("Invalid Linkage!");
13002}
13003
13009
13011 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13012 if (!VD->isFileVarDecl())
13013 return false;
13014 // Global named register variables (GNU extension) are never emitted.
13015 if (VD->getStorageClass() == SC_Register)
13016 return false;
13017 if (VD->getDescribedVarTemplate() ||
13019 return false;
13020 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13021 // We never need to emit an uninstantiated function template.
13022 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13023 return false;
13024 } else if (isa<PragmaCommentDecl>(D))
13025 return true;
13027 return true;
13028 else if (isa<OMPRequiresDecl>(D))
13029 return true;
13030 else if (isa<OMPThreadPrivateDecl>(D))
13031 return !D->getDeclContext()->isDependentContext();
13032 else if (isa<OMPAllocateDecl>(D))
13033 return !D->getDeclContext()->isDependentContext();
13035 return !D->getDeclContext()->isDependentContext();
13036 else if (isa<ImportDecl>(D))
13037 return true;
13038 else
13039 return false;
13040
13041 // If this is a member of a class template, we do not need to emit it.
13043 return false;
13044
13045 // Weak references don't produce any output by themselves.
13046 if (D->hasAttr<WeakRefAttr>())
13047 return false;
13048
13049 // SYCL device compilation requires that functions defined with the
13050 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13051 // other entities are emitted only if they are used by a function
13052 // defined with one of those attributes.
13053 if (LangOpts.SYCLIsDevice)
13054 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13055 D->hasAttr<SYCLExternalAttr>());
13056
13057 // Aliases and used decls are required.
13058 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13059 return true;
13060
13061 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13062 // Forward declarations aren't required.
13063 if (!FD->doesThisDeclarationHaveABody())
13064 return FD->doesDeclarationForceExternallyVisibleDefinition();
13065
13066 // Constructors and destructors are required.
13067 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13068 return true;
13069
13070 // The key function for a class is required. This rule only comes
13071 // into play when inline functions can be key functions, though.
13072 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13073 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13074 const CXXRecordDecl *RD = MD->getParent();
13075 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13076 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13077 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13078 return true;
13079 }
13080 }
13081 }
13082
13084
13085 // static, static inline, always_inline, and extern inline functions can
13086 // always be deferred. Normal inline functions can be deferred in C99/C++.
13087 // Implicit template instantiations can also be deferred in C++.
13089 }
13090
13091 const auto *VD = cast<VarDecl>(D);
13092 assert(VD->isFileVarDecl() && "Expected file scoped var");
13093
13094 // If the decl is marked as `declare target to`, it should be emitted for the
13095 // host and for the device.
13096 if (LangOpts.OpenMP &&
13097 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13098 return true;
13099
13100 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13102 return false;
13103
13104 if (VD->shouldEmitInExternalSource())
13105 return false;
13106
13107 // Variables that can be needed in other TUs are required.
13110 return true;
13111
13112 // We never need to emit a variable that is available in another TU.
13114 return false;
13115
13116 // Variables that have destruction with side-effects are required.
13117 if (VD->needsDestruction(*this))
13118 return true;
13119
13120 // Variables that have initialization with side-effects are required.
13121 if (VD->hasInitWithSideEffects())
13122 return true;
13123
13124 // Likewise, variables with tuple-like bindings are required if their
13125 // bindings have side-effects.
13126 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13127 for (const auto *BD : DD->flat_bindings())
13128 if (const auto *BindingVD = BD->getHoldingVar())
13129 if (DeclMustBeEmitted(BindingVD))
13130 return true;
13131 }
13132
13133 return false;
13134}
13135
13137 const FunctionDecl *FD,
13138 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13139 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13140 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13141 FD = FD->getMostRecentDecl();
13142 // FIXME: The order of traversal here matters and depends on the order of
13143 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13144 // shouldn't rely on that.
13145 for (auto *CurDecl :
13147 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13148 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13149 SeenDecls.insert(CurFD).second) {
13150 Pred(CurFD);
13151 }
13152 }
13153}
13154
13156 bool IsCXXMethod) const {
13157 // Pass through to the C++ ABI object
13158 if (IsCXXMethod)
13159 return ABI->getDefaultMethodCallConv(IsVariadic);
13160
13161 switch (LangOpts.getDefaultCallingConv()) {
13163 break;
13165 return CC_C;
13167 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13168 return CC_X86FastCall;
13169 break;
13171 if (!IsVariadic)
13172 return CC_X86StdCall;
13173 break;
13175 // __vectorcall cannot be applied to variadic functions.
13176 if (!IsVariadic)
13177 return CC_X86VectorCall;
13178 break;
13180 // __regcall cannot be applied to variadic functions.
13181 if (!IsVariadic)
13182 return CC_X86RegCall;
13183 break;
13185 if (!IsVariadic)
13186 return CC_M68kRTD;
13187 break;
13188 }
13189 return Target->getDefaultCallingConv();
13190}
13191
13193 // Pass through to the C++ ABI object
13194 return ABI->isNearlyEmpty(RD);
13195}
13196
13198 if (!VTContext) {
13199 auto ABI = Target->getCXXABI();
13200 if (ABI.isMicrosoft())
13201 VTContext.reset(new MicrosoftVTableContext(*this));
13202 else {
13203 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13206 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13207 }
13208 }
13209 return VTContext.get();
13210}
13211
13213 if (!T)
13214 T = Target;
13215 switch (T->getCXXABI().getKind()) {
13216 case TargetCXXABI::AppleARM64:
13217 case TargetCXXABI::Fuchsia:
13218 case TargetCXXABI::GenericAArch64:
13219 case TargetCXXABI::GenericItanium:
13220 case TargetCXXABI::GenericARM:
13221 case TargetCXXABI::GenericMIPS:
13222 case TargetCXXABI::iOS:
13223 case TargetCXXABI::WebAssembly:
13224 case TargetCXXABI::WatchOS:
13225 case TargetCXXABI::XL:
13227 case TargetCXXABI::Microsoft:
13229 }
13230 llvm_unreachable("Unsupported ABI");
13231}
13232
13234 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13235 "Device mangle context does not support Microsoft mangling.");
13236 switch (T.getCXXABI().getKind()) {
13237 case TargetCXXABI::AppleARM64:
13238 case TargetCXXABI::Fuchsia:
13239 case TargetCXXABI::GenericAArch64:
13240 case TargetCXXABI::GenericItanium:
13241 case TargetCXXABI::GenericARM:
13242 case TargetCXXABI::GenericMIPS:
13243 case TargetCXXABI::iOS:
13244 case TargetCXXABI::WebAssembly:
13245 case TargetCXXABI::WatchOS:
13246 case TargetCXXABI::XL:
13248 *this, getDiagnostics(),
13249 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13250 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13251 return RD->getDeviceLambdaManglingNumber();
13252 return std::nullopt;
13253 },
13254 /*IsAux=*/true);
13255 case TargetCXXABI::Microsoft:
13257 /*IsAux=*/true);
13258 }
13259 llvm_unreachable("Unsupported ABI");
13260}
13261
13262CXXABI::~CXXABI() = default;
13263
13265 return ASTRecordLayouts.getMemorySize() +
13266 llvm::capacity_in_bytes(ObjCLayouts) +
13267 llvm::capacity_in_bytes(KeyFunctions) +
13268 llvm::capacity_in_bytes(ObjCImpls) +
13269 llvm::capacity_in_bytes(BlockVarCopyInits) +
13270 llvm::capacity_in_bytes(DeclAttrs) +
13271 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13272 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13273 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13274 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13275 llvm::capacity_in_bytes(OverriddenMethods) +
13276 llvm::capacity_in_bytes(Types) +
13277 llvm::capacity_in_bytes(VariableArrayTypes);
13278}
13279
13280/// getIntTypeForBitwidth -
13281/// sets integer QualTy according to specified details:
13282/// bitwidth, signed/unsigned.
13283/// Returns empty type if there is no appropriate target types.
13285 unsigned Signed) const {
13287 CanQualType QualTy = getFromTargetType(Ty);
13288 if (!QualTy && DestWidth == 128)
13289 return Signed ? Int128Ty : UnsignedInt128Ty;
13290 return QualTy;
13291}
13292
13293/// getRealTypeForBitwidth -
13294/// sets floating point QualTy according to specified bitwidth.
13295/// Returns empty type if there is no appropriate target types.
13297 FloatModeKind ExplicitType) const {
13298 FloatModeKind Ty =
13299 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13300 switch (Ty) {
13302 return HalfTy;
13304 return FloatTy;
13306 return DoubleTy;
13308 return LongDoubleTy;
13310 return Float128Ty;
13312 return Ibm128Ty;
13314 return {};
13315 }
13316
13317 llvm_unreachable("Unhandled TargetInfo::RealType value");
13318}
13319
13320void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13321 if (Number <= 1)
13322 return;
13323
13324 MangleNumbers[ND] = Number;
13325
13326 if (Listener)
13327 Listener->AddedManglingNumber(ND, Number);
13328}
13329
13331 bool ForAuxTarget) const {
13332 auto I = MangleNumbers.find(ND);
13333 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13334 // CUDA/HIP host compilation encodes host and device mangling numbers
13335 // as lower and upper half of 32 bit integer.
13336 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13337 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13338 } else {
13339 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13340 "number for aux target");
13341 }
13342 return Res > 1 ? Res : 1;
13343}
13344
13345void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13346 if (Number <= 1)
13347 return;
13348
13349 StaticLocalNumbers[VD] = Number;
13350
13351 if (Listener)
13352 Listener->AddedStaticLocalNumbers(VD, Number);
13353}
13354
13356 auto I = StaticLocalNumbers.find(VD);
13357 return I != StaticLocalNumbers.end() ? I->second : 1;
13358}
13359
13361 bool IsDestroying) {
13362 if (!IsDestroying) {
13363 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13364 return;
13365 }
13366 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13367}
13368
13370 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13371}
13372
13374 bool IsTypeAware) {
13375 if (!IsTypeAware) {
13376 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13377 return;
13378 }
13379 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13380}
13381
13383 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13384}
13385
13388 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13389 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13390 if (!MCtx)
13392 return *MCtx;
13393}
13394
13397 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13398 std::unique_ptr<MangleNumberingContext> &MCtx =
13399 ExtraMangleNumberingContexts[D];
13400 if (!MCtx)
13402 return *MCtx;
13403}
13404
13405std::unique_ptr<MangleNumberingContext>
13407 return ABI->createMangleNumberingContext();
13408}
13409
13410const CXXConstructorDecl *
13412 return ABI->getCopyConstructorForExceptionObject(
13414}
13415
13417 CXXConstructorDecl *CD) {
13418 return ABI->addCopyConstructorForExceptionObject(
13421}
13422
13424 TypedefNameDecl *DD) {
13425 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13426}
13427
13430 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13431}
13432
13434 DeclaratorDecl *DD) {
13435 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13436}
13437
13439 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13440}
13441
13443 ParamIndices[D] = index;
13444}
13445
13447 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13448 assert(I != ParamIndices.end() &&
13449 "ParmIndices lacks entry set by ParmVarDecl");
13450 return I->second;
13451}
13452
13454 unsigned Length) const {
13455 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13456 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13457 EltTy = EltTy.withConst();
13458
13459 EltTy = adjustStringLiteralBaseType(EltTy);
13460
13461 // Get an array type for the string, according to C99 6.4.5. This includes
13462 // the null terminator character.
13463 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13464 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13465}
13466
13469 StringLiteral *&Result = StringLiteralCache[Key];
13470 if (!Result)
13472 *this, Key, StringLiteralKind::Ordinary,
13473 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13474 SourceLocation());
13475 return Result;
13476}
13477
13478MSGuidDecl *
13480 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13481
13482 llvm::FoldingSetNodeID ID;
13483 MSGuidDecl::Profile(ID, Parts);
13484
13485 void *InsertPos;
13486 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13487 return Existing;
13488
13489 QualType GUIDType = getMSGuidType().withConst();
13490 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13491 MSGuidDecls.InsertNode(New, InsertPos);
13492 return New;
13493}
13494
13497 const APValue &APVal) const {
13498 llvm::FoldingSetNodeID ID;
13500
13501 void *InsertPos;
13502 if (UnnamedGlobalConstantDecl *Existing =
13503 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13504 return Existing;
13505
13507 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13508 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13509 return New;
13510}
13511
13514 assert(T->isRecordType() && "template param object of unexpected type");
13515
13516 // C++ [temp.param]p8:
13517 // [...] a static storage duration object of type 'const T' [...]
13518 T.addConst();
13519
13520 llvm::FoldingSetNodeID ID;
13522
13523 void *InsertPos;
13524 if (TemplateParamObjectDecl *Existing =
13525 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13526 return Existing;
13527
13528 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13529 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13530 return New;
13531}
13532
13534 const llvm::Triple &T = getTargetInfo().getTriple();
13535 if (!T.isOSDarwin())
13536 return false;
13537
13538 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13539 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13540 return false;
13541
13542 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13543 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13544 uint64_t Size = sizeChars.getQuantity();
13545 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13546 unsigned Align = alignChars.getQuantity();
13547 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13548 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13549}
13550
13551bool
13553 const ObjCMethodDecl *MethodImpl) {
13554 // No point trying to match an unavailable/deprecated mothod.
13555 if (MethodDecl->hasAttr<UnavailableAttr>()
13556 || MethodDecl->hasAttr<DeprecatedAttr>())
13557 return false;
13558 if (MethodDecl->getObjCDeclQualifier() !=
13559 MethodImpl->getObjCDeclQualifier())
13560 return false;
13561 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13562 return false;
13563
13564 if (MethodDecl->param_size() != MethodImpl->param_size())
13565 return false;
13566
13567 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13568 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13569 EF = MethodDecl->param_end();
13570 IM != EM && IF != EF; ++IM, ++IF) {
13571 const ParmVarDecl *DeclVar = (*IF);
13572 const ParmVarDecl *ImplVar = (*IM);
13573 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13574 return false;
13575 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13576 return false;
13577 }
13578
13579 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13580}
13581
13583 LangAS AS;
13585 AS = LangAS::Default;
13586 else
13587 AS = QT->getPointeeType().getAddressSpace();
13588
13590}
13591
13594}
13595
13596bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13597 if (X == Y)
13598 return true;
13599 if (!X || !Y)
13600 return false;
13601 llvm::FoldingSetNodeID IDX, IDY;
13602 X->Profile(IDX, *this, /*Canonical=*/true);
13603 Y->Profile(IDY, *this, /*Canonical=*/true);
13604 return IDX == IDY;
13605}
13606
13607// The getCommon* helpers return, for given 'same' X and Y entities given as
13608// inputs, another entity which is also the 'same' as the inputs, but which
13609// is closer to the canonical form of the inputs, each according to a given
13610// criteria.
13611// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13612// the regular ones.
13613
13615 if (!declaresSameEntity(X, Y))
13616 return nullptr;
13617 for (const Decl *DX : X->redecls()) {
13618 // If we reach Y before reaching the first decl, that means X is older.
13619 if (DX == Y)
13620 return X;
13621 // If we reach the first decl, then Y is older.
13622 if (DX->isFirstDecl())
13623 return Y;
13624 }
13625 llvm_unreachable("Corrupt redecls chain");
13626}
13627
13628template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13629static T *getCommonDecl(T *X, T *Y) {
13630 return cast_or_null<T>(
13631 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13632 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13633}
13634
13635template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13636static T *getCommonDeclChecked(T *X, T *Y) {
13637 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13638 const_cast<Decl *>(cast<Decl>(Y))));
13639}
13640
13642 TemplateName Y,
13643 bool IgnoreDeduced = false) {
13644 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13645 return X;
13646 // FIXME: There are cases here where we could find a common template name
13647 // with more sugar. For example one could be a SubstTemplateTemplate*
13648 // replacing the other.
13649 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13650 if (CX.getAsVoidPointer() !=
13652 return TemplateName();
13653 return CX;
13654}
13655
13658 bool IgnoreDeduced) {
13659 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13660 assert(R.getAsVoidPointer() != nullptr);
13661 return R;
13662}
13663
13665 ArrayRef<QualType> Ys, bool Unqualified = false) {
13666 assert(Xs.size() == Ys.size());
13667 SmallVector<QualType, 8> Rs(Xs.size());
13668 for (size_t I = 0; I < Rs.size(); ++I)
13669 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13670 return Rs;
13671}
13672
13673template <class T>
13674static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13675 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13676 : SourceLocation();
13677}
13678
13680 const TemplateArgument &X,
13681 const TemplateArgument &Y) {
13682 if (X.getKind() != Y.getKind())
13683 return TemplateArgument();
13684
13685 switch (X.getKind()) {
13687 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13688 return TemplateArgument();
13689 return TemplateArgument(
13690 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13692 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13693 return TemplateArgument();
13694 return TemplateArgument(
13695 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13696 /*Unqualified=*/true);
13698 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13699 return TemplateArgument();
13700 // FIXME: Try to keep the common sugar.
13701 return X;
13703 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13704 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13705 if (!CTN.getAsVoidPointer())
13706 return TemplateArgument();
13707 return TemplateArgument(CTN);
13708 }
13710 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13712 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13713 if (!CTN.getAsVoidPointer())
13714 return TemplateName();
13715 auto NExpX = X.getNumTemplateExpansions();
13716 assert(NExpX == Y.getNumTemplateExpansions());
13717 return TemplateArgument(CTN, NExpX);
13718 }
13719 default:
13720 // FIXME: Handle the other argument kinds.
13721 return X;
13722 }
13723}
13724
13729 if (Xs.size() != Ys.size())
13730 return true;
13731 R.resize(Xs.size());
13732 for (size_t I = 0; I < R.size(); ++I) {
13733 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13734 if (R[I].isNull())
13735 return true;
13736 }
13737 return false;
13738}
13739
13744 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13745 assert(!Different);
13746 (void)Different;
13747 return R;
13748}
13749
13750template <class T>
13752 bool IsSame) {
13753 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13754 if (KX == KY)
13755 return KX;
13757 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13758 return KX;
13759}
13760
13761/// Returns a NestedNameSpecifier which has only the common sugar
13762/// present in both NNS1 and NNS2.
13765 NestedNameSpecifier NNS2, bool IsSame) {
13766 // If they are identical, all sugar is common.
13767 if (NNS1 == NNS2)
13768 return NNS1;
13769
13770 // IsSame implies both Qualifiers are equivalent.
13771 NestedNameSpecifier Canon = NNS1.getCanonical();
13772 if (Canon != NNS2.getCanonical()) {
13773 assert(!IsSame && "Should be the same NestedNameSpecifier");
13774 // If they are not the same, there is nothing to unify.
13775 return std::nullopt;
13776 }
13777
13778 NestedNameSpecifier R = std::nullopt;
13779 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13780 assert(Kind == NNS2.getKind());
13781 switch (Kind) {
13783 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13784 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13785 auto Kind = Namespace1->getKind();
13786 if (Kind != Namespace2->getKind() ||
13787 (Kind == Decl::NamespaceAlias &&
13788 !declaresSameEntity(Namespace1, Namespace2))) {
13790 Ctx,
13791 ::getCommonDeclChecked(Namespace1->getNamespace(),
13792 Namespace2->getNamespace()),
13793 /*Prefix=*/std::nullopt);
13794 break;
13795 }
13796 // The prefixes for namespaces are not significant, its declaration
13797 // identifies it uniquely.
13798 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13799 /*IsSame=*/false);
13800 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13801 Prefix);
13802 break;
13803 }
13805 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13806 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13807 /*Unqualified=*/true)
13808 .getTypePtr();
13810 break;
13811 }
13813 // FIXME: Can __super even be used with data members?
13814 // If it's only usable in functions, we will never see it here,
13815 // unless we save the qualifiers used in function types.
13816 // In that case, it might be possible NNS2 is a type,
13817 // in which case we should degrade the result to
13818 // a CXXRecordType.
13820 NNS2.getAsMicrosoftSuper()));
13821 break;
13822 }
13825 // These are singletons.
13826 llvm_unreachable("singletons did not compare equal");
13827 }
13828 assert(R.getCanonical() == Canon);
13829 return R;
13830}
13831
13832template <class T>
13834 const T *Y, bool IsSame) {
13835 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13836}
13837
13838template <class T>
13839static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13840 const T *Y) {
13841 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13842}
13843
13844template <class T>
13846 Qualifiers &QX, const T *Y,
13847 Qualifiers &QY) {
13848 QualType EX = X->getElementType(), EY = Y->getElementType();
13849 QualType R = Ctx.getCommonSugaredType(EX, EY,
13850 /*Unqualified=*/true);
13851 // Qualifiers common to both element types.
13852 Qualifiers RQ = R.getQualifiers();
13853 // For each side, move to the top level any qualifiers which are not common to
13854 // both element types. The caller must assume top level qualifiers might
13855 // be different, even if they are the same type, and can be treated as sugar.
13856 QX += EX.getQualifiers() - RQ;
13857 QY += EY.getQualifiers() - RQ;
13858 return R;
13859}
13860
13861template <class T>
13862static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13863 const T *Y) {
13864 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13865}
13866
13867template <class T>
13868static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13869 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13870 return X->getSizeExpr();
13871}
13872
13873static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13874 assert(X->getSizeModifier() == Y->getSizeModifier());
13875 return X->getSizeModifier();
13876}
13877
13879 const ArrayType *Y) {
13880 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13881 return X->getIndexTypeCVRQualifiers();
13882}
13883
13884// Merges two type lists such that the resulting vector will contain
13885// each type (in a canonical sense) only once, in the order they appear
13886// from X to Y. If they occur in both X and Y, the result will contain
13887// the common sugared type between them.
13888static void mergeTypeLists(const ASTContext &Ctx,
13891 llvm::DenseMap<QualType, unsigned> Found;
13892 for (auto Ts : {X, Y}) {
13893 for (QualType T : Ts) {
13894 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13895 if (!Res.second) {
13896 QualType &U = Out[Res.first->second];
13897 U = Ctx.getCommonSugaredType(U, T);
13898 } else {
13899 Out.emplace_back(T);
13900 }
13901 }
13902 }
13903}
13904
13905FunctionProtoType::ExceptionSpecInfo
13908 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13909 bool AcceptDependent) const {
13910 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13911
13912 // If either of them can throw anything, that is the result.
13913 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13914 if (EST1 == I)
13915 return ESI1;
13916 if (EST2 == I)
13917 return ESI2;
13918 }
13919
13920 // If either of them is non-throwing, the result is the other.
13921 for (auto I :
13923 if (EST1 == I)
13924 return ESI2;
13925 if (EST2 == I)
13926 return ESI1;
13927 }
13928
13929 // If we're left with value-dependent computed noexcept expressions, we're
13930 // stuck. Before C++17, we can just drop the exception specification entirely,
13931 // since it's not actually part of the canonical type. And this should never
13932 // happen in C++17, because it would mean we were computing the composite
13933 // pointer type of dependent types, which should never happen.
13934 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13935 assert(AcceptDependent &&
13936 "computing composite pointer type of dependent types");
13938 }
13939
13940 // Switch over the possibilities so that people adding new values know to
13941 // update this function.
13942 switch (EST1) {
13943 case EST_None:
13944 case EST_DynamicNone:
13945 case EST_MSAny:
13946 case EST_BasicNoexcept:
13948 case EST_NoexceptFalse:
13949 case EST_NoexceptTrue:
13950 case EST_NoThrow:
13951 llvm_unreachable("These ESTs should be handled above");
13952
13953 case EST_Dynamic: {
13954 // This is the fun case: both exception specifications are dynamic. Form
13955 // the union of the two lists.
13956 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13957 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13958 ESI2.Exceptions);
13960 Result.Exceptions = ExceptionTypeStorage;
13961 return Result;
13962 }
13963
13964 case EST_Unevaluated:
13965 case EST_Uninstantiated:
13966 case EST_Unparsed:
13967 llvm_unreachable("shouldn't see unresolved exception specifications here");
13968 }
13969
13970 llvm_unreachable("invalid ExceptionSpecificationType");
13971}
13972
13974 Qualifiers &QX, const Type *Y,
13975 Qualifiers &QY) {
13976 Type::TypeClass TC = X->getTypeClass();
13977 assert(TC == Y->getTypeClass());
13978 switch (TC) {
13979#define UNEXPECTED_TYPE(Class, Kind) \
13980 case Type::Class: \
13981 llvm_unreachable("Unexpected " Kind ": " #Class);
13982
13983#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13984#define TYPE(Class, Base)
13985#include "clang/AST/TypeNodes.inc"
13986
13987#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13989 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13990 SUGAR_FREE_TYPE(DependentBitInt)
13992 SUGAR_FREE_TYPE(ObjCInterface)
13993 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13994 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
13995 SUGAR_FREE_TYPE(UnresolvedUsing)
13996 SUGAR_FREE_TYPE(HLSLAttributedResource)
13997 SUGAR_FREE_TYPE(HLSLInlineSpirv)
13998#undef SUGAR_FREE_TYPE
13999#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14000 NON_UNIQUE_TYPE(TypeOfExpr)
14001 NON_UNIQUE_TYPE(VariableArray)
14002#undef NON_UNIQUE_TYPE
14003
14004 UNEXPECTED_TYPE(TypeOf, "sugar")
14005
14006#undef UNEXPECTED_TYPE
14007
14008 case Type::Auto: {
14009 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14010 assert(AX->getDeducedType().isNull());
14011 assert(AY->getDeducedType().isNull());
14012 assert(AX->getKeyword() == AY->getKeyword());
14013 assert(AX->isInstantiationDependentType() ==
14014 AY->isInstantiationDependentType());
14015 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14016 AY->getTypeConstraintArguments());
14017 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14019 AX->containsUnexpandedParameterPack(),
14020 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14021 AY->getTypeConstraintConcept()),
14022 As);
14023 }
14024 case Type::IncompleteArray: {
14025 const auto *AX = cast<IncompleteArrayType>(X),
14027 return Ctx.getIncompleteArrayType(
14028 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14030 }
14031 case Type::DependentSizedArray: {
14032 const auto *AX = cast<DependentSizedArrayType>(X),
14034 return Ctx.getDependentSizedArrayType(
14035 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14036 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14038 }
14039 case Type::ConstantArray: {
14040 const auto *AX = cast<ConstantArrayType>(X),
14041 *AY = cast<ConstantArrayType>(Y);
14042 assert(AX->getSize() == AY->getSize());
14043 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14044 ? AX->getSizeExpr()
14045 : nullptr;
14046 return Ctx.getConstantArrayType(
14047 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14049 }
14050 case Type::ArrayParameter: {
14051 const auto *AX = cast<ArrayParameterType>(X),
14052 *AY = cast<ArrayParameterType>(Y);
14053 assert(AX->getSize() == AY->getSize());
14054 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14055 ? AX->getSizeExpr()
14056 : nullptr;
14057 auto ArrayTy = Ctx.getConstantArrayType(
14058 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14060 return Ctx.getArrayParameterType(ArrayTy);
14061 }
14062 case Type::Atomic: {
14063 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14064 return Ctx.getAtomicType(
14065 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14066 }
14067 case Type::Complex: {
14068 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14069 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14070 }
14071 case Type::Pointer: {
14072 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14073 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14074 }
14075 case Type::BlockPointer: {
14076 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14077 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14078 }
14079 case Type::ObjCObjectPointer: {
14080 const auto *PX = cast<ObjCObjectPointerType>(X),
14082 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14083 }
14084 case Type::MemberPointer: {
14085 const auto *PX = cast<MemberPointerType>(X),
14086 *PY = cast<MemberPointerType>(Y);
14087 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14088 PY->getMostRecentCXXRecordDecl()));
14089 return Ctx.getMemberPointerType(
14090 getCommonPointeeType(Ctx, PX, PY),
14091 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14092 PX->getMostRecentCXXRecordDecl());
14093 }
14094 case Type::LValueReference: {
14095 const auto *PX = cast<LValueReferenceType>(X),
14097 // FIXME: Preserve PointeeTypeAsWritten.
14098 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14099 PX->isSpelledAsLValue() ||
14100 PY->isSpelledAsLValue());
14101 }
14102 case Type::RValueReference: {
14103 const auto *PX = cast<RValueReferenceType>(X),
14105 // FIXME: Preserve PointeeTypeAsWritten.
14106 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14107 }
14108 case Type::DependentAddressSpace: {
14109 const auto *PX = cast<DependentAddressSpaceType>(X),
14111 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14112 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14113 PX->getAddrSpaceExpr(),
14114 getCommonAttrLoc(PX, PY));
14115 }
14116 case Type::FunctionNoProto: {
14117 const auto *FX = cast<FunctionNoProtoType>(X),
14119 assert(FX->getExtInfo() == FY->getExtInfo());
14120 return Ctx.getFunctionNoProtoType(
14121 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14122 FX->getExtInfo());
14123 }
14124 case Type::FunctionProto: {
14125 const auto *FX = cast<FunctionProtoType>(X),
14126 *FY = cast<FunctionProtoType>(Y);
14127 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14128 EPIY = FY->getExtProtoInfo();
14129 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14130 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14131 assert(!EPIX.ExtParameterInfos ||
14132 llvm::equal(
14133 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14134 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14135 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14136 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14137 assert(EPIX.Variadic == EPIY.Variadic);
14138
14139 // FIXME: Can we handle an empty EllipsisLoc?
14140 // Use emtpy EllipsisLoc if X and Y differ.
14141
14142 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14143
14144 QualType R =
14145 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14146 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14147 /*Unqualified=*/true);
14148
14149 SmallVector<QualType, 8> Exceptions;
14151 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14152 return Ctx.getFunctionType(R, P, EPIX);
14153 }
14154 case Type::ObjCObject: {
14155 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14156 assert(
14157 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14158 OY->getProtocols().begin(), OY->getProtocols().end(),
14159 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14160 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14161 }) &&
14162 "protocol lists must be the same");
14163 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14164 OY->getTypeArgsAsWritten());
14165 return Ctx.getObjCObjectType(
14166 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14167 OX->getProtocols(),
14168 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14169 }
14170 case Type::ConstantMatrix: {
14171 const auto *MX = cast<ConstantMatrixType>(X),
14172 *MY = cast<ConstantMatrixType>(Y);
14173 assert(MX->getNumRows() == MY->getNumRows());
14174 assert(MX->getNumColumns() == MY->getNumColumns());
14175 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14176 MX->getNumRows(), MX->getNumColumns());
14177 }
14178 case Type::DependentSizedMatrix: {
14179 const auto *MX = cast<DependentSizedMatrixType>(X),
14181 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14182 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14183 return Ctx.getDependentSizedMatrixType(
14184 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14185 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14186 }
14187 case Type::Vector: {
14188 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14189 assert(VX->getNumElements() == VY->getNumElements());
14190 assert(VX->getVectorKind() == VY->getVectorKind());
14191 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14192 VX->getNumElements(), VX->getVectorKind());
14193 }
14194 case Type::ExtVector: {
14195 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14196 assert(VX->getNumElements() == VY->getNumElements());
14197 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14198 VX->getNumElements());
14199 }
14200 case Type::DependentSizedExtVector: {
14201 const auto *VX = cast<DependentSizedExtVectorType>(X),
14204 getCommonSizeExpr(Ctx, VX, VY),
14205 getCommonAttrLoc(VX, VY));
14206 }
14207 case Type::DependentVector: {
14208 const auto *VX = cast<DependentVectorType>(X),
14210 assert(VX->getVectorKind() == VY->getVectorKind());
14211 return Ctx.getDependentVectorType(
14212 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14213 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14214 }
14215 case Type::Enum:
14216 case Type::Record:
14217 case Type::InjectedClassName: {
14218 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14219 return Ctx.getTagType(
14220 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14221 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14222 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14223 /*OwnedTag=*/false);
14224 }
14225 case Type::TemplateSpecialization: {
14226 const auto *TX = cast<TemplateSpecializationType>(X),
14228 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14229 TY->template_arguments());
14231 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14232 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14233 TY->getTemplateName(),
14234 /*IgnoreDeduced=*/true),
14235 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14236 }
14237 case Type::Decltype: {
14238 const auto *DX = cast<DecltypeType>(X);
14239 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14240 assert(DX->isDependentType());
14241 assert(DY->isDependentType());
14242 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14243 // As Decltype is not uniqued, building a common type would be wasteful.
14244 return QualType(DX, 0);
14245 }
14246 case Type::PackIndexing: {
14247 const auto *DX = cast<PackIndexingType>(X);
14248 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14249 assert(DX->isDependentType());
14250 assert(DY->isDependentType());
14251 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14252 return QualType(DX, 0);
14253 }
14254 case Type::DependentName: {
14255 const auto *NX = cast<DependentNameType>(X),
14256 *NY = cast<DependentNameType>(Y);
14257 assert(NX->getIdentifier() == NY->getIdentifier());
14258 return Ctx.getDependentNameType(
14259 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14260 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14261 }
14262 case Type::UnaryTransform: {
14263 const auto *TX = cast<UnaryTransformType>(X),
14264 *TY = cast<UnaryTransformType>(Y);
14265 assert(TX->getUTTKind() == TY->getUTTKind());
14266 return Ctx.getUnaryTransformType(
14267 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14268 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14269 TY->getUnderlyingType()),
14270 TX->getUTTKind());
14271 }
14272 case Type::PackExpansion: {
14273 const auto *PX = cast<PackExpansionType>(X),
14274 *PY = cast<PackExpansionType>(Y);
14275 assert(PX->getNumExpansions() == PY->getNumExpansions());
14276 return Ctx.getPackExpansionType(
14277 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14278 PX->getNumExpansions(), false);
14279 }
14280 case Type::Pipe: {
14281 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14282 assert(PX->isReadOnly() == PY->isReadOnly());
14283 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14285 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14286 }
14287 case Type::TemplateTypeParm: {
14288 const auto *TX = cast<TemplateTypeParmType>(X),
14290 assert(TX->getDepth() == TY->getDepth());
14291 assert(TX->getIndex() == TY->getIndex());
14292 assert(TX->isParameterPack() == TY->isParameterPack());
14293 return Ctx.getTemplateTypeParmType(
14294 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14295 getCommonDecl(TX->getDecl(), TY->getDecl()));
14296 }
14297 }
14298 llvm_unreachable("Unknown Type Class");
14299}
14300
14302 const Type *Y,
14303 SplitQualType Underlying) {
14304 Type::TypeClass TC = X->getTypeClass();
14305 if (TC != Y->getTypeClass())
14306 return QualType();
14307 switch (TC) {
14308#define UNEXPECTED_TYPE(Class, Kind) \
14309 case Type::Class: \
14310 llvm_unreachable("Unexpected " Kind ": " #Class);
14311#define TYPE(Class, Base)
14312#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14313#include "clang/AST/TypeNodes.inc"
14314
14315#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14318 CANONICAL_TYPE(BlockPointer)
14321 CANONICAL_TYPE(ConstantArray)
14322 CANONICAL_TYPE(ArrayParameter)
14323 CANONICAL_TYPE(ConstantMatrix)
14325 CANONICAL_TYPE(ExtVector)
14326 CANONICAL_TYPE(FunctionNoProto)
14327 CANONICAL_TYPE(FunctionProto)
14328 CANONICAL_TYPE(IncompleteArray)
14329 CANONICAL_TYPE(HLSLAttributedResource)
14330 CANONICAL_TYPE(HLSLInlineSpirv)
14331 CANONICAL_TYPE(LValueReference)
14332 CANONICAL_TYPE(ObjCInterface)
14333 CANONICAL_TYPE(ObjCObject)
14334 CANONICAL_TYPE(ObjCObjectPointer)
14338 CANONICAL_TYPE(RValueReference)
14339 CANONICAL_TYPE(VariableArray)
14341#undef CANONICAL_TYPE
14342
14343#undef UNEXPECTED_TYPE
14344
14345 case Type::Adjusted: {
14346 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14347 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14348 if (!Ctx.hasSameType(OX, OY))
14349 return QualType();
14350 // FIXME: It's inefficient to have to unify the original types.
14351 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14352 Ctx.getQualifiedType(Underlying));
14353 }
14354 case Type::Decayed: {
14355 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14356 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14357 if (!Ctx.hasSameType(OX, OY))
14358 return QualType();
14359 // FIXME: It's inefficient to have to unify the original types.
14360 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14361 Ctx.getQualifiedType(Underlying));
14362 }
14363 case Type::Attributed: {
14364 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14365 AttributedType::Kind Kind = AX->getAttrKind();
14366 if (Kind != AY->getAttrKind())
14367 return QualType();
14368 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14369 if (!Ctx.hasSameType(MX, MY))
14370 return QualType();
14371 // FIXME: It's inefficient to have to unify the modified types.
14372 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14373 Ctx.getQualifiedType(Underlying),
14374 AX->getAttr());
14375 }
14376 case Type::BTFTagAttributed: {
14377 const auto *BX = cast<BTFTagAttributedType>(X);
14378 const BTFTypeTagAttr *AX = BX->getAttr();
14379 // The attribute is not uniqued, so just compare the tag.
14380 if (AX->getBTFTypeTag() !=
14381 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14382 return QualType();
14383 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14384 }
14385 case Type::Auto: {
14386 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14387
14388 AutoTypeKeyword KW = AX->getKeyword();
14389 if (KW != AY->getKeyword())
14390 return QualType();
14391
14392 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14393 AY->getTypeConstraintConcept());
14395 if (CD &&
14396 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14397 AY->getTypeConstraintArguments())) {
14398 CD = nullptr; // The arguments differ, so make it unconstrained.
14399 As.clear();
14400 }
14401
14402 // Both auto types can't be dependent, otherwise they wouldn't have been
14403 // sugar. This implies they can't contain unexpanded packs either.
14404 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14405 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14406 }
14407 case Type::PackIndexing:
14408 case Type::Decltype:
14409 return QualType();
14410 case Type::DeducedTemplateSpecialization:
14411 // FIXME: Try to merge these.
14412 return QualType();
14413 case Type::MacroQualified: {
14414 const auto *MX = cast<MacroQualifiedType>(X),
14415 *MY = cast<MacroQualifiedType>(Y);
14416 const IdentifierInfo *IX = MX->getMacroIdentifier();
14417 if (IX != MY->getMacroIdentifier())
14418 return QualType();
14419 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14420 }
14421 case Type::SubstTemplateTypeParm: {
14422 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14424 Decl *CD =
14425 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14426 if (!CD)
14427 return QualType();
14428 unsigned Index = SX->getIndex();
14429 if (Index != SY->getIndex())
14430 return QualType();
14431 auto PackIndex = SX->getPackIndex();
14432 if (PackIndex != SY->getPackIndex())
14433 return QualType();
14434 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14435 CD, Index, PackIndex,
14436 SX->getFinal() && SY->getFinal());
14437 }
14438 case Type::ObjCTypeParam:
14439 // FIXME: Try to merge these.
14440 return QualType();
14441 case Type::Paren:
14442 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14443
14444 case Type::TemplateSpecialization: {
14445 const auto *TX = cast<TemplateSpecializationType>(X),
14447 TemplateName CTN =
14448 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14449 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14450 if (!CTN.getAsVoidPointer())
14451 return QualType();
14453 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14454 TY->template_arguments()))
14455 return QualType();
14457 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14458 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14459 }
14460 case Type::Typedef: {
14461 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14462 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14463 if (!CD)
14464 return QualType();
14465 return Ctx.getTypedefType(
14466 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14467 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14468 Ctx.getQualifiedType(Underlying));
14469 }
14470 case Type::TypeOf: {
14471 // The common sugar between two typeof expressions, where one is
14472 // potentially a typeof_unqual and the other is not, we unify to the
14473 // qualified type as that retains the most information along with the type.
14474 // We only return a typeof_unqual type when both types are unqual types.
14479 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14480 }
14481 case Type::TypeOfExpr:
14482 return QualType();
14483
14484 case Type::UnaryTransform: {
14485 const auto *UX = cast<UnaryTransformType>(X),
14486 *UY = cast<UnaryTransformType>(Y);
14487 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14488 if (KX != UY->getUTTKind())
14489 return QualType();
14490 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14491 if (!Ctx.hasSameType(BX, BY))
14492 return QualType();
14493 // FIXME: It's inefficient to have to unify the base types.
14494 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14495 Ctx.getQualifiedType(Underlying), KX);
14496 }
14497 case Type::Using: {
14498 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14499 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14500 if (!CD)
14501 return QualType();
14502 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14503 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14504 CD, Ctx.getQualifiedType(Underlying));
14505 }
14506 case Type::MemberPointer: {
14507 const auto *PX = cast<MemberPointerType>(X),
14508 *PY = cast<MemberPointerType>(Y);
14509 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14510 assert(Cls == PY->getMostRecentCXXRecordDecl());
14511 return Ctx.getMemberPointerType(
14512 ::getCommonPointeeType(Ctx, PX, PY),
14513 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14514 }
14515 case Type::CountAttributed: {
14516 const auto *DX = cast<CountAttributedType>(X),
14518 if (DX->isCountInBytes() != DY->isCountInBytes())
14519 return QualType();
14520 if (DX->isOrNull() != DY->isOrNull())
14521 return QualType();
14522 Expr *CEX = DX->getCountExpr();
14523 Expr *CEY = DY->getCountExpr();
14524 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14525 if (Ctx.hasSameExpr(CEX, CEY))
14526 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14527 DX->isCountInBytes(), DX->isOrNull(),
14528 CDX);
14529 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14530 return QualType();
14531 // Two declarations with the same integer constant may still differ in their
14532 // expression pointers, so we need to evaluate them.
14533 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14534 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14535 if (VX != VY)
14536 return QualType();
14537 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14538 DX->isCountInBytes(), DX->isOrNull(),
14539 CDX);
14540 }
14541 case Type::PredefinedSugar:
14542 assert(cast<PredefinedSugarType>(X)->getKind() !=
14544 return QualType();
14545 }
14546 llvm_unreachable("Unhandled Type Class");
14547}
14548
14549static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14551 while (true) {
14552 QTotal.addConsistentQualifiers(T.Quals);
14553 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14554 if (NT == QualType(T.Ty, 0))
14555 break;
14556 R.push_back(T);
14557 T = NT.split();
14558 }
14559 return R;
14560}
14561
14563 bool Unqualified) const {
14564 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14565 if (X == Y)
14566 return X;
14567 if (!Unqualified) {
14568 if (X.isCanonical())
14569 return X;
14570 if (Y.isCanonical())
14571 return Y;
14572 }
14573
14574 SplitQualType SX = X.split(), SY = Y.split();
14575 Qualifiers QX, QY;
14576 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14577 // until we reach their underlying "canonical nodes". Note these are not
14578 // necessarily canonical types, as they may still have sugared properties.
14579 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14580 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14581
14582 // If this is an ArrayType, the element qualifiers are interchangeable with
14583 // the top level qualifiers.
14584 // * In case the canonical nodes are the same, the elements types are already
14585 // the same.
14586 // * Otherwise, the element types will be made the same, and any different
14587 // element qualifiers will be moved up to the top level qualifiers, per
14588 // 'getCommonArrayElementType'.
14589 // In both cases, this means there may be top level qualifiers which differ
14590 // between X and Y. If so, these differing qualifiers are redundant with the
14591 // element qualifiers, and can be removed without changing the canonical type.
14592 // The desired behaviour is the same as for the 'Unqualified' case here:
14593 // treat the redundant qualifiers as sugar, remove the ones which are not
14594 // common to both sides.
14595 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14596
14597 if (SX.Ty != SY.Ty) {
14598 // The canonical nodes differ. Build a common canonical node out of the two,
14599 // unifying their sugar. This may recurse back here.
14600 SX.Ty =
14601 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14602 } else {
14603 // The canonical nodes were identical: We may have desugared too much.
14604 // Add any common sugar back in.
14605 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14606 QX -= SX.Quals;
14607 QY -= SY.Quals;
14608 SX = Xs.pop_back_val();
14609 SY = Ys.pop_back_val();
14610 }
14611 }
14612 if (KeepCommonQualifiers)
14614 else
14615 assert(QX == QY);
14616
14617 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14618 // related. Walk up these nodes, unifying them and adding the result.
14619 while (!Xs.empty() && !Ys.empty()) {
14620 auto Underlying = SplitQualType(
14621 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14622 SX = Xs.pop_back_val();
14623 SY = Ys.pop_back_val();
14624 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14626 // Stop at the first pair which is unrelated.
14627 if (!SX.Ty) {
14628 SX.Ty = Underlying.Ty;
14629 break;
14630 }
14631 QX -= Underlying.Quals;
14632 };
14633
14634 // Add back the missing accumulated qualifiers, which were stripped off
14635 // with the sugar nodes we could not unify.
14636 QualType R = getQualifiedType(SX.Ty, QX);
14637 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14638 return R;
14639}
14640
14642 assert(Ty->isFixedPointType());
14643
14645 return Ty;
14646
14647 switch (Ty->castAs<BuiltinType>()->getKind()) {
14648 default:
14649 llvm_unreachable("Not a saturated fixed point type!");
14650 case BuiltinType::SatShortAccum:
14651 return ShortAccumTy;
14652 case BuiltinType::SatAccum:
14653 return AccumTy;
14654 case BuiltinType::SatLongAccum:
14655 return LongAccumTy;
14656 case BuiltinType::SatUShortAccum:
14657 return UnsignedShortAccumTy;
14658 case BuiltinType::SatUAccum:
14659 return UnsignedAccumTy;
14660 case BuiltinType::SatULongAccum:
14661 return UnsignedLongAccumTy;
14662 case BuiltinType::SatShortFract:
14663 return ShortFractTy;
14664 case BuiltinType::SatFract:
14665 return FractTy;
14666 case BuiltinType::SatLongFract:
14667 return LongFractTy;
14668 case BuiltinType::SatUShortFract:
14669 return UnsignedShortFractTy;
14670 case BuiltinType::SatUFract:
14671 return UnsignedFractTy;
14672 case BuiltinType::SatULongFract:
14673 return UnsignedLongFractTy;
14674 }
14675}
14676
14678 assert(Ty->isFixedPointType());
14679
14680 if (Ty->isSaturatedFixedPointType()) return Ty;
14681
14682 switch (Ty->castAs<BuiltinType>()->getKind()) {
14683 default:
14684 llvm_unreachable("Not a fixed point type!");
14685 case BuiltinType::ShortAccum:
14686 return SatShortAccumTy;
14687 case BuiltinType::Accum:
14688 return SatAccumTy;
14689 case BuiltinType::LongAccum:
14690 return SatLongAccumTy;
14691 case BuiltinType::UShortAccum:
14693 case BuiltinType::UAccum:
14694 return SatUnsignedAccumTy;
14695 case BuiltinType::ULongAccum:
14697 case BuiltinType::ShortFract:
14698 return SatShortFractTy;
14699 case BuiltinType::Fract:
14700 return SatFractTy;
14701 case BuiltinType::LongFract:
14702 return SatLongFractTy;
14703 case BuiltinType::UShortFract:
14705 case BuiltinType::UFract:
14706 return SatUnsignedFractTy;
14707 case BuiltinType::ULongFract:
14709 }
14710}
14711
14713 if (LangOpts.OpenCL)
14715
14716 if (LangOpts.CUDA)
14718
14719 return getLangASFromTargetAS(AS);
14720}
14721
14722// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14723// doesn't include ASTContext.h
14724template
14726 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14728 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14729 const clang::ASTContext &Ctx, Decl *Value);
14730
14732 assert(Ty->isFixedPointType());
14733
14734 const TargetInfo &Target = getTargetInfo();
14735 switch (Ty->castAs<BuiltinType>()->getKind()) {
14736 default:
14737 llvm_unreachable("Not a fixed point type!");
14738 case BuiltinType::ShortAccum:
14739 case BuiltinType::SatShortAccum:
14740 return Target.getShortAccumScale();
14741 case BuiltinType::Accum:
14742 case BuiltinType::SatAccum:
14743 return Target.getAccumScale();
14744 case BuiltinType::LongAccum:
14745 case BuiltinType::SatLongAccum:
14746 return Target.getLongAccumScale();
14747 case BuiltinType::UShortAccum:
14748 case BuiltinType::SatUShortAccum:
14749 return Target.getUnsignedShortAccumScale();
14750 case BuiltinType::UAccum:
14751 case BuiltinType::SatUAccum:
14752 return Target.getUnsignedAccumScale();
14753 case BuiltinType::ULongAccum:
14754 case BuiltinType::SatULongAccum:
14755 return Target.getUnsignedLongAccumScale();
14756 case BuiltinType::ShortFract:
14757 case BuiltinType::SatShortFract:
14758 return Target.getShortFractScale();
14759 case BuiltinType::Fract:
14760 case BuiltinType::SatFract:
14761 return Target.getFractScale();
14762 case BuiltinType::LongFract:
14763 case BuiltinType::SatLongFract:
14764 return Target.getLongFractScale();
14765 case BuiltinType::UShortFract:
14766 case BuiltinType::SatUShortFract:
14767 return Target.getUnsignedShortFractScale();
14768 case BuiltinType::UFract:
14769 case BuiltinType::SatUFract:
14770 return Target.getUnsignedFractScale();
14771 case BuiltinType::ULongFract:
14772 case BuiltinType::SatULongFract:
14773 return Target.getUnsignedLongFractScale();
14774 }
14775}
14776
14778 assert(Ty->isFixedPointType());
14779
14780 const TargetInfo &Target = getTargetInfo();
14781 switch (Ty->castAs<BuiltinType>()->getKind()) {
14782 default:
14783 llvm_unreachable("Not a fixed point type!");
14784 case BuiltinType::ShortAccum:
14785 case BuiltinType::SatShortAccum:
14786 return Target.getShortAccumIBits();
14787 case BuiltinType::Accum:
14788 case BuiltinType::SatAccum:
14789 return Target.getAccumIBits();
14790 case BuiltinType::LongAccum:
14791 case BuiltinType::SatLongAccum:
14792 return Target.getLongAccumIBits();
14793 case BuiltinType::UShortAccum:
14794 case BuiltinType::SatUShortAccum:
14795 return Target.getUnsignedShortAccumIBits();
14796 case BuiltinType::UAccum:
14797 case BuiltinType::SatUAccum:
14798 return Target.getUnsignedAccumIBits();
14799 case BuiltinType::ULongAccum:
14800 case BuiltinType::SatULongAccum:
14801 return Target.getUnsignedLongAccumIBits();
14802 case BuiltinType::ShortFract:
14803 case BuiltinType::SatShortFract:
14804 case BuiltinType::Fract:
14805 case BuiltinType::SatFract:
14806 case BuiltinType::LongFract:
14807 case BuiltinType::SatLongFract:
14808 case BuiltinType::UShortFract:
14809 case BuiltinType::SatUShortFract:
14810 case BuiltinType::UFract:
14811 case BuiltinType::SatUFract:
14812 case BuiltinType::ULongFract:
14813 case BuiltinType::SatULongFract:
14814 return 0;
14815 }
14816}
14817
14818llvm::FixedPointSemantics
14820 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14821 "Can only get the fixed point semantics for a "
14822 "fixed point or integer type.");
14823 if (Ty->isIntegerType())
14824 return llvm::FixedPointSemantics::GetIntegerSemantics(
14825 getIntWidth(Ty), Ty->isSignedIntegerType());
14826
14827 bool isSigned = Ty->isSignedFixedPointType();
14828 return llvm::FixedPointSemantics(
14829 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14831 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14832}
14833
14834llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14835 assert(Ty->isFixedPointType());
14836 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14837}
14838
14839llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14840 assert(Ty->isFixedPointType());
14841 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14842}
14843
14845 assert(Ty->isUnsignedFixedPointType() &&
14846 "Expected unsigned fixed point type");
14847
14848 switch (Ty->castAs<BuiltinType>()->getKind()) {
14849 case BuiltinType::UShortAccum:
14850 return ShortAccumTy;
14851 case BuiltinType::UAccum:
14852 return AccumTy;
14853 case BuiltinType::ULongAccum:
14854 return LongAccumTy;
14855 case BuiltinType::SatUShortAccum:
14856 return SatShortAccumTy;
14857 case BuiltinType::SatUAccum:
14858 return SatAccumTy;
14859 case BuiltinType::SatULongAccum:
14860 return SatLongAccumTy;
14861 case BuiltinType::UShortFract:
14862 return ShortFractTy;
14863 case BuiltinType::UFract:
14864 return FractTy;
14865 case BuiltinType::ULongFract:
14866 return LongFractTy;
14867 case BuiltinType::SatUShortFract:
14868 return SatShortFractTy;
14869 case BuiltinType::SatUFract:
14870 return SatFractTy;
14871 case BuiltinType::SatULongFract:
14872 return SatLongFractTy;
14873 default:
14874 llvm_unreachable("Unexpected unsigned fixed point type");
14875 }
14876}
14877
14878// Given a list of FMV features, return a concatenated list of the
14879// corresponding backend features (which may contain duplicates).
14880static std::vector<std::string> getFMVBackendFeaturesFor(
14881 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14882 std::vector<std::string> BackendFeats;
14883 llvm::AArch64::ExtensionSet FeatureBits;
14884 for (StringRef F : FMVFeatStrings)
14885 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14886 if (FMVExt->ID)
14887 FeatureBits.enable(*FMVExt->ID);
14888 FeatureBits.toLLVMFeatureList(BackendFeats);
14889 return BackendFeats;
14890}
14891
14892ParsedTargetAttr
14893ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14894 assert(TD != nullptr);
14895 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14896
14897 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14898 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14899 });
14900 return ParsedAttr;
14901}
14902
14903void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14904 const FunctionDecl *FD) const {
14905 if (FD)
14906 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14907 else
14908 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14909 Target->getTargetOpts().CPU,
14910 Target->getTargetOpts().Features);
14911}
14912
14913// Fills in the supplied string map with the set of target features for the
14914// passed in function.
14915void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14916 GlobalDecl GD) const {
14917 StringRef TargetCPU = Target->getTargetOpts().CPU;
14918 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14919 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14921
14922 // Make a copy of the features as passed on the command line into the
14923 // beginning of the additional features from the function to override.
14924 // AArch64 handles command line option features in parseTargetAttr().
14925 if (!Target->getTriple().isAArch64())
14926 ParsedAttr.Features.insert(
14927 ParsedAttr.Features.begin(),
14928 Target->getTargetOpts().FeaturesAsWritten.begin(),
14929 Target->getTargetOpts().FeaturesAsWritten.end());
14930
14931 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14932 TargetCPU = ParsedAttr.CPU;
14933
14934 // Now populate the feature map, first with the TargetCPU which is either
14935 // the default or a new one from the target attribute string. Then we'll use
14936 // the passed in features (FeaturesAsWritten) along with the new ones from
14937 // the attribute.
14938 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14939 ParsedAttr.Features);
14940 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14942 Target->getCPUSpecificCPUDispatchFeatures(
14943 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14944 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14945 Features.insert(Features.begin(),
14946 Target->getTargetOpts().FeaturesAsWritten.begin(),
14947 Target->getTargetOpts().FeaturesAsWritten.end());
14948 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14949 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14950 if (Target->getTriple().isAArch64()) {
14952 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14953 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14954 Features.insert(Features.begin(),
14955 Target->getTargetOpts().FeaturesAsWritten.begin(),
14956 Target->getTargetOpts().FeaturesAsWritten.end());
14957 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14958 } else if (Target->getTriple().isRISCV()) {
14959 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14960 std::vector<std::string> Features;
14961 if (VersionStr != "default") {
14962 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14963 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14964 ParsedAttr.Features.end());
14965 }
14966 Features.insert(Features.begin(),
14967 Target->getTargetOpts().FeaturesAsWritten.begin(),
14968 Target->getTargetOpts().FeaturesAsWritten.end());
14969 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14970 } else {
14971 std::vector<std::string> Features;
14972 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14973 if (VersionStr.starts_with("arch="))
14974 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14975 else if (VersionStr != "default")
14976 Features.push_back((StringRef{"+"} + VersionStr).str());
14977 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14978 }
14979 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14980 std::vector<std::string> Features;
14981 if (Target->getTriple().isRISCV()) {
14982 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14983 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14984 ParsedAttr.Features.end());
14985 } else {
14986 assert(Target->getTriple().isAArch64());
14988 TV->getFeatures(Feats);
14989 Features = getFMVBackendFeaturesFor(Feats);
14990 }
14991 Features.insert(Features.begin(),
14992 Target->getTargetOpts().FeaturesAsWritten.begin(),
14993 Target->getTargetOpts().FeaturesAsWritten.end());
14994 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14995 } else {
14996 FeatureMap = Target->getTargetOpts().FeatureMap;
14997 }
14998}
14999
15001 CanQualType KernelNameType,
15002 const FunctionDecl *FD) {
15003 // Host and device compilation may use different ABIs and different ABIs
15004 // may allocate name mangling discriminators differently. A discriminator
15005 // override is used to ensure consistent discriminator allocation across
15006 // host and device compilation.
15007 auto DeviceDiscriminatorOverrider =
15008 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15009 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15010 if (RD->isLambda())
15011 return RD->getDeviceLambdaManglingNumber();
15012 return std::nullopt;
15013 };
15014 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15015 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15016
15017 // Construct a mangled name for the SYCL kernel caller offload entry point.
15018 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15019 // name the SYCL kernel caller offload entry point function. This mangling
15020 // does not suffice to clearly identify symbols that correspond to SYCL
15021 // kernel caller functions, nor is this mangling natural for targets that
15022 // use a non-Itanium ABI.
15023 std::string Buffer;
15024 Buffer.reserve(128);
15025 llvm::raw_string_ostream Out(Buffer);
15026 MC->mangleCanonicalTypeName(KernelNameType, Out);
15027 std::string KernelName = Out.str();
15028
15029 return {KernelNameType, FD, KernelName};
15030}
15031
15033 // If the function declaration to register is invalid or dependent, the
15034 // registration attempt is ignored.
15035 if (FD->isInvalidDecl() || FD->isTemplated())
15036 return;
15037
15038 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15039 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15040
15041 // Be tolerant of multiple registration attempts so long as each attempt
15042 // is for the same entity. Callers are obligated to detect and diagnose
15043 // conflicting kernel names prior to calling this function.
15044 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15045 auto IT = SYCLKernels.find(KernelNameType);
15046 assert((IT == SYCLKernels.end() ||
15047 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15048 "SYCL kernel name conflict");
15049 (void)IT;
15050 SYCLKernels.insert(std::make_pair(
15051 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15052}
15053
15055 CanQualType KernelNameType = getCanonicalType(T);
15056 return SYCLKernels.at(KernelNameType);
15057}
15058
15060 CanQualType KernelNameType = getCanonicalType(T);
15061 auto IT = SYCLKernels.find(KernelNameType);
15062 if (IT != SYCLKernels.end())
15063 return &IT->second;
15064 return nullptr;
15065}
15066
15068 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15069 return *OMPTraitInfoVector.back();
15070}
15071
15074 const ASTContext::SectionInfo &Section) {
15075 if (Section.Decl)
15076 return DB << Section.Decl;
15077 return DB << "a prior #pragma section";
15078}
15079
15080bool ASTContext::mayExternalize(const Decl *D) const {
15081 bool IsInternalVar =
15082 isa<VarDecl>(D) &&
15084 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15085 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15086 (D->hasAttr<CUDAConstantAttr>() &&
15087 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15088 // CUDA/HIP: managed variables need to be externalized since it is
15089 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15090 // anonymous name space needs to be externalized to avoid duplicate symbols.
15091 return (IsInternalVar &&
15092 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15093 (D->hasAttr<CUDAGlobalAttr>() &&
15095 GVA_Internal);
15096}
15097
15099 return mayExternalize(D) &&
15100 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15102}
15103
15104StringRef ASTContext::getCUIDHash() const {
15105 if (!CUIDHash.empty())
15106 return CUIDHash;
15107 if (LangOpts.CUID.empty())
15108 return StringRef();
15109 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15110 return CUIDHash;
15111}
15112
15113const CXXRecordDecl *
15115 assert(ThisClass);
15116 assert(ThisClass->isPolymorphic());
15117 const CXXRecordDecl *PrimaryBase = ThisClass;
15118 while (1) {
15119 assert(PrimaryBase);
15120 assert(PrimaryBase->isPolymorphic());
15121 auto &Layout = getASTRecordLayout(PrimaryBase);
15122 auto Base = Layout.getPrimaryBase();
15123 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15124 break;
15125 PrimaryBase = Base;
15126 }
15127 return PrimaryBase;
15128}
15129
15131 StringRef MangledName) {
15132 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15133 assert(Method->isVirtual());
15134 bool DefaultIncludesPointerAuth =
15135 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15136
15137 if (!DefaultIncludesPointerAuth)
15138 return true;
15139
15140 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15141 if (Existing != ThunksToBeAbbreviated.end())
15142 return Existing->second.contains(MangledName.str());
15143
15144 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15145 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15146 auto VtableContext = getVTableContext();
15147 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15148 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15149 for (const auto &Thunk : *ThunkInfos) {
15150 SmallString<256> ElidedName;
15151 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15152 if (Destructor)
15153 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15154 Thunk, /* elideOverrideInfo */ true,
15155 ElidedNameStream);
15156 else
15157 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15158 ElidedNameStream);
15159 SmallString<256> MangledName;
15160 llvm::raw_svector_ostream mangledNameStream(MangledName);
15161 if (Destructor)
15162 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15163 Thunk, /* elideOverrideInfo */ false,
15164 mangledNameStream);
15165 else
15166 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15167 mangledNameStream);
15168
15169 Thunks[ElidedName].push_back(std::string(MangledName));
15170 }
15171 }
15172 llvm::StringSet<> SimplifiedThunkNames;
15173 for (auto &ThunkList : Thunks) {
15174 llvm::sort(ThunkList.second);
15175 SimplifiedThunkNames.insert(ThunkList.second[0]);
15176 }
15177 bool Result = SimplifiedThunkNames.contains(MangledName);
15178 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15179 return Result;
15180}
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:451
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2777
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition MachO.h:31
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:95
Defines the clang::Module class, which describes a module in the source code.
Defines types useful for describing an Objective-C runtime.
#define SM(sm)
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ __2f16 float c
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1073
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1080
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
Definition ASTContext.h:988
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:776
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:777
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:772
Builtin::Context & BuiltinInfo
Definition ASTContext.h:774
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:773
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
Definition ASTContext.h:959
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void cacheRawCommentForDecl(const Decl &OriginalD, const RawComment &Comment) const
Attaches Comment to OriginalD and to its redeclaration chain and removes the redeclaration chain from...
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
CanQualType Float128Ty
CanQualType ObjCBuiltinClassTy
unsigned NumImplicitDefaultConstructorsDeclared
The number of implicitly-declared default constructors for which declarations were built.
CanQualType UnresolvedTemplateTy
OMPTraitInfo & getNewOMPTraitInfo()
Return a new OMPTraitInfo object owned by this context.
friend class CXXRecordDecl
Definition ASTContext.h:555
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:775
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
Definition ASTContext.h:962
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
CanQualType IntTy
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:221
void PrintStats() const
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:778
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
CharUnits getAlignOfGlobalVarInChars(QualType T, const VarDecl *VD) const
Return the alignment in characters that should be given to a global variable with type T.
const ObjCMethodDecl * getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const
Get the duplicate declaration of a ObjCMethod in the same interface, or null if none exists.
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, UnsignedOrNone Index=std::nullopt) const
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
GVALinkage GetGVALinkageForVariable(const VarDecl *VD) const
llvm::PointerUnion< VarTemplateDecl *, MemberSpecializationInfo * > TemplateOrSpecializationInfo
A type synonym for the TemplateOrInstantiation mapping.
Definition ASTContext.h:547
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
llvm::DenseMap< const Decl *, const RawComment * > DeclRawComments
Mapping from declaration to directly attached comment.
Definition ASTContext.h:968
CanQualType OCLSamplerTy
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
CanQualType VoidTy
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions, bool ExpectPackInType=true) const
Form a pack expansion type with the given pattern.
CanQualType UnsignedCharTy
CanQualType UnsignedShortFractTy
BuiltinTemplateDecl * buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, const IdentifierInfo *II) const
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:846
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
RawComment * getRawCommentForDeclNoCache(const Decl *D) const
Return the documentation comment attached to a given declaration, without looking into cache.
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
interp::Context & getInterpContext()
Returns the clang bytecode interpreter context.
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:891
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
Definition ASTContext.h:984
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
unsigned getTargetAddressSpace(LangAS AS) const
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
Definition ASTContext.h:975
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers in instanc...
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
CanQualType Char8Ty
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
RawComment * getRawCommentForDeclNoCacheImpl(const Decl *D, const SourceLocation RepresentativeLocForDecl, const std::map< unsigned, RawComment * > &CommentsInFile) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
QualType mergeTransparentUnionType(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeTransparentUnionType - if T is a transparent union type and a member of T is compatible with Sub...
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
CanQualType getNSUIntegerType() const
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getDataSize() const
getDataSize() - Get the record data size, which is the record size without tail padding,...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
CharUnits getUnadjustedAlignment() const
getUnadjustedAlignment - Get the record alignment in characters, before alignment adjustment.
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition TypeBase.h:3489
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h: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:559
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:176
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:187
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:181
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:184
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h: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:207
bool isAlignRequired()
Definition ASTContext.h:199
AlignRequirementKind AlignRequirement
Definition ASTContext.h:193
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986