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 case BuiltinType::DMR2048:
3505 OS << "?";
3506 return;
3507
3508 // Don't bother discriminating based on these seldom-used types.
3509 case BuiltinType::Ibm128:
3510 return;
3511#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3512 case BuiltinType::Id: \
3513 return;
3514#include "clang/Basic/OpenCLImageTypes.def"
3515#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3516 case BuiltinType::Id: \
3517 return;
3518#include "clang/Basic/OpenCLExtensionTypes.def"
3519#define SVE_TYPE(Name, Id, SingletonId) \
3520 case BuiltinType::Id: \
3521 return;
3522#include "clang/Basic/AArch64ACLETypes.def"
3523#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3524 case BuiltinType::Id: \
3525 return;
3526#include "clang/Basic/HLSLIntangibleTypes.def"
3527 case BuiltinType::Dependent:
3528 llvm_unreachable("should never get here");
3529#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3530#include "clang/Basic/AMDGPUTypes.def"
3531 case BuiltinType::WasmExternRef:
3532#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3533#include "clang/Basic/RISCVVTypes.def"
3534 llvm_unreachable("not yet implemented");
3535 }
3536 llvm_unreachable("should never get here");
3537 }
3538 case Type::Record: {
3539 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getOriginalDecl();
3540 const IdentifierInfo *II = RD->getIdentifier();
3541
3542 // In C++, an immediate typedef of an anonymous struct or union
3543 // is considered to name it for ODR purposes, but C's specification
3544 // of type compatibility does not have a similar rule. Using the typedef
3545 // name in function type discriminators anyway, as we do here,
3546 // therefore technically violates the C standard: two function pointer
3547 // types defined in terms of two typedef'd anonymous structs with
3548 // different names are formally still compatible, but we are assigning
3549 // them different discriminators and therefore incompatible ABIs.
3550 //
3551 // This is a relatively minor violation that significantly improves
3552 // discrimination in some cases and has not caused problems in
3553 // practice. Regardless, it is now part of the ABI in places where
3554 // function type discrimination is used, and it can no longer be
3555 // changed except on new platforms.
3556
3557 if (!II)
3558 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3559 II = Typedef->getDeclName().getAsIdentifierInfo();
3560
3561 if (!II) {
3562 OS << "<anonymous_record>";
3563 return;
3564 }
3565 OS << II->getLength() << II->getName();
3566 return;
3567 }
3568 case Type::HLSLAttributedResource:
3569 case Type::HLSLInlineSpirv:
3570 llvm_unreachable("should never get here");
3571 break;
3572 case Type::DeducedTemplateSpecialization:
3573 case Type::Auto:
3574#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3575#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3576#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3577#define ABSTRACT_TYPE(Class, Base)
3578#define TYPE(Class, Base)
3579#include "clang/AST/TypeNodes.inc"
3580 llvm_unreachable("unexpected non-canonical or dependent type!");
3581 return;
3582 }
3583}
3584
3586 assert(!T->isDependentType() &&
3587 "cannot compute type discriminator of a dependent type");
3588
3589 SmallString<256> Str;
3590 llvm::raw_svector_ostream Out(Str);
3591
3592 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3593 T = T->getPointeeType();
3594
3595 if (T->isFunctionType()) {
3597 } else {
3598 T = T.getUnqualifiedType();
3599 // Calls to member function pointers don't need to worry about
3600 // language interop or the laxness of the C type compatibility rules.
3601 // We just mangle the member pointer type directly, which is
3602 // implicitly much stricter about type matching. However, we do
3603 // strip any top-level exception specification before this mangling.
3604 // C++23 requires calls to work when the function type is convertible
3605 // to the pointer type by a function pointer conversion, which can
3606 // change the exception specification. This does not technically
3607 // require the exception specification to not affect representation,
3608 // because the function pointer conversion is still always a direct
3609 // value conversion and therefore an opportunity to resign the
3610 // pointer. (This is in contrast to e.g. qualification conversions,
3611 // which can be applied in nested pointer positions, effectively
3612 // requiring qualified and unqualified representations to match.)
3613 // However, it is pragmatic to ignore exception specifications
3614 // because it allows a certain amount of `noexcept` mismatching
3615 // to not become a visible ODR problem. This also leaves some
3616 // room for the committee to add laxness to function pointer
3617 // conversions in future standards.
3618 if (auto *MPT = T->getAs<MemberPointerType>())
3619 if (MPT->isMemberFunctionPointer()) {
3620 QualType PointeeType = MPT->getPointeeType();
3621 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3622 EST_None) {
3624 T = getMemberPointerType(FT, MPT->getQualifier(),
3625 MPT->getMostRecentCXXRecordDecl());
3626 }
3627 }
3628 std::unique_ptr<MangleContext> MC(createMangleContext());
3629 MC->mangleCanonicalTypeName(T, Out);
3630 }
3631
3632 return llvm::getPointerAuthStableSipHash(Str);
3633}
3634
3636 Qualifiers::GC GCAttr) const {
3637 QualType CanT = getCanonicalType(T);
3638 if (CanT.getObjCGCAttr() == GCAttr)
3639 return T;
3640
3641 if (const auto *ptr = T->getAs<PointerType>()) {
3642 QualType Pointee = ptr->getPointeeType();
3643 if (Pointee->isAnyPointerType()) {
3644 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3645 return getPointerType(ResultType);
3646 }
3647 }
3648
3649 // If we are composing extended qualifiers together, merge together
3650 // into one ExtQuals node.
3651 QualifierCollector Quals;
3652 const Type *TypeNode = Quals.strip(T);
3653
3654 // If this type already has an ObjCGC specified, it cannot get
3655 // another one.
3656 assert(!Quals.hasObjCGCAttr() &&
3657 "Type cannot have multiple ObjCGCs!");
3658 Quals.addObjCGCAttr(GCAttr);
3659
3660 return getExtQualType(TypeNode, Quals);
3661}
3662
3664 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3665 QualType Pointee = Ptr->getPointeeType();
3666 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3667 return getPointerType(removeAddrSpaceQualType(Pointee));
3668 }
3669 }
3670 return T;
3671}
3672
3674 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3675 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3676 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3677
3678 llvm::FoldingSetNodeID ID;
3679 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3680
3681 void *InsertPos = nullptr;
3682 CountAttributedType *CATy =
3683 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3684 if (CATy)
3685 return QualType(CATy, 0);
3686
3687 QualType CanonTy = getCanonicalType(WrappedTy);
3688 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3689 DependentDecls.size());
3691 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3692 OrNull, DependentDecls);
3693 Types.push_back(CATy);
3694 CountAttributedTypes.InsertNode(CATy, InsertPos);
3695
3696 return QualType(CATy, 0);
3697}
3698
3701 llvm::function_ref<QualType(QualType)> Adjust) const {
3702 switch (Orig->getTypeClass()) {
3703 case Type::Attributed: {
3704 const auto *AT = cast<AttributedType>(Orig);
3705 return getAttributedType(AT->getAttrKind(),
3706 adjustType(AT->getModifiedType(), Adjust),
3707 adjustType(AT->getEquivalentType(), Adjust),
3708 AT->getAttr());
3709 }
3710
3711 case Type::BTFTagAttributed: {
3712 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3713 return getBTFTagAttributedType(BTFT->getAttr(),
3714 adjustType(BTFT->getWrappedType(), Adjust));
3715 }
3716
3717 case Type::Paren:
3718 return getParenType(
3719 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3720
3721 case Type::Adjusted: {
3722 const auto *AT = cast<AdjustedType>(Orig);
3723 return getAdjustedType(AT->getOriginalType(),
3724 adjustType(AT->getAdjustedType(), Adjust));
3725 }
3726
3727 case Type::MacroQualified: {
3728 const auto *MQT = cast<MacroQualifiedType>(Orig);
3729 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3730 MQT->getMacroIdentifier());
3731 }
3732
3733 default:
3734 return Adjust(Orig);
3735 }
3736}
3737
3739 FunctionType::ExtInfo Info) {
3740 if (T->getExtInfo() == Info)
3741 return T;
3742
3744 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3745 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3746 } else {
3747 const auto *FPT = cast<FunctionProtoType>(T);
3748 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3749 EPI.ExtInfo = Info;
3750 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3751 }
3752
3753 return cast<FunctionType>(Result.getTypePtr());
3754}
3755
3757 QualType ResultType) {
3758 return adjustType(FunctionType, [&](QualType Orig) {
3759 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3760 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3761
3762 const auto *FPT = Orig->castAs<FunctionProtoType>();
3763 return getFunctionType(ResultType, FPT->getParamTypes(),
3764 FPT->getExtProtoInfo());
3765 });
3766}
3767
3769 QualType ResultType) {
3770 FD = FD->getMostRecentDecl();
3771 while (true) {
3772 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3773 if (FunctionDecl *Next = FD->getPreviousDecl())
3774 FD = Next;
3775 else
3776 break;
3777 }
3779 L->DeducedReturnType(FD, ResultType);
3780}
3781
3782/// Get a function type and produce the equivalent function type with the
3783/// specified exception specification. Type sugar that can be present on a
3784/// declaration of a function with an exception specification is permitted
3785/// and preserved. Other type sugar (for instance, typedefs) is not.
3787 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3788 return adjustType(Orig, [&](QualType Ty) {
3789 const auto *Proto = Ty->castAs<FunctionProtoType>();
3790 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3791 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3792 });
3793}
3794
3802
3804 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3805 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3806 SmallVector<QualType, 16> Args(Proto->param_types().size());
3807 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3808 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3809 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3810 }
3811
3812 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3813 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3814 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3815 }
3816
3817 return T;
3818}
3819
3825
3827 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3828 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3829 EPI.ExtParameterInfos = nullptr;
3830 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3831 }
3832 return T;
3833}
3834
3840
3843 bool AsWritten) {
3844 // Update the type.
3845 QualType Updated =
3847 FD->setType(Updated);
3848
3849 if (!AsWritten)
3850 return;
3851
3852 // Update the type in the type source information too.
3853 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3854 // If the type and the type-as-written differ, we may need to update
3855 // the type-as-written too.
3856 if (TSInfo->getType() != FD->getType())
3857 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3858
3859 // FIXME: When we get proper type location information for exceptions,
3860 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3861 // up the TypeSourceInfo;
3862 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3863 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3864 "TypeLoc size mismatch from updating exception specification");
3865 TSInfo->overrideType(Updated);
3866 }
3867}
3868
3869/// getComplexType - Return the uniqued reference to the type for a complex
3870/// number with the specified element type.
3872 // Unique pointers, to guarantee there is only one pointer of a particular
3873 // structure.
3874 llvm::FoldingSetNodeID ID;
3876
3877 void *InsertPos = nullptr;
3878 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3879 return QualType(CT, 0);
3880
3881 // If the pointee type isn't canonical, this won't be a canonical type either,
3882 // so fill in the canonical type field.
3883 QualType Canonical;
3884 if (!T.isCanonical()) {
3885 Canonical = getComplexType(getCanonicalType(T));
3886
3887 // Get the new insert position for the node we care about.
3888 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3889 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3890 }
3891 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3892 Types.push_back(New);
3893 ComplexTypes.InsertNode(New, InsertPos);
3894 return QualType(New, 0);
3895}
3896
3897/// getPointerType - Return the uniqued reference to the type for a pointer to
3898/// the specified type.
3900 // Unique pointers, to guarantee there is only one pointer of a particular
3901 // structure.
3902 llvm::FoldingSetNodeID ID;
3904
3905 void *InsertPos = nullptr;
3906 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3907 return QualType(PT, 0);
3908
3909 // If the pointee type isn't canonical, this won't be a canonical type either,
3910 // so fill in the canonical type field.
3911 QualType Canonical;
3912 if (!T.isCanonical()) {
3913 Canonical = getPointerType(getCanonicalType(T));
3914
3915 // Get the new insert position for the node we care about.
3916 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3917 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3918 }
3919 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
3920 Types.push_back(New);
3921 PointerTypes.InsertNode(New, InsertPos);
3922 return QualType(New, 0);
3923}
3924
3926 llvm::FoldingSetNodeID ID;
3927 AdjustedType::Profile(ID, Orig, New);
3928 void *InsertPos = nullptr;
3929 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3930 if (AT)
3931 return QualType(AT, 0);
3932
3933 QualType Canonical = getCanonicalType(New);
3934
3935 // Get the new insert position for the node we care about.
3936 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3937 assert(!AT && "Shouldn't be in the map!");
3938
3939 AT = new (*this, alignof(AdjustedType))
3940 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3941 Types.push_back(AT);
3942 AdjustedTypes.InsertNode(AT, InsertPos);
3943 return QualType(AT, 0);
3944}
3945
3947 llvm::FoldingSetNodeID ID;
3948 AdjustedType::Profile(ID, Orig, Decayed);
3949 void *InsertPos = nullptr;
3950 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3951 if (AT)
3952 return QualType(AT, 0);
3953
3954 QualType Canonical = getCanonicalType(Decayed);
3955
3956 // Get the new insert position for the node we care about.
3957 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3958 assert(!AT && "Shouldn't be in the map!");
3959
3960 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
3961 Types.push_back(AT);
3962 AdjustedTypes.InsertNode(AT, InsertPos);
3963 return QualType(AT, 0);
3964}
3965
3967 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3968
3969 QualType Decayed;
3970
3971 // C99 6.7.5.3p7:
3972 // A declaration of a parameter as "array of type" shall be
3973 // adjusted to "qualified pointer to type", where the type
3974 // qualifiers (if any) are those specified within the [ and ] of
3975 // the array type derivation.
3976 if (T->isArrayType())
3977 Decayed = getArrayDecayedType(T);
3978
3979 // C99 6.7.5.3p8:
3980 // A declaration of a parameter as "function returning type"
3981 // shall be adjusted to "pointer to function returning type", as
3982 // in 6.3.2.1.
3983 if (T->isFunctionType())
3984 Decayed = getPointerType(T);
3985
3986 return getDecayedType(T, Decayed);
3987}
3988
3990 if (Ty->isArrayParameterType())
3991 return Ty;
3992 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
3993 QualType DTy = Ty.getDesugaredType(*this);
3994 const auto *ATy = cast<ConstantArrayType>(DTy);
3995 llvm::FoldingSetNodeID ID;
3996 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
3997 ATy->getSizeExpr(), ATy->getSizeModifier(),
3998 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
3999 void *InsertPos = nullptr;
4000 ArrayParameterType *AT =
4001 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4002 if (AT)
4003 return QualType(AT, 0);
4004
4005 QualType Canonical;
4006 if (!DTy.isCanonical()) {
4007 Canonical = getArrayParameterType(getCanonicalType(Ty));
4008
4009 // Get the new insert position for the node we care about.
4010 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4011 assert(!AT && "Shouldn't be in the map!");
4012 }
4013
4014 AT = new (*this, alignof(ArrayParameterType))
4015 ArrayParameterType(ATy, Canonical);
4016 Types.push_back(AT);
4017 ArrayParameterTypes.InsertNode(AT, InsertPos);
4018 return QualType(AT, 0);
4019}
4020
4021/// getBlockPointerType - Return the uniqued reference to the type for
4022/// a pointer to the specified block.
4024 assert(T->isFunctionType() && "block of function types only");
4025 // Unique pointers, to guarantee there is only one block of a particular
4026 // structure.
4027 llvm::FoldingSetNodeID ID;
4029
4030 void *InsertPos = nullptr;
4031 if (BlockPointerType *PT =
4032 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4033 return QualType(PT, 0);
4034
4035 // If the block pointee type isn't canonical, this won't be a canonical
4036 // type either so fill in the canonical type field.
4037 QualType Canonical;
4038 if (!T.isCanonical()) {
4040
4041 // Get the new insert position for the node we care about.
4042 BlockPointerType *NewIP =
4043 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4044 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4045 }
4046 auto *New =
4047 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4048 Types.push_back(New);
4049 BlockPointerTypes.InsertNode(New, InsertPos);
4050 return QualType(New, 0);
4051}
4052
4053/// getLValueReferenceType - Return the uniqued reference to the type for an
4054/// lvalue reference to the specified type.
4056ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4057 assert((!T->isPlaceholderType() ||
4058 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4059 "Unresolved placeholder type");
4060
4061 // Unique pointers, to guarantee there is only one pointer of a particular
4062 // structure.
4063 llvm::FoldingSetNodeID ID;
4064 ReferenceType::Profile(ID, T, SpelledAsLValue);
4065
4066 void *InsertPos = nullptr;
4067 if (LValueReferenceType *RT =
4068 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4069 return QualType(RT, 0);
4070
4071 const auto *InnerRef = T->getAs<ReferenceType>();
4072
4073 // If the referencee type isn't canonical, this won't be a canonical type
4074 // either, so fill in the canonical type field.
4075 QualType Canonical;
4076 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4077 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4078 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4079
4080 // Get the new insert position for the node we care about.
4081 LValueReferenceType *NewIP =
4082 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4083 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4084 }
4085
4086 auto *New = new (*this, alignof(LValueReferenceType))
4087 LValueReferenceType(T, Canonical, SpelledAsLValue);
4088 Types.push_back(New);
4089 LValueReferenceTypes.InsertNode(New, InsertPos);
4090
4091 return QualType(New, 0);
4092}
4093
4094/// getRValueReferenceType - Return the uniqued reference to the type for an
4095/// rvalue reference to the specified type.
4097 assert((!T->isPlaceholderType() ||
4098 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4099 "Unresolved placeholder type");
4100
4101 // Unique pointers, to guarantee there is only one pointer of a particular
4102 // structure.
4103 llvm::FoldingSetNodeID ID;
4104 ReferenceType::Profile(ID, T, false);
4105
4106 void *InsertPos = nullptr;
4107 if (RValueReferenceType *RT =
4108 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4109 return QualType(RT, 0);
4110
4111 const auto *InnerRef = T->getAs<ReferenceType>();
4112
4113 // If the referencee type isn't canonical, this won't be a canonical type
4114 // either, so fill in the canonical type field.
4115 QualType Canonical;
4116 if (InnerRef || !T.isCanonical()) {
4117 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4118 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4119
4120 // Get the new insert position for the node we care about.
4121 RValueReferenceType *NewIP =
4122 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4123 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4124 }
4125
4126 auto *New = new (*this, alignof(RValueReferenceType))
4127 RValueReferenceType(T, Canonical);
4128 Types.push_back(New);
4129 RValueReferenceTypes.InsertNode(New, InsertPos);
4130 return QualType(New, 0);
4131}
4132
4134 NestedNameSpecifier Qualifier,
4135 const CXXRecordDecl *Cls) const {
4136 if (!Qualifier) {
4137 assert(Cls && "At least one of Qualifier or Cls must be provided");
4138 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4139 } else if (!Cls) {
4140 Cls = Qualifier.getAsRecordDecl();
4141 }
4142 // Unique pointers, to guarantee there is only one pointer of a particular
4143 // structure.
4144 llvm::FoldingSetNodeID ID;
4145 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4146
4147 void *InsertPos = nullptr;
4148 if (MemberPointerType *PT =
4149 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4150 return QualType(PT, 0);
4151
4152 NestedNameSpecifier CanonicalQualifier = [&] {
4153 if (!Cls)
4154 return Qualifier.getCanonical();
4155 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4156 assert(R.isCanonical());
4157 return R;
4158 }();
4159 // If the pointee or class type isn't canonical, this won't be a canonical
4160 // type either, so fill in the canonical type field.
4161 QualType Canonical;
4162 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4163 Canonical =
4164 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4165 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4166 // Get the new insert position for the node we care about.
4167 [[maybe_unused]] MemberPointerType *NewIP =
4168 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4169 assert(!NewIP && "Shouldn't be in the map!");
4170 }
4171 auto *New = new (*this, alignof(MemberPointerType))
4172 MemberPointerType(T, Qualifier, Canonical);
4173 Types.push_back(New);
4174 MemberPointerTypes.InsertNode(New, InsertPos);
4175 return QualType(New, 0);
4176}
4177
4178/// getConstantArrayType - Return the unique reference to the type for an
4179/// array of the specified element type.
4181 const llvm::APInt &ArySizeIn,
4182 const Expr *SizeExpr,
4184 unsigned IndexTypeQuals) const {
4185 assert((EltTy->isDependentType() ||
4186 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4187 "Constant array of VLAs is illegal!");
4188
4189 // We only need the size as part of the type if it's instantiation-dependent.
4190 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4191 SizeExpr = nullptr;
4192
4193 // Convert the array size into a canonical width matching the pointer size for
4194 // the target.
4195 llvm::APInt ArySize(ArySizeIn);
4196 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4197
4198 llvm::FoldingSetNodeID ID;
4199 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4200 ASM, IndexTypeQuals);
4201
4202 void *InsertPos = nullptr;
4203 if (ConstantArrayType *ATP =
4204 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4205 return QualType(ATP, 0);
4206
4207 // If the element type isn't canonical or has qualifiers, or the array bound
4208 // is instantiation-dependent, this won't be a canonical type either, so fill
4209 // in the canonical type field.
4210 QualType Canon;
4211 // FIXME: Check below should look for qualifiers behind sugar.
4212 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4213 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4214 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4215 ASM, IndexTypeQuals);
4216 Canon = getQualifiedType(Canon, canonSplit.Quals);
4217
4218 // Get the new insert position for the node we care about.
4219 ConstantArrayType *NewIP =
4220 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4221 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4222 }
4223
4224 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4225 ASM, IndexTypeQuals);
4226 ConstantArrayTypes.InsertNode(New, InsertPos);
4227 Types.push_back(New);
4228 return QualType(New, 0);
4229}
4230
4231/// getVariableArrayDecayedType - Turns the given type, which may be
4232/// variably-modified, into the corresponding type with all the known
4233/// sizes replaced with [*].
4235 // Vastly most common case.
4236 if (!type->isVariablyModifiedType()) return type;
4237
4238 QualType result;
4239
4240 SplitQualType split = type.getSplitDesugaredType();
4241 const Type *ty = split.Ty;
4242 switch (ty->getTypeClass()) {
4243#define TYPE(Class, Base)
4244#define ABSTRACT_TYPE(Class, Base)
4245#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4246#include "clang/AST/TypeNodes.inc"
4247 llvm_unreachable("didn't desugar past all non-canonical types?");
4248
4249 // These types should never be variably-modified.
4250 case Type::Builtin:
4251 case Type::Complex:
4252 case Type::Vector:
4253 case Type::DependentVector:
4254 case Type::ExtVector:
4255 case Type::DependentSizedExtVector:
4256 case Type::ConstantMatrix:
4257 case Type::DependentSizedMatrix:
4258 case Type::DependentAddressSpace:
4259 case Type::ObjCObject:
4260 case Type::ObjCInterface:
4261 case Type::ObjCObjectPointer:
4262 case Type::Record:
4263 case Type::Enum:
4264 case Type::UnresolvedUsing:
4265 case Type::TypeOfExpr:
4266 case Type::TypeOf:
4267 case Type::Decltype:
4268 case Type::UnaryTransform:
4269 case Type::DependentName:
4270 case Type::InjectedClassName:
4271 case Type::TemplateSpecialization:
4272 case Type::TemplateTypeParm:
4273 case Type::SubstTemplateTypeParmPack:
4274 case Type::SubstBuiltinTemplatePack:
4275 case Type::Auto:
4276 case Type::DeducedTemplateSpecialization:
4277 case Type::PackExpansion:
4278 case Type::PackIndexing:
4279 case Type::BitInt:
4280 case Type::DependentBitInt:
4281 case Type::ArrayParameter:
4282 case Type::HLSLAttributedResource:
4283 case Type::HLSLInlineSpirv:
4284 llvm_unreachable("type should never be variably-modified");
4285
4286 // These types can be variably-modified but should never need to
4287 // further decay.
4288 case Type::FunctionNoProto:
4289 case Type::FunctionProto:
4290 case Type::BlockPointer:
4291 case Type::MemberPointer:
4292 case Type::Pipe:
4293 return type;
4294
4295 // These types can be variably-modified. All these modifications
4296 // preserve structure except as noted by comments.
4297 // TODO: if we ever care about optimizing VLAs, there are no-op
4298 // optimizations available here.
4299 case Type::Pointer:
4302 break;
4303
4304 case Type::LValueReference: {
4305 const auto *lv = cast<LValueReferenceType>(ty);
4306 result = getLValueReferenceType(
4307 getVariableArrayDecayedType(lv->getPointeeType()),
4308 lv->isSpelledAsLValue());
4309 break;
4310 }
4311
4312 case Type::RValueReference: {
4313 const auto *lv = cast<RValueReferenceType>(ty);
4314 result = getRValueReferenceType(
4315 getVariableArrayDecayedType(lv->getPointeeType()));
4316 break;
4317 }
4318
4319 case Type::Atomic: {
4320 const auto *at = cast<AtomicType>(ty);
4321 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4322 break;
4323 }
4324
4325 case Type::ConstantArray: {
4326 const auto *cat = cast<ConstantArrayType>(ty);
4327 result = getConstantArrayType(
4328 getVariableArrayDecayedType(cat->getElementType()),
4329 cat->getSize(),
4330 cat->getSizeExpr(),
4331 cat->getSizeModifier(),
4332 cat->getIndexTypeCVRQualifiers());
4333 break;
4334 }
4335
4336 case Type::DependentSizedArray: {
4337 const auto *dat = cast<DependentSizedArrayType>(ty);
4339 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4340 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4341 break;
4342 }
4343
4344 // Turn incomplete types into [*] types.
4345 case Type::IncompleteArray: {
4346 const auto *iat = cast<IncompleteArrayType>(ty);
4347 result =
4349 /*size*/ nullptr, ArraySizeModifier::Normal,
4350 iat->getIndexTypeCVRQualifiers());
4351 break;
4352 }
4353
4354 // Turn VLA types into [*] types.
4355 case Type::VariableArray: {
4356 const auto *vat = cast<VariableArrayType>(ty);
4357 result =
4359 /*size*/ nullptr, ArraySizeModifier::Star,
4360 vat->getIndexTypeCVRQualifiers());
4361 break;
4362 }
4363 }
4364
4365 // Apply the top-level qualifiers from the original.
4366 return getQualifiedType(result, split.Quals);
4367}
4368
4369/// getVariableArrayType - Returns a non-unique reference to the type for a
4370/// variable array of the specified element type.
4373 unsigned IndexTypeQuals) const {
4374 // Since we don't unique expressions, it isn't possible to unique VLA's
4375 // that have an expression provided for their size.
4376 QualType Canon;
4377
4378 // Be sure to pull qualifiers off the element type.
4379 // FIXME: Check below should look for qualifiers behind sugar.
4380 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4381 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4382 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4383 IndexTypeQuals);
4384 Canon = getQualifiedType(Canon, canonSplit.Quals);
4385 }
4386
4387 auto *New = new (*this, alignof(VariableArrayType))
4388 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4389
4390 VariableArrayTypes.push_back(New);
4391 Types.push_back(New);
4392 return QualType(New, 0);
4393}
4394
4395/// getDependentSizedArrayType - Returns a non-unique reference to
4396/// the type for a dependently-sized array of the specified element
4397/// type.
4401 unsigned elementTypeQuals) const {
4402 assert((!numElements || numElements->isTypeDependent() ||
4403 numElements->isValueDependent()) &&
4404 "Size must be type- or value-dependent!");
4405
4406 SplitQualType canonElementType = getCanonicalType(elementType).split();
4407
4408 void *insertPos = nullptr;
4409 llvm::FoldingSetNodeID ID;
4411 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4412 ASM, elementTypeQuals, numElements);
4413
4414 // Look for an existing type with these properties.
4415 DependentSizedArrayType *canonTy =
4416 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4417
4418 // Dependently-sized array types that do not have a specified number
4419 // of elements will have their sizes deduced from a dependent
4420 // initializer.
4421 if (!numElements) {
4422 if (canonTy)
4423 return QualType(canonTy, 0);
4424
4425 auto *newType = new (*this, alignof(DependentSizedArrayType))
4426 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4427 elementTypeQuals);
4428 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4429 Types.push_back(newType);
4430 return QualType(newType, 0);
4431 }
4432
4433 // If we don't have one, build one.
4434 if (!canonTy) {
4435 canonTy = new (*this, alignof(DependentSizedArrayType))
4436 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4437 numElements, ASM, elementTypeQuals);
4438 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4439 Types.push_back(canonTy);
4440 }
4441
4442 // Apply qualifiers from the element type to the array.
4443 QualType canon = getQualifiedType(QualType(canonTy,0),
4444 canonElementType.Quals);
4445
4446 // If we didn't need extra canonicalization for the element type or the size
4447 // expression, then just use that as our result.
4448 if (QualType(canonElementType.Ty, 0) == elementType &&
4449 canonTy->getSizeExpr() == numElements)
4450 return canon;
4451
4452 // Otherwise, we need to build a type which follows the spelling
4453 // of the element type.
4454 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4455 DependentSizedArrayType(elementType, canon, numElements, ASM,
4456 elementTypeQuals);
4457 Types.push_back(sugaredType);
4458 return QualType(sugaredType, 0);
4459}
4460
4463 unsigned elementTypeQuals) const {
4464 llvm::FoldingSetNodeID ID;
4465 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4466
4467 void *insertPos = nullptr;
4468 if (IncompleteArrayType *iat =
4469 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4470 return QualType(iat, 0);
4471
4472 // If the element type isn't canonical, this won't be a canonical type
4473 // either, so fill in the canonical type field. We also have to pull
4474 // qualifiers off the element type.
4475 QualType canon;
4476
4477 // FIXME: Check below should look for qualifiers behind sugar.
4478 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4479 SplitQualType canonSplit = getCanonicalType(elementType).split();
4480 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4481 ASM, elementTypeQuals);
4482 canon = getQualifiedType(canon, canonSplit.Quals);
4483
4484 // Get the new insert position for the node we care about.
4485 IncompleteArrayType *existing =
4486 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4487 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4488 }
4489
4490 auto *newType = new (*this, alignof(IncompleteArrayType))
4491 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4492
4493 IncompleteArrayTypes.InsertNode(newType, insertPos);
4494 Types.push_back(newType);
4495 return QualType(newType, 0);
4496}
4497
4500#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4501 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4502 NUMVECTORS};
4503
4504#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4505 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4506
4507 switch (Ty->getKind()) {
4508 default:
4509 llvm_unreachable("Unsupported builtin vector type");
4510
4511#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4512 ElBits, NF, IsSigned) \
4513 case BuiltinType::Id: \
4514 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4515 llvm::ElementCount::getScalable(NumEls), NF};
4516#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4517 ElBits, NF) \
4518 case BuiltinType::Id: \
4519 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4520 llvm::ElementCount::getScalable(NumEls), NF};
4521#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4522 ElBits, NF) \
4523 case BuiltinType::Id: \
4524 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4525#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4526 ElBits, NF) \
4527 case BuiltinType::Id: \
4528 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4529#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4530 case BuiltinType::Id: \
4531 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4532#include "clang/Basic/AArch64ACLETypes.def"
4533
4534#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4535 IsSigned) \
4536 case BuiltinType::Id: \
4537 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4538 llvm::ElementCount::getScalable(NumEls), NF};
4539#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4540 case BuiltinType::Id: \
4541 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4542 llvm::ElementCount::getScalable(NumEls), NF};
4543#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4544 case BuiltinType::Id: \
4545 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4546#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4547 case BuiltinType::Id: \
4548 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4549#include "clang/Basic/RISCVVTypes.def"
4550 }
4551}
4552
4553/// getExternrefType - Return a WebAssembly externref type, which represents an
4554/// opaque reference to a host value.
4556 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4557#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4558 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4559 return SingletonId;
4560#include "clang/Basic/WebAssemblyReferenceTypes.def"
4561 }
4562 llvm_unreachable(
4563 "shouldn't try to generate type externref outside WebAssembly target");
4564}
4565
4566/// getScalableVectorType - Return the unique reference to a scalable vector
4567/// type of the specified element type and size. VectorType must be a built-in
4568/// type.
4570 unsigned NumFields) const {
4571 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4572 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4573 return It->second;
4574
4575 if (Target->hasAArch64ACLETypes()) {
4576 uint64_t EltTySize = getTypeSize(EltTy);
4577
4578#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4579 ElBits, NF, IsSigned) \
4580 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4581 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4582 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4583 return ScalableVecTyMap[K] = SingletonId; \
4584 }
4585#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4586 ElBits, NF) \
4587 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4588 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4589 return ScalableVecTyMap[K] = SingletonId; \
4590 }
4591#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4592 ElBits, NF) \
4593 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4594 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4595 return ScalableVecTyMap[K] = SingletonId; \
4596 }
4597#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4598 ElBits, NF) \
4599 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4600 NumElts == (NumEls * NF) && NumFields == 1) { \
4601 return ScalableVecTyMap[K] = SingletonId; \
4602 }
4603#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4604 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4605 return ScalableVecTyMap[K] = SingletonId;
4606#include "clang/Basic/AArch64ACLETypes.def"
4607 } else if (Target->hasRISCVVTypes()) {
4608 uint64_t EltTySize = getTypeSize(EltTy);
4609#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4610 IsFP, IsBF) \
4611 if (!EltTy->isBooleanType() && \
4612 ((EltTy->hasIntegerRepresentation() && \
4613 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4614 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4615 IsFP && !IsBF) || \
4616 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4617 IsBF && !IsFP)) && \
4618 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4619 return ScalableVecTyMap[K] = SingletonId;
4620#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4621 if (EltTy->isBooleanType() && NumElts == NumEls) \
4622 return ScalableVecTyMap[K] = SingletonId;
4623#include "clang/Basic/RISCVVTypes.def"
4624 }
4625 return QualType();
4626}
4627
4628/// getVectorType - Return the unique reference to a vector type of
4629/// the specified element type and size. VectorType must be a built-in type.
4631 VectorKind VecKind) const {
4632 assert(vecType->isBuiltinType() ||
4633 (vecType->isBitIntType() &&
4634 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4635 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4636
4637 // Check if we've already instantiated a vector of this type.
4638 llvm::FoldingSetNodeID ID;
4639 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4640
4641 void *InsertPos = nullptr;
4642 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4643 return QualType(VTP, 0);
4644
4645 // If the element type isn't canonical, this won't be a canonical type either,
4646 // so fill in the canonical type field.
4647 QualType Canonical;
4648 if (!vecType.isCanonical()) {
4649 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4650
4651 // Get the new insert position for the node we care about.
4652 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4653 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4654 }
4655 auto *New = new (*this, alignof(VectorType))
4656 VectorType(vecType, NumElts, Canonical, VecKind);
4657 VectorTypes.InsertNode(New, InsertPos);
4658 Types.push_back(New);
4659 return QualType(New, 0);
4660}
4661
4663 SourceLocation AttrLoc,
4664 VectorKind VecKind) const {
4665 llvm::FoldingSetNodeID ID;
4666 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4667 VecKind);
4668 void *InsertPos = nullptr;
4669 DependentVectorType *Canon =
4670 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4672
4673 if (Canon) {
4674 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4675 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4676 } else {
4677 QualType CanonVecTy = getCanonicalType(VecType);
4678 if (CanonVecTy == VecType) {
4679 New = new (*this, alignof(DependentVectorType))
4680 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4681
4682 DependentVectorType *CanonCheck =
4683 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4684 assert(!CanonCheck &&
4685 "Dependent-sized vector_size canonical type broken");
4686 (void)CanonCheck;
4687 DependentVectorTypes.InsertNode(New, InsertPos);
4688 } else {
4689 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4690 SourceLocation(), VecKind);
4691 New = new (*this, alignof(DependentVectorType))
4692 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4693 }
4694 }
4695
4696 Types.push_back(New);
4697 return QualType(New, 0);
4698}
4699
4700/// getExtVectorType - Return the unique reference to an extended vector type of
4701/// the specified element type and size. VectorType must be a built-in type.
4703 unsigned NumElts) const {
4704 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4705 (vecType->isBitIntType() &&
4706 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4707 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4708
4709 // Check if we've already instantiated a vector of this type.
4710 llvm::FoldingSetNodeID ID;
4711 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4713 void *InsertPos = nullptr;
4714 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4715 return QualType(VTP, 0);
4716
4717 // If the element type isn't canonical, this won't be a canonical type either,
4718 // so fill in the canonical type field.
4719 QualType Canonical;
4720 if (!vecType.isCanonical()) {
4721 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4722
4723 // Get the new insert position for the node we care about.
4724 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4725 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4726 }
4727 auto *New = new (*this, alignof(ExtVectorType))
4728 ExtVectorType(vecType, NumElts, Canonical);
4729 VectorTypes.InsertNode(New, InsertPos);
4730 Types.push_back(New);
4731 return QualType(New, 0);
4732}
4733
4736 Expr *SizeExpr,
4737 SourceLocation AttrLoc) const {
4738 llvm::FoldingSetNodeID ID;
4740 SizeExpr);
4741
4742 void *InsertPos = nullptr;
4744 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4746 if (Canon) {
4747 // We already have a canonical version of this array type; use it as
4748 // the canonical type for a newly-built type.
4749 New = new (*this, alignof(DependentSizedExtVectorType))
4750 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4751 AttrLoc);
4752 } else {
4753 QualType CanonVecTy = getCanonicalType(vecType);
4754 if (CanonVecTy == vecType) {
4755 New = new (*this, alignof(DependentSizedExtVectorType))
4756 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4757
4758 DependentSizedExtVectorType *CanonCheck
4759 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4760 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4761 (void)CanonCheck;
4762 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4763 } else {
4764 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4765 SourceLocation());
4766 New = new (*this, alignof(DependentSizedExtVectorType))
4767 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4768 }
4769 }
4770
4771 Types.push_back(New);
4772 return QualType(New, 0);
4773}
4774
4776 unsigned NumColumns) const {
4777 llvm::FoldingSetNodeID ID;
4778 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4779 Type::ConstantMatrix);
4780
4781 assert(MatrixType::isValidElementType(ElementTy) &&
4782 "need a valid element type");
4783 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
4785 "need valid matrix dimensions");
4786 void *InsertPos = nullptr;
4787 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4788 return QualType(MTP, 0);
4789
4790 QualType Canonical;
4791 if (!ElementTy.isCanonical()) {
4792 Canonical =
4793 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4794
4795 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4796 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4797 (void)NewIP;
4798 }
4799
4800 auto *New = new (*this, alignof(ConstantMatrixType))
4801 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4802 MatrixTypes.InsertNode(New, InsertPos);
4803 Types.push_back(New);
4804 return QualType(New, 0);
4805}
4806
4808 Expr *RowExpr,
4809 Expr *ColumnExpr,
4810 SourceLocation AttrLoc) const {
4811 QualType CanonElementTy = getCanonicalType(ElementTy);
4812 llvm::FoldingSetNodeID ID;
4813 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4814 ColumnExpr);
4815
4816 void *InsertPos = nullptr;
4818 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4819
4820 if (!Canon) {
4821 Canon = new (*this, alignof(DependentSizedMatrixType))
4822 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4823 ColumnExpr, AttrLoc);
4824#ifndef NDEBUG
4825 DependentSizedMatrixType *CanonCheck =
4826 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4827 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4828#endif
4829 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4830 Types.push_back(Canon);
4831 }
4832
4833 // Already have a canonical version of the matrix type
4834 //
4835 // If it exactly matches the requested type, use it directly.
4836 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4837 Canon->getRowExpr() == ColumnExpr)
4838 return QualType(Canon, 0);
4839
4840 // Use Canon as the canonical type for newly-built type.
4842 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4843 ColumnExpr, AttrLoc);
4844 Types.push_back(New);
4845 return QualType(New, 0);
4846}
4847
4849 Expr *AddrSpaceExpr,
4850 SourceLocation AttrLoc) const {
4851 assert(AddrSpaceExpr->isInstantiationDependent());
4852
4853 QualType canonPointeeType = getCanonicalType(PointeeType);
4854
4855 void *insertPos = nullptr;
4856 llvm::FoldingSetNodeID ID;
4857 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4858 AddrSpaceExpr);
4859
4860 DependentAddressSpaceType *canonTy =
4861 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4862
4863 if (!canonTy) {
4864 canonTy = new (*this, alignof(DependentAddressSpaceType))
4865 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4866 AttrLoc);
4867 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4868 Types.push_back(canonTy);
4869 }
4870
4871 if (canonPointeeType == PointeeType &&
4872 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4873 return QualType(canonTy, 0);
4874
4875 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4876 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4877 AddrSpaceExpr, AttrLoc);
4878 Types.push_back(sugaredType);
4879 return QualType(sugaredType, 0);
4880}
4881
4882/// Determine whether \p T is canonical as the result type of a function.
4884 return T.isCanonical() &&
4885 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4886 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4887}
4888
4889/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4890QualType
4892 const FunctionType::ExtInfo &Info) const {
4893 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4894 // functionality creates a function without a prototype regardless of
4895 // language mode (so it makes them even in C++). Once the rewriter has been
4896 // fixed, this assertion can be enabled again.
4897 //assert(!LangOpts.requiresStrictPrototypes() &&
4898 // "strict prototypes are disabled");
4899
4900 // Unique functions, to guarantee there is only one function of a particular
4901 // structure.
4902 llvm::FoldingSetNodeID ID;
4903 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4904
4905 void *InsertPos = nullptr;
4906 if (FunctionNoProtoType *FT =
4907 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
4908 return QualType(FT, 0);
4909
4910 QualType Canonical;
4911 if (!isCanonicalResultType(ResultTy)) {
4912 Canonical =
4914
4915 // Get the new insert position for the node we care about.
4916 FunctionNoProtoType *NewIP =
4917 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4918 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4919 }
4920
4921 auto *New = new (*this, alignof(FunctionNoProtoType))
4922 FunctionNoProtoType(ResultTy, Canonical, Info);
4923 Types.push_back(New);
4924 FunctionNoProtoTypes.InsertNode(New, InsertPos);
4925 return QualType(New, 0);
4926}
4927
4930 CanQualType CanResultType = getCanonicalType(ResultType);
4931
4932 // Canonical result types do not have ARC lifetime qualifiers.
4933 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4934 Qualifiers Qs = CanResultType.getQualifiers();
4935 Qs.removeObjCLifetime();
4937 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4938 }
4939
4940 return CanResultType;
4941}
4942
4944 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4945 if (ESI.Type == EST_None)
4946 return true;
4947 if (!NoexceptInType)
4948 return false;
4949
4950 // C++17 onwards: exception specification is part of the type, as a simple
4951 // boolean "can this function type throw".
4952 if (ESI.Type == EST_BasicNoexcept)
4953 return true;
4954
4955 // A noexcept(expr) specification is (possibly) canonical if expr is
4956 // value-dependent.
4957 if (ESI.Type == EST_DependentNoexcept)
4958 return true;
4959
4960 // A dynamic exception specification is canonical if it only contains pack
4961 // expansions (so we can't tell whether it's non-throwing) and all its
4962 // contained types are canonical.
4963 if (ESI.Type == EST_Dynamic) {
4964 bool AnyPackExpansions = false;
4965 for (QualType ET : ESI.Exceptions) {
4966 if (!ET.isCanonical())
4967 return false;
4968 if (ET->getAs<PackExpansionType>())
4969 AnyPackExpansions = true;
4970 }
4971 return AnyPackExpansions;
4972 }
4973
4974 return false;
4975}
4976
4977QualType ASTContext::getFunctionTypeInternal(
4978 QualType ResultTy, ArrayRef<QualType> ArgArray,
4979 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4980 size_t NumArgs = ArgArray.size();
4981
4982 // Unique functions, to guarantee there is only one function of a particular
4983 // structure.
4984 llvm::FoldingSetNodeID ID;
4985 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4986 *this, true);
4987
4988 QualType Canonical;
4989 bool Unique = false;
4990
4991 void *InsertPos = nullptr;
4992 if (FunctionProtoType *FPT =
4993 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4994 QualType Existing = QualType(FPT, 0);
4995
4996 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4997 // it so long as our exception specification doesn't contain a dependent
4998 // noexcept expression, or we're just looking for a canonical type.
4999 // Otherwise, we're going to need to create a type
5000 // sugar node to hold the concrete expression.
5001 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5002 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5003 return Existing;
5004
5005 // We need a new type sugar node for this one, to hold the new noexcept
5006 // expression. We do no canonicalization here, but that's OK since we don't
5007 // expect to see the same noexcept expression much more than once.
5008 Canonical = getCanonicalType(Existing);
5009 Unique = true;
5010 }
5011
5012 bool NoexceptInType = getLangOpts().CPlusPlus17;
5013 bool IsCanonicalExceptionSpec =
5015
5016 // Determine whether the type being created is already canonical or not.
5017 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5018 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5019 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5020 if (!ArgArray[i].isCanonicalAsParam())
5021 isCanonical = false;
5022
5023 if (OnlyWantCanonical)
5024 assert(isCanonical &&
5025 "given non-canonical parameters constructing canonical type");
5026
5027 // If this type isn't canonical, get the canonical version of it if we don't
5028 // already have it. The exception spec is only partially part of the
5029 // canonical type, and only in C++17 onwards.
5030 if (!isCanonical && Canonical.isNull()) {
5031 SmallVector<QualType, 16> CanonicalArgs;
5032 CanonicalArgs.reserve(NumArgs);
5033 for (unsigned i = 0; i != NumArgs; ++i)
5034 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5035
5036 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5037 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5038 CanonicalEPI.HasTrailingReturn = false;
5039
5040 if (IsCanonicalExceptionSpec) {
5041 // Exception spec is already OK.
5042 } else if (NoexceptInType) {
5043 switch (EPI.ExceptionSpec.Type) {
5045 // We don't know yet. It shouldn't matter what we pick here; no-one
5046 // should ever look at this.
5047 [[fallthrough]];
5048 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5049 CanonicalEPI.ExceptionSpec.Type = EST_None;
5050 break;
5051
5052 // A dynamic exception specification is almost always "not noexcept",
5053 // with the exception that a pack expansion might expand to no types.
5054 case EST_Dynamic: {
5055 bool AnyPacks = false;
5056 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5057 if (ET->getAs<PackExpansionType>())
5058 AnyPacks = true;
5059 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5060 }
5061 if (!AnyPacks)
5062 CanonicalEPI.ExceptionSpec.Type = EST_None;
5063 else {
5064 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5065 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5066 }
5067 break;
5068 }
5069
5070 case EST_DynamicNone:
5071 case EST_BasicNoexcept:
5072 case EST_NoexceptTrue:
5073 case EST_NoThrow:
5074 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5075 break;
5076
5078 llvm_unreachable("dependent noexcept is already canonical");
5079 }
5080 } else {
5081 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5082 }
5083
5084 // Adjust the canonical function result type.
5085 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5086 Canonical =
5087 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5088
5089 // Get the new insert position for the node we care about.
5090 FunctionProtoType *NewIP =
5091 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5092 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5093 }
5094
5095 // Compute the needed size to hold this FunctionProtoType and the
5096 // various trailing objects.
5097 auto ESH = FunctionProtoType::getExceptionSpecSize(
5098 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5099 size_t Size = FunctionProtoType::totalSizeToAlloc<
5100 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5101 FunctionType::FunctionTypeExtraAttributeInfo,
5102 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5103 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5104 FunctionEffect, EffectConditionExpr>(
5107 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5108 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5109 EPI.ExtParameterInfos ? NumArgs : 0,
5111 EPI.FunctionEffects.conditions().size());
5112
5113 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5114 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5115 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5116 Types.push_back(FTP);
5117 if (!Unique)
5118 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5119 if (!EPI.FunctionEffects.empty())
5120 AnyFunctionEffects = true;
5121 return QualType(FTP, 0);
5122}
5123
5124QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5125 llvm::FoldingSetNodeID ID;
5126 PipeType::Profile(ID, T, ReadOnly);
5127
5128 void *InsertPos = nullptr;
5129 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5130 return QualType(PT, 0);
5131
5132 // If the pipe element type isn't canonical, this won't be a canonical type
5133 // either, so fill in the canonical type field.
5134 QualType Canonical;
5135 if (!T.isCanonical()) {
5136 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5137
5138 // Get the new insert position for the node we care about.
5139 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5140 assert(!NewIP && "Shouldn't be in the map!");
5141 (void)NewIP;
5142 }
5143 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5144 Types.push_back(New);
5145 PipeTypes.InsertNode(New, InsertPos);
5146 return QualType(New, 0);
5147}
5148
5150 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5151 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5152 : Ty;
5153}
5154
5156 return getPipeType(T, true);
5157}
5158
5160 return getPipeType(T, false);
5161}
5162
5163QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5164 llvm::FoldingSetNodeID ID;
5165 BitIntType::Profile(ID, IsUnsigned, NumBits);
5166
5167 void *InsertPos = nullptr;
5168 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5169 return QualType(EIT, 0);
5170
5171 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5172 BitIntTypes.InsertNode(New, InsertPos);
5173 Types.push_back(New);
5174 return QualType(New, 0);
5175}
5176
5178 Expr *NumBitsExpr) const {
5179 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5180 llvm::FoldingSetNodeID ID;
5181 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5182
5183 void *InsertPos = nullptr;
5184 if (DependentBitIntType *Existing =
5185 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5186 return QualType(Existing, 0);
5187
5188 auto *New = new (*this, alignof(DependentBitIntType))
5189 DependentBitIntType(IsUnsigned, NumBitsExpr);
5190 DependentBitIntTypes.InsertNode(New, InsertPos);
5191
5192 Types.push_back(New);
5193 return QualType(New, 0);
5194}
5195
5198 using Kind = PredefinedSugarType::Kind;
5199
5200 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5201 Target != nullptr)
5202 return QualType(Target, 0);
5203
5204 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5205 switch (KDI) {
5206 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5207 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5208 // are part of the core language and are widely used. Using
5209 // PredefinedSugarType makes these types as named sugar types rather than
5210 // standard integer types, enabling better hints and diagnostics.
5211 case Kind::SizeT:
5212 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5213 case Kind::SignedSizeT:
5214 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5215 case Kind::PtrdiffT:
5216 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5217 }
5218 llvm_unreachable("unexpected kind");
5219 };
5220 auto *New = new (*this, alignof(PredefinedSugarType))
5221 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5222 getCanonicalType(*this, static_cast<Kind>(KD)));
5223 Types.push_back(New);
5224 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5225 return QualType(New, 0);
5226}
5227
5229 NestedNameSpecifier Qualifier,
5230 const TypeDecl *Decl) const {
5231 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5232 return getTagType(Keyword, Qualifier, Tag,
5233 /*OwnsTag=*/false);
5234 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5235 return getTypedefType(Keyword, Qualifier, Typedef);
5236 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5237 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5238
5240 assert(!Qualifier);
5241 return QualType(Decl->TypeForDecl, 0);
5242}
5243
5245 if (auto *Tag = dyn_cast<TagDecl>(TD))
5246 return getCanonicalTagType(Tag);
5247 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5248 return getCanonicalType(TN->getUnderlyingType());
5249 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5251 assert(TD->TypeForDecl);
5252 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5253}
5254
5256 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5257 return getCanonicalTagType(TD);
5258 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5259 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5261 /*Qualifier=*/std::nullopt, TD);
5262 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5263 return getCanonicalUnresolvedUsingType(Using);
5264
5265 assert(Decl->TypeForDecl);
5266 return QualType(Decl->TypeForDecl, 0);
5267}
5268
5269/// getTypedefType - Return the unique reference to the type for the
5270/// specified typedef name decl.
5273 NestedNameSpecifier Qualifier,
5274 const TypedefNameDecl *Decl, QualType UnderlyingType,
5275 std::optional<bool> TypeMatchesDeclOrNone) const {
5276 if (!TypeMatchesDeclOrNone) {
5277 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5278 assert(!DeclUnderlyingType.isNull());
5279 if (UnderlyingType.isNull())
5280 UnderlyingType = DeclUnderlyingType;
5281 else
5282 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5283 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5284 } else {
5285 // FIXME: This is a workaround for a serialization cycle: assume the decl
5286 // underlying type is not available; don't touch it.
5287 assert(!UnderlyingType.isNull());
5288 }
5289
5290 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5291 *TypeMatchesDeclOrNone) {
5292 if (Decl->TypeForDecl)
5293 return QualType(Decl->TypeForDecl, 0);
5294
5295 auto *NewType = new (*this, alignof(TypedefType))
5296 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5297 !*TypeMatchesDeclOrNone);
5298
5299 Types.push_back(NewType);
5300 Decl->TypeForDecl = NewType;
5301 return QualType(NewType, 0);
5302 }
5303
5304 llvm::FoldingSetNodeID ID;
5305 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5306 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5307
5308 void *InsertPos = nullptr;
5309 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5310 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5311 return QualType(Placeholder->getType(), 0);
5312
5313 void *Mem =
5314 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5316 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5317 alignof(TypedefType));
5318 auto *NewType =
5319 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5320 UnderlyingType, !*TypeMatchesDeclOrNone);
5321 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5323 TypedefTypes.InsertNode(Placeholder, InsertPos);
5324 Types.push_back(NewType);
5325 return QualType(NewType, 0);
5326}
5327
5329 NestedNameSpecifier Qualifier,
5330 const UsingShadowDecl *D,
5331 QualType UnderlyingType) const {
5332 // FIXME: This is expensive to compute every time!
5333 if (UnderlyingType.isNull()) {
5334 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5335 UnderlyingType =
5338 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5339 }
5340
5341 llvm::FoldingSetNodeID ID;
5342 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5343
5344 void *InsertPos = nullptr;
5345 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5346 return QualType(T, 0);
5347
5348 assert(!UnderlyingType.hasLocalQualifiers());
5349
5350 assert(
5352 UnderlyingType));
5353
5354 void *Mem =
5355 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5356 alignof(UsingType));
5357 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5358 Types.push_back(T);
5359 UsingTypes.InsertNode(T, InsertPos);
5360 return QualType(T, 0);
5361}
5362
5363TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5364 NestedNameSpecifier Qualifier,
5365 const TagDecl *TD, bool OwnsTag,
5366 bool IsInjected,
5367 const Type *CanonicalType,
5368 bool WithFoldingSetNode) const {
5369 auto [TC, Size] = [&] {
5370 switch (TD->getDeclKind()) {
5371 case Decl::Enum:
5372 static_assert(alignof(EnumType) == alignof(TagType));
5373 return std::make_tuple(Type::Enum, sizeof(EnumType));
5374 case Decl::ClassTemplatePartialSpecialization:
5375 case Decl::ClassTemplateSpecialization:
5376 case Decl::CXXRecord:
5377 static_assert(alignof(RecordType) == alignof(TagType));
5378 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5379 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5380 return std::make_tuple(Type::InjectedClassName,
5381 sizeof(InjectedClassNameType));
5382 [[fallthrough]];
5383 case Decl::Record:
5384 return std::make_tuple(Type::Record, sizeof(RecordType));
5385 default:
5386 llvm_unreachable("unexpected decl kind");
5387 }
5388 }();
5389
5390 if (Qualifier) {
5391 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5392 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5393 sizeof(NestedNameSpecifier);
5394 }
5395 void *Mem;
5396 if (WithFoldingSetNode) {
5397 // FIXME: It would be more profitable to tail allocate the folding set node
5398 // from the type, instead of the other way around, due to the greater
5399 // alignment requirements of the type. But this makes it harder to deal with
5400 // the different type node sizes. This would require either uniquing from
5401 // different folding sets, or having the folding setaccept a
5402 // contextual parameter which is not fixed at construction.
5403 Mem = Allocate(
5404 sizeof(TagTypeFoldingSetPlaceholder) +
5405 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5406 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5407 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5408 Mem = T->getTagType();
5409 } else {
5410 Mem = Allocate(Size, alignof(TagType));
5411 }
5412
5413 auto *T = [&, TC = TC]() -> TagType * {
5414 switch (TC) {
5415 case Type::Enum: {
5416 assert(isa<EnumDecl>(TD));
5417 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5418 IsInjected, CanonicalType);
5419 assert(reinterpret_cast<void *>(T) ==
5420 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5421 "TagType must be the first base of EnumType");
5422 return T;
5423 }
5424 case Type::Record: {
5425 assert(isa<RecordDecl>(TD));
5426 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5427 IsInjected, CanonicalType);
5428 assert(reinterpret_cast<void *>(T) ==
5429 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5430 "TagType must be the first base of RecordType");
5431 return T;
5432 }
5433 case Type::InjectedClassName: {
5434 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5435 IsInjected, CanonicalType);
5436 assert(reinterpret_cast<void *>(T) ==
5437 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5438 "TagType must be the first base of InjectedClassNameType");
5439 return T;
5440 }
5441 default:
5442 llvm_unreachable("unexpected type class");
5443 }
5444 }();
5445 assert(T->getKeyword() == Keyword);
5446 assert(T->getQualifier() == Qualifier);
5447 assert(T->getOriginalDecl() == TD);
5448 assert(T->isInjected() == IsInjected);
5449 assert(T->isTagOwned() == OwnsTag);
5450 assert((T->isCanonicalUnqualified()
5451 ? QualType()
5452 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5453 Types.push_back(T);
5454 return T;
5455}
5456
5457static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5458 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5459 RD && RD->isInjectedClassName())
5460 return cast<TagDecl>(RD->getDeclContext());
5461 return TD;
5462}
5463
5466 if (TD->TypeForDecl)
5467 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5468
5469 const Type *CanonicalType = getTagTypeInternal(
5471 /*Qualifier=*/std::nullopt, TD,
5472 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5473 /*WithFoldingSetNode=*/false);
5474 TD->TypeForDecl = CanonicalType;
5475 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5476}
5477
5479 NestedNameSpecifier Qualifier,
5480 const TagDecl *TD, bool OwnsTag) const {
5481
5482 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5483 bool IsInjected = TD != NonInjectedTD;
5484
5485 ElaboratedTypeKeyword PreferredKeyword =
5488 NonInjectedTD->getTagKind());
5489
5490 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5491 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5492 return QualType(T, 0);
5493
5494 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5495 const Type *T =
5496 getTagTypeInternal(Keyword,
5497 /*Qualifier=*/std::nullopt, NonInjectedTD,
5498 /*OwnsTag=*/false, IsInjected, CanonicalType,
5499 /*WithFoldingSetNode=*/false);
5500 TD->TypeForDecl = T;
5501 return QualType(T, 0);
5502 }
5503
5504 llvm::FoldingSetNodeID ID;
5505 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5506 OwnsTag, IsInjected);
5507
5508 void *InsertPos = nullptr;
5509 if (TagTypeFoldingSetPlaceholder *T =
5510 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5511 return QualType(T->getTagType(), 0);
5512
5513 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5514 TagType *T =
5515 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5516 CanonicalType, /*WithFoldingSetNode=*/true);
5517 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5518 return QualType(T, 0);
5519}
5520
5521bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5522 unsigned NumPositiveBits,
5523 QualType &BestType,
5524 QualType &BestPromotionType) {
5525 unsigned IntWidth = Target->getIntWidth();
5526 unsigned CharWidth = Target->getCharWidth();
5527 unsigned ShortWidth = Target->getShortWidth();
5528 bool EnumTooLarge = false;
5529 unsigned BestWidth;
5530 if (NumNegativeBits) {
5531 // If there is a negative value, figure out the smallest integer type (of
5532 // int/long/longlong) that fits.
5533 // If it's packed, check also if it fits a char or a short.
5534 if (IsPacked && NumNegativeBits <= CharWidth &&
5535 NumPositiveBits < CharWidth) {
5536 BestType = SignedCharTy;
5537 BestWidth = CharWidth;
5538 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5539 NumPositiveBits < ShortWidth) {
5540 BestType = ShortTy;
5541 BestWidth = ShortWidth;
5542 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5543 BestType = IntTy;
5544 BestWidth = IntWidth;
5545 } else {
5546 BestWidth = Target->getLongWidth();
5547
5548 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5549 BestType = LongTy;
5550 } else {
5551 BestWidth = Target->getLongLongWidth();
5552
5553 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5554 EnumTooLarge = true;
5555 BestType = LongLongTy;
5556 }
5557 }
5558 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5559 } else {
5560 // If there is no negative value, figure out the smallest type that fits
5561 // all of the enumerator values.
5562 // If it's packed, check also if it fits a char or a short.
5563 if (IsPacked && NumPositiveBits <= CharWidth) {
5564 BestType = UnsignedCharTy;
5565 BestPromotionType = IntTy;
5566 BestWidth = CharWidth;
5567 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5568 BestType = UnsignedShortTy;
5569 BestPromotionType = IntTy;
5570 BestWidth = ShortWidth;
5571 } else if (NumPositiveBits <= IntWidth) {
5572 BestType = UnsignedIntTy;
5573 BestWidth = IntWidth;
5574 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5576 : IntTy;
5577 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5578 BestType = UnsignedLongTy;
5579 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5581 : LongTy;
5582 } else {
5583 BestWidth = Target->getLongLongWidth();
5584 if (NumPositiveBits > BestWidth) {
5585 // This can happen with bit-precise integer types, but those are not
5586 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5587 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5588 // a 128-bit integer, we should consider doing the same.
5589 EnumTooLarge = true;
5590 }
5591 BestType = UnsignedLongLongTy;
5592 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5594 : LongLongTy;
5595 }
5596 }
5597 return EnumTooLarge;
5598}
5599
5601 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5602 "Integral type required!");
5603 unsigned BitWidth = getIntWidth(T);
5604
5605 if (Value.isUnsigned() || Value.isNonNegative()) {
5606 if (T->isSignedIntegerOrEnumerationType())
5607 --BitWidth;
5608 return Value.getActiveBits() <= BitWidth;
5609 }
5610 return Value.getSignificantBits() <= BitWidth;
5611}
5612
5613UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5615 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5616 const Type *CanonicalType) const {
5617 void *Mem = Allocate(
5618 UnresolvedUsingType::totalSizeToAlloc<
5620 !!InsertPos, !!Qualifier),
5621 alignof(UnresolvedUsingType));
5622 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5623 if (InsertPos) {
5624 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5626 TypedefTypes.InsertNode(Placeholder, InsertPos);
5627 }
5628 Types.push_back(T);
5629 return T;
5630}
5631
5633 const UnresolvedUsingTypenameDecl *D) const {
5634 D = D->getCanonicalDecl();
5635 if (D->TypeForDecl)
5636 return D->TypeForDecl->getCanonicalTypeUnqualified();
5637
5638 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5640 /*Qualifier=*/std::nullopt, D,
5641 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5642 D->TypeForDecl = CanonicalType;
5643 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5644}
5645
5648 NestedNameSpecifier Qualifier,
5649 const UnresolvedUsingTypenameDecl *D) const {
5650 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5651 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5652 return QualType(T, 0);
5653
5654 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5655 const Type *T =
5656 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5657 /*Qualifier=*/std::nullopt, D,
5658 /*InsertPos=*/nullptr, CanonicalType);
5659 D->TypeForDecl = T;
5660 return QualType(T, 0);
5661 }
5662
5663 llvm::FoldingSetNodeID ID;
5664 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5665
5666 void *InsertPos = nullptr;
5668 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5669 return QualType(Placeholder->getType(), 0);
5670 assert(InsertPos);
5671
5672 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5673 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5674 InsertPos, CanonicalType);
5675 return QualType(T, 0);
5676}
5677
5679 QualType modifiedType,
5680 QualType equivalentType,
5681 const Attr *attr) const {
5682 llvm::FoldingSetNodeID id;
5683 AttributedType::Profile(id, attrKind, modifiedType, equivalentType, attr);
5684
5685 void *insertPos = nullptr;
5686 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5687 if (type) return QualType(type, 0);
5688
5689 assert(!attr || attr->getKind() == attrKind);
5690
5691 QualType canon = getCanonicalType(equivalentType);
5692 type = new (*this, alignof(AttributedType))
5693 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5694
5695 Types.push_back(type);
5696 AttributedTypes.InsertNode(type, insertPos);
5697
5698 return QualType(type, 0);
5699}
5700
5702 QualType equivalentType) const {
5703 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5704}
5705
5707 QualType modifiedType,
5708 QualType equivalentType) {
5709 switch (nullability) {
5711 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5712
5714 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5715
5717 return getAttributedType(attr::TypeNullableResult, modifiedType,
5718 equivalentType);
5719
5721 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5722 equivalentType);
5723 }
5724
5725 llvm_unreachable("Unknown nullability kind");
5726}
5727
5728QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5729 QualType Wrapped) const {
5730 llvm::FoldingSetNodeID ID;
5731 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5732
5733 void *InsertPos = nullptr;
5734 BTFTagAttributedType *Ty =
5735 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5736 if (Ty)
5737 return QualType(Ty, 0);
5738
5739 QualType Canon = getCanonicalType(Wrapped);
5740 Ty = new (*this, alignof(BTFTagAttributedType))
5741 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5742
5743 Types.push_back(Ty);
5744 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5745
5746 return QualType(Ty, 0);
5747}
5748
5750 QualType Wrapped, QualType Contained,
5751 const HLSLAttributedResourceType::Attributes &Attrs) {
5752
5753 llvm::FoldingSetNodeID ID;
5754 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5755
5756 void *InsertPos = nullptr;
5757 HLSLAttributedResourceType *Ty =
5758 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5759 if (Ty)
5760 return QualType(Ty, 0);
5761
5762 Ty = new (*this, alignof(HLSLAttributedResourceType))
5763 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5764
5765 Types.push_back(Ty);
5766 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5767
5768 return QualType(Ty, 0);
5769}
5770
5771QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5772 uint32_t Alignment,
5773 ArrayRef<SpirvOperand> Operands) {
5774 llvm::FoldingSetNodeID ID;
5775 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5776
5777 void *InsertPos = nullptr;
5778 HLSLInlineSpirvType *Ty =
5779 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5780 if (Ty)
5781 return QualType(Ty, 0);
5782
5783 void *Mem = Allocate(
5784 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5785 alignof(HLSLInlineSpirvType));
5786
5787 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5788
5789 Types.push_back(Ty);
5790 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5791
5792 return QualType(Ty, 0);
5793}
5794
5795/// Retrieve a substitution-result type.
5797 Decl *AssociatedDecl,
5798 unsigned Index,
5799 UnsignedOrNone PackIndex,
5800 bool Final) const {
5801 llvm::FoldingSetNodeID ID;
5802 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5803 PackIndex, Final);
5804 void *InsertPos = nullptr;
5805 SubstTemplateTypeParmType *SubstParm =
5806 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5807
5808 if (!SubstParm) {
5809 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5810 !Replacement.isCanonical()),
5811 alignof(SubstTemplateTypeParmType));
5812 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5813 Index, PackIndex, Final);
5814 Types.push_back(SubstParm);
5815 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5816 }
5817
5818 return QualType(SubstParm, 0);
5819}
5820
5823 unsigned Index, bool Final,
5824 const TemplateArgument &ArgPack) {
5825#ifndef NDEBUG
5826 for (const auto &P : ArgPack.pack_elements())
5827 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5828#endif
5829
5830 llvm::FoldingSetNodeID ID;
5831 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5832 ArgPack);
5833 void *InsertPos = nullptr;
5834 if (SubstTemplateTypeParmPackType *SubstParm =
5835 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5836 return QualType(SubstParm, 0);
5837
5838 QualType Canon;
5839 {
5840 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5841 if (!AssociatedDecl->isCanonicalDecl() ||
5842 !CanonArgPack.structurallyEquals(ArgPack)) {
5844 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5845 [[maybe_unused]] const auto *Nothing =
5846 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5847 assert(!Nothing);
5848 }
5849 }
5850
5851 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5852 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5853 ArgPack);
5854 Types.push_back(SubstParm);
5855 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
5856 return QualType(SubstParm, 0);
5857}
5858
5861 assert(llvm::all_of(ArgPack.pack_elements(),
5862 [](const auto &P) {
5863 return P.getKind() == TemplateArgument::Type;
5864 }) &&
5865 "Pack contains a non-type");
5866
5867 llvm::FoldingSetNodeID ID;
5868 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5869
5870 void *InsertPos = nullptr;
5871 if (auto *T =
5872 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
5873 return QualType(T, 0);
5874
5875 QualType Canon;
5876 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5877 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5878 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5879 // Refresh InsertPos, in case the recursive call above caused rehashing,
5880 // which would invalidate the bucket pointer.
5881 [[maybe_unused]] const auto *Nothing =
5882 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
5883 assert(!Nothing);
5884 }
5885
5886 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5887 SubstBuiltinTemplatePackType(Canon, ArgPack);
5888 Types.push_back(PackType);
5889 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
5890 return QualType(PackType, 0);
5891}
5892
5893/// Retrieve the template type parameter type for a template
5894/// parameter or parameter pack with the given depth, index, and (optionally)
5895/// name.
5896QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
5897 bool ParameterPack,
5898 TemplateTypeParmDecl *TTPDecl) const {
5899 llvm::FoldingSetNodeID ID;
5900 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
5901 void *InsertPos = nullptr;
5902 TemplateTypeParmType *TypeParm
5903 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5904
5905 if (TypeParm)
5906 return QualType(TypeParm, 0);
5907
5908 if (TTPDecl) {
5909 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5910 TypeParm = new (*this, alignof(TemplateTypeParmType))
5911 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
5912
5913 TemplateTypeParmType *TypeCheck
5914 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5915 assert(!TypeCheck && "Template type parameter canonical type broken");
5916 (void)TypeCheck;
5917 } else
5918 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
5919 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
5920
5921 Types.push_back(TypeParm);
5922 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
5923
5924 return QualType(TypeParm, 0);
5925}
5926
5929 switch (Keyword) {
5930 // These are just themselves.
5936 return Keyword;
5937
5938 // These are equivalent.
5941
5942 // These are functionally equivalent, so relying on their equivalence is
5943 // IFNDR. By making them equivalent, we disallow overloading, which at least
5944 // can produce a diagnostic.
5947 }
5948 llvm_unreachable("unexpected keyword kind");
5949}
5950
5952 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
5953 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
5954 TemplateName Name, SourceLocation NameLoc,
5955 const TemplateArgumentListInfo &SpecifiedArgs,
5956 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5958 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
5959
5962 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
5963 SpecifiedArgs);
5964 return DI;
5965}
5966
5969 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
5970 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
5971 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
5972 SpecifiedArgVec.reserve(SpecifiedArgs.size());
5973 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
5974 SpecifiedArgVec.push_back(Arg.getArgument());
5975
5976 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
5977 CanonicalArgs, Underlying);
5978}
5979
5980[[maybe_unused]] static bool
5982 for (const TemplateArgument &Arg : Args)
5983 if (Arg.isPackExpansion())
5984 return true;
5985 return false;
5986}
5987
5990 ArrayRef<TemplateArgument> Args) const {
5991 assert(Template ==
5992 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
5994 Template.getAsDependentTemplateName()));
5995#ifndef NDEBUG
5996 for (const auto &Arg : Args)
5997 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
5998#endif
5999
6000 llvm::FoldingSetNodeID ID;
6001 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6002 *this);
6003 void *InsertPos = nullptr;
6004 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6005 return QualType(T, 0);
6006
6007 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6008 sizeof(TemplateArgument) * Args.size(),
6009 alignof(TemplateSpecializationType));
6010 auto *Spec =
6011 new (Mem) TemplateSpecializationType(Keyword, Template,
6012 /*IsAlias=*/false, Args, QualType());
6013 assert(Spec->isDependentType() &&
6014 "canonical template specialization must be dependent");
6015 Types.push_back(Spec);
6016 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6017 return QualType(Spec, 0);
6018}
6019
6022 ArrayRef<TemplateArgument> SpecifiedArgs,
6023 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6024 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6025 bool IsTypeAlias = TD && TD->isTypeAlias();
6026 if (Underlying.isNull()) {
6027 TemplateName CanonTemplate =
6028 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6029 ElaboratedTypeKeyword CanonKeyword =
6030 CanonTemplate.getAsDependentTemplateName()
6033 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6035 if (CanonicalArgs.empty()) {
6036 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6037 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6038 CanonicalArgs = CanonArgsVec;
6039 } else {
6040 NonCanonical |= !llvm::equal(
6041 SpecifiedArgs, CanonicalArgs,
6042 [](const TemplateArgument &A, const TemplateArgument &B) {
6043 return A.structurallyEquals(B);
6044 });
6045 }
6046
6047 // We can get here with an alias template when the specialization
6048 // contains a pack expansion that does not match up with a parameter
6049 // pack, or a builtin template which cannot be resolved due to dependency.
6050 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6051 hasAnyPackExpansions(CanonicalArgs)) &&
6052 "Caller must compute aliased type");
6053 IsTypeAlias = false;
6054
6056 CanonKeyword, CanonTemplate, CanonicalArgs);
6057 if (!NonCanonical)
6058 return Underlying;
6059 }
6060 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6061 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6062 (IsTypeAlias ? sizeof(QualType) : 0),
6063 alignof(TemplateSpecializationType));
6064 auto *Spec = new (Mem) TemplateSpecializationType(
6065 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6066 Types.push_back(Spec);
6067 return QualType(Spec, 0);
6068}
6069
6072 llvm::FoldingSetNodeID ID;
6073 ParenType::Profile(ID, InnerType);
6074
6075 void *InsertPos = nullptr;
6076 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6077 if (T)
6078 return QualType(T, 0);
6079
6080 QualType Canon = InnerType;
6081 if (!Canon.isCanonical()) {
6082 Canon = getCanonicalType(InnerType);
6083 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6084 assert(!CheckT && "Paren canonical type broken");
6085 (void)CheckT;
6086 }
6087
6088 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6089 Types.push_back(T);
6090 ParenTypes.InsertNode(T, InsertPos);
6091 return QualType(T, 0);
6092}
6093
6096 const IdentifierInfo *MacroII) const {
6097 QualType Canon = UnderlyingTy;
6098 if (!Canon.isCanonical())
6099 Canon = getCanonicalType(UnderlyingTy);
6100
6101 auto *newType = new (*this, alignof(MacroQualifiedType))
6102 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6103 Types.push_back(newType);
6104 return QualType(newType, 0);
6105}
6106
6109 const IdentifierInfo *Name) const {
6110 llvm::FoldingSetNodeID ID;
6111 DependentNameType::Profile(ID, Keyword, NNS, Name);
6112
6113 void *InsertPos = nullptr;
6114 if (DependentNameType *T =
6115 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6116 return QualType(T, 0);
6117
6118 ElaboratedTypeKeyword CanonKeyword =
6120 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6121
6122 QualType Canon;
6123 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6124 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6125 [[maybe_unused]] DependentNameType *T =
6126 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6127 assert(!T && "broken canonicalization");
6128 assert(Canon.isCanonical());
6129 }
6130
6131 DependentNameType *T = new (*this, alignof(DependentNameType))
6132 DependentNameType(Keyword, NNS, Name, Canon);
6133 Types.push_back(T);
6134 DependentNameTypes.InsertNode(T, InsertPos);
6135 return QualType(T, 0);
6136}
6137
6139 TemplateArgument Arg;
6140 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6142 if (TTP->isParameterPack())
6143 ArgType = getPackExpansionType(ArgType, std::nullopt);
6144
6146 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6147 QualType T =
6148 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6149 // For class NTTPs, ensure we include the 'const' so the type matches that
6150 // of a real template argument.
6151 // FIXME: It would be more faithful to model this as something like an
6152 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6154 if (T->isRecordType()) {
6155 // C++ [temp.param]p8: An id-expression naming a non-type
6156 // template-parameter of class type T denotes a static storage duration
6157 // object of type const T.
6158 T.addConst();
6159 VK = VK_LValue;
6160 } else {
6161 VK = Expr::getValueKindForType(NTTP->getType());
6162 }
6163 Expr *E = new (*this)
6164 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6165 T, VK, NTTP->getLocation());
6166
6167 if (NTTP->isParameterPack())
6168 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6169 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6170 } else {
6171 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6173 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6174 TemplateName(TTP));
6175 if (TTP->isParameterPack())
6176 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6177 else
6178 Arg = TemplateArgument(Name);
6179 }
6180
6181 if (Param->isTemplateParameterPack())
6182 Arg =
6183 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6184
6185 return Arg;
6186}
6187
6189 UnsignedOrNone NumExpansions,
6190 bool ExpectPackInType) const {
6191 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6192 "Pack expansions must expand one or more parameter packs");
6193
6194 llvm::FoldingSetNodeID ID;
6195 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6196
6197 void *InsertPos = nullptr;
6198 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6199 if (T)
6200 return QualType(T, 0);
6201
6202 QualType Canon;
6203 if (!Pattern.isCanonical()) {
6204 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6205 /*ExpectPackInType=*/false);
6206
6207 // Find the insert position again, in case we inserted an element into
6208 // PackExpansionTypes and invalidated our insert position.
6209 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6210 }
6211
6212 T = new (*this, alignof(PackExpansionType))
6213 PackExpansionType(Pattern, Canon, NumExpansions);
6214 Types.push_back(T);
6215 PackExpansionTypes.InsertNode(T, InsertPos);
6216 return QualType(T, 0);
6217}
6218
6219/// CmpProtocolNames - Comparison predicate for sorting protocols
6220/// alphabetically.
6221static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6222 ObjCProtocolDecl *const *RHS) {
6223 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6224}
6225
6227 if (Protocols.empty()) return true;
6228
6229 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6230 return false;
6231
6232 for (unsigned i = 1; i != Protocols.size(); ++i)
6233 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6234 Protocols[i]->getCanonicalDecl() != Protocols[i])
6235 return false;
6236 return true;
6237}
6238
6239static void
6241 // Sort protocols, keyed by name.
6242 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6243
6244 // Canonicalize.
6245 for (ObjCProtocolDecl *&P : Protocols)
6246 P = P->getCanonicalDecl();
6247
6248 // Remove duplicates.
6249 auto ProtocolsEnd = llvm::unique(Protocols);
6250 Protocols.erase(ProtocolsEnd, Protocols.end());
6251}
6252
6254 ObjCProtocolDecl * const *Protocols,
6255 unsigned NumProtocols) const {
6256 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6257 /*isKindOf=*/false);
6258}
6259
6261 QualType baseType,
6262 ArrayRef<QualType> typeArgs,
6264 bool isKindOf) const {
6265 // If the base type is an interface and there aren't any protocols or
6266 // type arguments to add, then the interface type will do just fine.
6267 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6268 isa<ObjCInterfaceType>(baseType))
6269 return baseType;
6270
6271 // Look in the folding set for an existing type.
6272 llvm::FoldingSetNodeID ID;
6273 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6274 void *InsertPos = nullptr;
6275 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6276 return QualType(QT, 0);
6277
6278 // Determine the type arguments to be used for canonicalization,
6279 // which may be explicitly specified here or written on the base
6280 // type.
6281 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6282 if (effectiveTypeArgs.empty()) {
6283 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6284 effectiveTypeArgs = baseObject->getTypeArgs();
6285 }
6286
6287 // Build the canonical type, which has the canonical base type and a
6288 // sorted-and-uniqued list of protocols and the type arguments
6289 // canonicalized.
6290 QualType canonical;
6291 bool typeArgsAreCanonical = llvm::all_of(
6292 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6293 bool protocolsSorted = areSortedAndUniqued(protocols);
6294 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6295 // Determine the canonical type arguments.
6296 ArrayRef<QualType> canonTypeArgs;
6297 SmallVector<QualType, 4> canonTypeArgsVec;
6298 if (!typeArgsAreCanonical) {
6299 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6300 for (auto typeArg : effectiveTypeArgs)
6301 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6302 canonTypeArgs = canonTypeArgsVec;
6303 } else {
6304 canonTypeArgs = effectiveTypeArgs;
6305 }
6306
6307 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6308 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6309 if (!protocolsSorted) {
6310 canonProtocolsVec.append(protocols.begin(), protocols.end());
6311 SortAndUniqueProtocols(canonProtocolsVec);
6312 canonProtocols = canonProtocolsVec;
6313 } else {
6314 canonProtocols = protocols;
6315 }
6316
6317 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6318 canonProtocols, isKindOf);
6319
6320 // Regenerate InsertPos.
6321 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6322 }
6323
6324 unsigned size = sizeof(ObjCObjectTypeImpl);
6325 size += typeArgs.size() * sizeof(QualType);
6326 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6327 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6328 auto *T =
6329 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6330 isKindOf);
6331
6332 Types.push_back(T);
6333 ObjCObjectTypes.InsertNode(T, InsertPos);
6334 return QualType(T, 0);
6335}
6336
6337/// Apply Objective-C protocol qualifiers to the given type.
6338/// If this is for the canonical type of a type parameter, we can apply
6339/// protocol qualifiers on the ObjCObjectPointerType.
6342 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6343 bool allowOnPointerType) const {
6344 hasError = false;
6345
6346 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6347 return getObjCTypeParamType(objT->getDecl(), protocols);
6348 }
6349
6350 // Apply protocol qualifiers to ObjCObjectPointerType.
6351 if (allowOnPointerType) {
6352 if (const auto *objPtr =
6353 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6354 const ObjCObjectType *objT = objPtr->getObjectType();
6355 // Merge protocol lists and construct ObjCObjectType.
6357 protocolsVec.append(objT->qual_begin(),
6358 objT->qual_end());
6359 protocolsVec.append(protocols.begin(), protocols.end());
6360 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6362 objT->getBaseType(),
6363 objT->getTypeArgsAsWritten(),
6364 protocols,
6365 objT->isKindOfTypeAsWritten());
6367 }
6368 }
6369
6370 // Apply protocol qualifiers to ObjCObjectType.
6371 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6372 // FIXME: Check for protocols to which the class type is already
6373 // known to conform.
6374
6375 return getObjCObjectType(objT->getBaseType(),
6376 objT->getTypeArgsAsWritten(),
6377 protocols,
6378 objT->isKindOfTypeAsWritten());
6379 }
6380
6381 // If the canonical type is ObjCObjectType, ...
6382 if (type->isObjCObjectType()) {
6383 // Silently overwrite any existing protocol qualifiers.
6384 // TODO: determine whether that's the right thing to do.
6385
6386 // FIXME: Check for protocols to which the class type is already
6387 // known to conform.
6388 return getObjCObjectType(type, {}, protocols, false);
6389 }
6390
6391 // id<protocol-list>
6392 if (type->isObjCIdType()) {
6393 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6394 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6395 objPtr->isKindOfType());
6397 }
6398
6399 // Class<protocol-list>
6400 if (type->isObjCClassType()) {
6401 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6402 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6403 objPtr->isKindOfType());
6405 }
6406
6407 hasError = true;
6408 return type;
6409}
6410
6413 ArrayRef<ObjCProtocolDecl *> protocols) const {
6414 // Look in the folding set for an existing type.
6415 llvm::FoldingSetNodeID ID;
6416 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6417 void *InsertPos = nullptr;
6418 if (ObjCTypeParamType *TypeParam =
6419 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6420 return QualType(TypeParam, 0);
6421
6422 // We canonicalize to the underlying type.
6423 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6424 if (!protocols.empty()) {
6425 // Apply the protocol qualifers.
6426 bool hasError;
6428 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6429 assert(!hasError && "Error when apply protocol qualifier to bound type");
6430 }
6431
6432 unsigned size = sizeof(ObjCTypeParamType);
6433 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6434 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6435 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6436
6437 Types.push_back(newType);
6438 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6439 return QualType(newType, 0);
6440}
6441
6443 ObjCTypeParamDecl *New) const {
6444 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6445 // Update TypeForDecl after updating TypeSourceInfo.
6446 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6448 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6449 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6450 New->TypeForDecl = UpdatedTy.getTypePtr();
6451}
6452
6453/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6454/// protocol list adopt all protocols in QT's qualified-id protocol
6455/// list.
6457 ObjCInterfaceDecl *IC) {
6458 if (!QT->isObjCQualifiedIdType())
6459 return false;
6460
6461 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6462 // If both the right and left sides have qualifiers.
6463 for (auto *Proto : OPT->quals()) {
6464 if (!IC->ClassImplementsProtocol(Proto, false))
6465 return false;
6466 }
6467 return true;
6468 }
6469 return false;
6470}
6471
6472/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6473/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6474/// of protocols.
6476 ObjCInterfaceDecl *IDecl) {
6477 if (!QT->isObjCQualifiedIdType())
6478 return false;
6479 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6480 if (!OPT)
6481 return false;
6482 if (!IDecl->hasDefinition())
6483 return false;
6485 CollectInheritedProtocols(IDecl, InheritedProtocols);
6486 if (InheritedProtocols.empty())
6487 return false;
6488 // Check that if every protocol in list of id<plist> conforms to a protocol
6489 // of IDecl's, then bridge casting is ok.
6490 bool Conforms = false;
6491 for (auto *Proto : OPT->quals()) {
6492 Conforms = false;
6493 for (auto *PI : InheritedProtocols) {
6494 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6495 Conforms = true;
6496 break;
6497 }
6498 }
6499 if (!Conforms)
6500 break;
6501 }
6502 if (Conforms)
6503 return true;
6504
6505 for (auto *PI : InheritedProtocols) {
6506 // If both the right and left sides have qualifiers.
6507 bool Adopts = false;
6508 for (auto *Proto : OPT->quals()) {
6509 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6510 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6511 break;
6512 }
6513 if (!Adopts)
6514 return false;
6515 }
6516 return true;
6517}
6518
6519/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6520/// the given object type.
6522 llvm::FoldingSetNodeID ID;
6523 ObjCObjectPointerType::Profile(ID, ObjectT);
6524
6525 void *InsertPos = nullptr;
6526 if (ObjCObjectPointerType *QT =
6527 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6528 return QualType(QT, 0);
6529
6530 // Find the canonical object type.
6531 QualType Canonical;
6532 if (!ObjectT.isCanonical()) {
6533 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6534
6535 // Regenerate InsertPos.
6536 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6537 }
6538
6539 // No match.
6540 void *Mem =
6542 auto *QType =
6543 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6544
6545 Types.push_back(QType);
6546 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6547 return QualType(QType, 0);
6548}
6549
6550/// getObjCInterfaceType - Return the unique reference to the type for the
6551/// specified ObjC interface decl. The list of protocols is optional.
6553 ObjCInterfaceDecl *PrevDecl) const {
6554 if (Decl->TypeForDecl)
6555 return QualType(Decl->TypeForDecl, 0);
6556
6557 if (PrevDecl) {
6558 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6559 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6560 return QualType(PrevDecl->TypeForDecl, 0);
6561 }
6562
6563 // Prefer the definition, if there is one.
6564 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6565 Decl = Def;
6566
6567 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6568 auto *T = new (Mem) ObjCInterfaceType(Decl);
6569 Decl->TypeForDecl = T;
6570 Types.push_back(T);
6571 return QualType(T, 0);
6572}
6573
6574/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6575/// TypeOfExprType AST's (since expression's are never shared). For example,
6576/// multiple declarations that refer to "typeof(x)" all contain different
6577/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6578/// on canonical type's (which are always unique).
6580 TypeOfExprType *toe;
6581 if (tofExpr->isTypeDependent()) {
6582 llvm::FoldingSetNodeID ID;
6583 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6584 Kind == TypeOfKind::Unqualified);
6585
6586 void *InsertPos = nullptr;
6588 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6589 if (Canon) {
6590 // We already have a "canonical" version of an identical, dependent
6591 // typeof(expr) type. Use that as our canonical type.
6592 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6593 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6594 } else {
6595 // Build a new, canonical typeof(expr) type.
6596 Canon = new (*this, alignof(DependentTypeOfExprType))
6597 DependentTypeOfExprType(*this, tofExpr, Kind);
6598 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6599 toe = Canon;
6600 }
6601 } else {
6602 QualType Canonical = getCanonicalType(tofExpr->getType());
6603 toe = new (*this, alignof(TypeOfExprType))
6604 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6605 }
6606 Types.push_back(toe);
6607 return QualType(toe, 0);
6608}
6609
6610/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6611/// TypeOfType nodes. The only motivation to unique these nodes would be
6612/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6613/// an issue. This doesn't affect the type checker, since it operates
6614/// on canonical types (which are always unique).
6616 QualType Canonical = getCanonicalType(tofType);
6617 auto *tot = new (*this, alignof(TypeOfType))
6618 TypeOfType(*this, tofType, Canonical, Kind);
6619 Types.push_back(tot);
6620 return QualType(tot, 0);
6621}
6622
6623/// getReferenceQualifiedType - Given an expr, will return the type for
6624/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6625/// and class member access into account.
6627 // C++11 [dcl.type.simple]p4:
6628 // [...]
6629 QualType T = E->getType();
6630 switch (E->getValueKind()) {
6631 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6632 // type of e;
6633 case VK_XValue:
6634 return getRValueReferenceType(T);
6635 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6636 // type of e;
6637 case VK_LValue:
6638 return getLValueReferenceType(T);
6639 // - otherwise, decltype(e) is the type of e.
6640 case VK_PRValue:
6641 return T;
6642 }
6643 llvm_unreachable("Unknown value kind");
6644}
6645
6646/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6647/// nodes. This would never be helpful, since each such type has its own
6648/// expression, and would not give a significant memory saving, since there
6649/// is an Expr tree under each such type.
6651 // C++11 [temp.type]p2:
6652 // If an expression e involves a template parameter, decltype(e) denotes a
6653 // unique dependent type. Two such decltype-specifiers refer to the same
6654 // type only if their expressions are equivalent (14.5.6.1).
6655 QualType CanonType;
6656 if (!E->isInstantiationDependent()) {
6657 CanonType = getCanonicalType(UnderlyingType);
6658 } else if (!UnderlyingType.isNull()) {
6659 CanonType = getDecltypeType(E, QualType());
6660 } else {
6661 llvm::FoldingSetNodeID ID;
6662 DependentDecltypeType::Profile(ID, *this, E);
6663
6664 void *InsertPos = nullptr;
6665 if (DependentDecltypeType *Canon =
6666 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6667 return QualType(Canon, 0);
6668
6669 // Build a new, canonical decltype(expr) type.
6670 auto *DT =
6671 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6672 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6673 Types.push_back(DT);
6674 return QualType(DT, 0);
6675 }
6676 auto *DT = new (*this, alignof(DecltypeType))
6677 DecltypeType(E, UnderlyingType, CanonType);
6678 Types.push_back(DT);
6679 return QualType(DT, 0);
6680}
6681
6683 bool FullySubstituted,
6684 ArrayRef<QualType> Expansions,
6685 UnsignedOrNone Index) const {
6686 QualType Canonical;
6687 if (FullySubstituted && Index) {
6688 Canonical = getCanonicalType(Expansions[*Index]);
6689 } else {
6690 llvm::FoldingSetNodeID ID;
6691 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6692 FullySubstituted, Expansions);
6693 void *InsertPos = nullptr;
6694 PackIndexingType *Canon =
6695 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6696 if (!Canon) {
6697 void *Mem = Allocate(
6698 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6700 Canon =
6701 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6702 IndexExpr, FullySubstituted, Expansions);
6703 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6704 }
6705 Canonical = QualType(Canon, 0);
6706 }
6707
6708 void *Mem =
6709 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6711 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6712 FullySubstituted, Expansions);
6713 Types.push_back(T);
6714 return QualType(T, 0);
6715}
6716
6717/// getUnaryTransformationType - We don't unique these, since the memory
6718/// savings are minimal and these are rare.
6721 UnaryTransformType::UTTKind Kind) const {
6722
6723 llvm::FoldingSetNodeID ID;
6724 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6725
6726 void *InsertPos = nullptr;
6727 if (UnaryTransformType *UT =
6728 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6729 return QualType(UT, 0);
6730
6731 QualType CanonType;
6732 if (!BaseType->isDependentType()) {
6733 CanonType = UnderlyingType.getCanonicalType();
6734 } else {
6735 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6736 UnderlyingType = QualType();
6737 if (QualType CanonBase = BaseType.getCanonicalType();
6738 BaseType != CanonBase) {
6739 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6740 assert(CanonType.isCanonical());
6741
6742 // Find the insertion position again.
6743 [[maybe_unused]] UnaryTransformType *UT =
6744 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6745 assert(!UT && "broken canonicalization");
6746 }
6747 }
6748
6749 auto *UT = new (*this, alignof(UnaryTransformType))
6750 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6751 UnaryTransformTypes.InsertNode(UT, InsertPos);
6752 Types.push_back(UT);
6753 return QualType(UT, 0);
6754}
6755
6756QualType ASTContext::getAutoTypeInternal(
6757 QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
6758 bool IsPack, TemplateDecl *TypeConstraintConcept,
6759 ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
6760 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
6761 !TypeConstraintConcept && !IsDependent)
6762 return getAutoDeductType();
6763
6764 // Look in the folding set for an existing type.
6765 llvm::FoldingSetNodeID ID;
6766 bool IsDeducedDependent =
6767 isa_and_nonnull<TemplateTemplateParmDecl>(TypeConstraintConcept) ||
6768 (!DeducedType.isNull() && DeducedType->isDependentType());
6769 AutoType::Profile(ID, *this, DeducedType, Keyword,
6770 IsDependent || IsDeducedDependent, TypeConstraintConcept,
6771 TypeConstraintArgs);
6772 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6773 return QualType(AT_iter->getSecond(), 0);
6774
6775 QualType Canon;
6776 if (!IsCanon) {
6777 if (!DeducedType.isNull()) {
6778 Canon = DeducedType.getCanonicalType();
6779 } else if (TypeConstraintConcept) {
6780 bool AnyNonCanonArgs = false;
6781 auto *CanonicalConcept =
6782 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6783 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6784 *this, TypeConstraintArgs, AnyNonCanonArgs);
6785 if (CanonicalConcept != TypeConstraintConcept || AnyNonCanonArgs) {
6786 Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
6787 CanonicalConcept, CanonicalConceptArgs,
6788 /*IsCanon=*/true);
6789 }
6790 }
6791 }
6792
6793 void *Mem = Allocate(sizeof(AutoType) +
6794 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6795 alignof(AutoType));
6796 auto *AT = new (Mem) AutoType(
6797 DeducedType, Keyword,
6798 (IsDependent ? TypeDependence::DependentInstantiation
6799 : TypeDependence::None) |
6800 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
6801 Canon, TypeConstraintConcept, TypeConstraintArgs);
6802#ifndef NDEBUG
6803 llvm::FoldingSetNodeID InsertedID;
6804 AT->Profile(InsertedID, *this);
6805 assert(InsertedID == ID && "ID does not match");
6806#endif
6807 Types.push_back(AT);
6808 AutoTypes.try_emplace(ID, AT);
6809 return QualType(AT, 0);
6810}
6811
6812/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6813/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6814/// canonical deduced-but-dependent 'auto' type.
6815QualType
6817 bool IsDependent, bool IsPack,
6818 TemplateDecl *TypeConstraintConcept,
6819 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6820 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
6821 assert((!IsDependent || DeducedType.isNull()) &&
6822 "A dependent auto should be undeduced");
6823 return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
6824 TypeConstraintConcept, TypeConstraintArgs);
6825}
6826
6828 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6829
6830 // Remove a type-constraint from a top-level auto or decltype(auto).
6831 if (auto *AT = CanonT->getAs<AutoType>()) {
6832 if (!AT->isConstrained())
6833 return T;
6834 return getQualifiedType(getAutoType(QualType(), AT->getKeyword(),
6835 AT->isDependentType(),
6836 AT->containsUnexpandedParameterPack()),
6837 T.getQualifiers());
6838 }
6839
6840 // FIXME: We only support constrained auto at the top level in the type of a
6841 // non-type template parameter at the moment. Once we lift that restriction,
6842 // we'll need to recursively build types containing auto here.
6843 assert(!CanonT->getContainedAutoType() ||
6844 !CanonT->getContainedAutoType()->isConstrained());
6845 return T;
6846}
6847
6848QualType ASTContext::getDeducedTemplateSpecializationTypeInternal(
6850 bool IsDependent, QualType Canon) const {
6851 // Look in the folding set for an existing type.
6852 void *InsertPos = nullptr;
6853 llvm::FoldingSetNodeID ID;
6854 DeducedTemplateSpecializationType::Profile(ID, Keyword, Template, DeducedType,
6855 IsDependent);
6856 if (DeducedTemplateSpecializationType *DTST =
6857 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6858 return QualType(DTST, 0);
6859
6860 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6861 DeducedTemplateSpecializationType(Keyword, Template, DeducedType,
6862 IsDependent, Canon);
6863
6864#ifndef NDEBUG
6865 llvm::FoldingSetNodeID TempID;
6866 DTST->Profile(TempID);
6867 assert(ID == TempID && "ID does not match");
6868#endif
6869 Types.push_back(DTST);
6870 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
6871 return QualType(DTST, 0);
6872}
6873
6874/// Return the uniqued reference to the deduced template specialization type
6875/// which has been deduced to the given type, or to the canonical undeduced
6876/// such type, or the canonical deduced-but-dependent such type.
6879 bool IsDependent) const {
6880 // FIXME: This could save an extra hash table lookup if it handled all the
6881 // parameters already being canonical.
6882 // FIXME: Can this be formed from a DependentTemplateName, such that the
6883 // keyword should be part of the canonical type?
6884 QualType Canon =
6885 DeducedType.isNull()
6886 ? getDeducedTemplateSpecializationTypeInternal(
6888 QualType(), IsDependent, QualType())
6889 : DeducedType.getCanonicalType();
6890 return getDeducedTemplateSpecializationTypeInternal(
6891 Keyword, Template, DeducedType, IsDependent, Canon);
6892}
6893
6894/// getAtomicType - Return the uniqued reference to the atomic type for
6895/// the given value type.
6897 // Unique pointers, to guarantee there is only one pointer of a particular
6898 // structure.
6899 llvm::FoldingSetNodeID ID;
6901
6902 void *InsertPos = nullptr;
6903 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
6904 return QualType(AT, 0);
6905
6906 // If the atomic value type isn't canonical, this won't be a canonical type
6907 // either, so fill in the canonical type field.
6908 QualType Canonical;
6909 if (!T.isCanonical()) {
6910 Canonical = getAtomicType(getCanonicalType(T));
6911
6912 // Get the new insert position for the node we care about.
6913 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
6914 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
6915 }
6916 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6917 Types.push_back(New);
6918 AtomicTypes.InsertNode(New, InsertPos);
6919 return QualType(New, 0);
6920}
6921
6922/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6924 if (AutoDeductTy.isNull())
6925 AutoDeductTy = QualType(new (*this, alignof(AutoType))
6926 AutoType(QualType(), AutoTypeKeyword::Auto,
6927 TypeDependence::None, QualType(),
6928 /*concept*/ nullptr, /*args*/ {}),
6929 0);
6930 return AutoDeductTy;
6931}
6932
6933/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6935 if (AutoRRefDeductTy.isNull())
6937 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6938 return AutoRRefDeductTy;
6939}
6940
6941/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6942/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6943/// needs to agree with the definition in <stddef.h>.
6947
6949 return getFromTargetType(Target->getSizeType());
6950}
6951
6952/// Return the unique signed counterpart of the integer type
6953/// corresponding to size_t.
6957
6958/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6959/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
6963
6964/// Return the unique unsigned counterpart of "ptrdiff_t"
6965/// integer type. The standard (C11 7.21.6.1p7) refers to this type
6966/// in the definition of %tu format specifier.
6968 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
6969}
6970
6971/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
6973 return getFromTargetType(Target->getIntMaxType());
6974}
6975
6976/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
6978 return getFromTargetType(Target->getUIntMaxType());
6979}
6980
6981/// getSignedWCharType - Return the type of "signed wchar_t".
6982/// Used when in C++, as a GCC extension.
6984 // FIXME: derive from "Target" ?
6985 return WCharTy;
6986}
6987
6988/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
6989/// Used when in C++, as a GCC extension.
6991 // FIXME: derive from "Target" ?
6992 return UnsignedIntTy;
6993}
6994
6996 return getFromTargetType(Target->getIntPtrType());
6997}
6998
7002
7003/// Return the unique type for "pid_t" defined in
7004/// <sys/types.h>. We need this to compute the correct type for vfork().
7006 return getFromTargetType(Target->getProcessIDType());
7007}
7008
7009//===----------------------------------------------------------------------===//
7010// Type Operators
7011//===----------------------------------------------------------------------===//
7012
7014 // Push qualifiers into arrays, and then discard any remaining
7015 // qualifiers.
7016 T = getCanonicalType(T);
7018 const Type *Ty = T.getTypePtr();
7022 } else if (isa<ArrayType>(Ty)) {
7024 } else if (isa<FunctionType>(Ty)) {
7025 Result = getPointerType(QualType(Ty, 0));
7026 } else {
7027 Result = QualType(Ty, 0);
7028 }
7029
7031}
7032
7034 Qualifiers &quals) const {
7035 SplitQualType splitType = type.getSplitUnqualifiedType();
7036
7037 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7038 // the unqualified desugared type and then drops it on the floor.
7039 // We then have to strip that sugar back off with
7040 // getUnqualifiedDesugaredType(), which is silly.
7041 const auto *AT =
7042 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7043
7044 // If we don't have an array, just use the results in splitType.
7045 if (!AT) {
7046 quals = splitType.Quals;
7047 return QualType(splitType.Ty, 0);
7048 }
7049
7050 // Otherwise, recurse on the array's element type.
7051 QualType elementType = AT->getElementType();
7052 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7053
7054 // If that didn't change the element type, AT has no qualifiers, so we
7055 // can just use the results in splitType.
7056 if (elementType == unqualElementType) {
7057 assert(quals.empty()); // from the recursive call
7058 quals = splitType.Quals;
7059 return QualType(splitType.Ty, 0);
7060 }
7061
7062 // Otherwise, add in the qualifiers from the outermost type, then
7063 // build the type back up.
7064 quals.addConsistentQualifiers(splitType.Quals);
7065
7066 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7067 return getConstantArrayType(unqualElementType, CAT->getSize(),
7068 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7069 }
7070
7071 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7072 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7073 }
7074
7075 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7076 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7077 VAT->getSizeModifier(),
7078 VAT->getIndexTypeCVRQualifiers());
7079 }
7080
7081 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7082 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7083 DSAT->getSizeModifier(), 0);
7084}
7085
7086/// Attempt to unwrap two types that may both be array types with the same bound
7087/// (or both be array types of unknown bound) for the purpose of comparing the
7088/// cv-decomposition of two types per C++ [conv.qual].
7089///
7090/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7091/// C++20 [conv.qual], if permitted by the current language mode.
7093 bool AllowPiMismatch) const {
7094 while (true) {
7095 auto *AT1 = getAsArrayType(T1);
7096 if (!AT1)
7097 return;
7098
7099 auto *AT2 = getAsArrayType(T2);
7100 if (!AT2)
7101 return;
7102
7103 // If we don't have two array types with the same constant bound nor two
7104 // incomplete array types, we've unwrapped everything we can.
7105 // C++20 also permits one type to be a constant array type and the other
7106 // to be an incomplete array type.
7107 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7108 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7109 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7110 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7111 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7113 return;
7114 } else if (isa<IncompleteArrayType>(AT1)) {
7115 if (!(isa<IncompleteArrayType>(AT2) ||
7116 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7118 return;
7119 } else {
7120 return;
7121 }
7122
7123 T1 = AT1->getElementType();
7124 T2 = AT2->getElementType();
7125 }
7126}
7127
7128/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7129///
7130/// If T1 and T2 are both pointer types of the same kind, or both array types
7131/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7132/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7133///
7134/// This function will typically be called in a loop that successively
7135/// "unwraps" pointer and pointer-to-member types to compare them at each
7136/// level.
7137///
7138/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7139/// C++20 [conv.qual], if permitted by the current language mode.
7140///
7141/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7142/// pair of types that can't be unwrapped further.
7144 bool AllowPiMismatch) const {
7145 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7146
7147 const auto *T1PtrType = T1->getAs<PointerType>();
7148 const auto *T2PtrType = T2->getAs<PointerType>();
7149 if (T1PtrType && T2PtrType) {
7150 T1 = T1PtrType->getPointeeType();
7151 T2 = T2PtrType->getPointeeType();
7152 return true;
7153 }
7154
7155 if (const auto *T1MPType = T1->getAs<MemberPointerType>(),
7156 *T2MPType = T2->getAs<MemberPointerType>();
7157 T1MPType && T2MPType) {
7158 if (auto *RD1 = T1MPType->getMostRecentCXXRecordDecl(),
7159 *RD2 = T2MPType->getMostRecentCXXRecordDecl();
7160 RD1 != RD2 && RD1->getCanonicalDecl() != RD2->getCanonicalDecl())
7161 return false;
7162 if (T1MPType->getQualifier().getCanonical() !=
7163 T2MPType->getQualifier().getCanonical())
7164 return false;
7165 T1 = T1MPType->getPointeeType();
7166 T2 = T2MPType->getPointeeType();
7167 return true;
7168 }
7169
7170 if (getLangOpts().ObjC) {
7171 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7172 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7173 if (T1OPType && T2OPType) {
7174 T1 = T1OPType->getPointeeType();
7175 T2 = T2OPType->getPointeeType();
7176 return true;
7177 }
7178 }
7179
7180 // FIXME: Block pointers, too?
7181
7182 return false;
7183}
7184
7186 while (true) {
7187 Qualifiers Quals;
7188 T1 = getUnqualifiedArrayType(T1, Quals);
7189 T2 = getUnqualifiedArrayType(T2, Quals);
7190 if (hasSameType(T1, T2))
7191 return true;
7192 if (!UnwrapSimilarTypes(T1, T2))
7193 return false;
7194 }
7195}
7196
7198 while (true) {
7199 Qualifiers Quals1, Quals2;
7200 T1 = getUnqualifiedArrayType(T1, Quals1);
7201 T2 = getUnqualifiedArrayType(T2, Quals2);
7202
7203 Quals1.removeCVRQualifiers();
7204 Quals2.removeCVRQualifiers();
7205 if (Quals1 != Quals2)
7206 return false;
7207
7208 if (hasSameType(T1, T2))
7209 return true;
7210
7211 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7212 return false;
7213 }
7214}
7215
7218 SourceLocation NameLoc) const {
7219 switch (Name.getKind()) {
7222 // DNInfo work in progress: CHECKME: what about DNLoc?
7224 NameLoc);
7225
7228 // DNInfo work in progress: CHECKME: what about DNLoc?
7229 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7230 }
7231
7234 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7235 }
7236
7240 DeclarationName DName;
7241 if (const IdentifierInfo *II = TN.getIdentifier()) {
7242 DName = DeclarationNames.getIdentifier(II);
7243 return DeclarationNameInfo(DName, NameLoc);
7244 } else {
7245 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7246 // DNInfo work in progress: FIXME: source locations?
7247 DeclarationNameLoc DNLoc =
7249 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7250 }
7251 }
7252
7256 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7257 NameLoc);
7258 }
7259
7264 NameLoc);
7265 }
7268 NameLoc);
7271 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7272 }
7273 }
7274
7275 llvm_unreachable("bad template name kind!");
7276}
7277
7278static const TemplateArgument *
7280 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7281 if (!TP->hasDefaultArgument())
7282 return nullptr;
7283 return &TP->getDefaultArgument().getArgument();
7284 };
7285 switch (P->getKind()) {
7286 case NamedDecl::TemplateTypeParm:
7287 return handleParam(cast<TemplateTypeParmDecl>(P));
7288 case NamedDecl::NonTypeTemplateParm:
7289 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7290 case NamedDecl::TemplateTemplateParm:
7291 return handleParam(cast<TemplateTemplateParmDecl>(P));
7292 default:
7293 llvm_unreachable("Unexpected template parameter kind");
7294 }
7295}
7296
7298 bool IgnoreDeduced) const {
7299 while (std::optional<TemplateName> UnderlyingOrNone =
7300 Name.desugar(IgnoreDeduced))
7301 Name = *UnderlyingOrNone;
7302
7303 switch (Name.getKind()) {
7306 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7308
7309 // The canonical template name is the canonical template declaration.
7310 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7311 }
7312
7315 llvm_unreachable("cannot canonicalize unresolved template");
7316
7319 assert(DTN && "Non-dependent template names must refer to template decls.");
7320 NestedNameSpecifier Qualifier = DTN->getQualifier();
7321 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7322 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7323 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7324 /*HasTemplateKeyword=*/true});
7325 return Name;
7326 }
7327
7331 TemplateArgument canonArgPack =
7334 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7335 subst->getIndex(), subst->getFinal());
7336 }
7338 assert(IgnoreDeduced == false);
7340 DefaultArguments DefArgs = DTS->getDefaultArguments();
7341 TemplateName Underlying = DTS->getUnderlying();
7342
7343 TemplateName CanonUnderlying =
7344 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7345 bool NonCanonical = CanonUnderlying != Underlying;
7346 auto CanonArgs =
7347 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7348
7349 ArrayRef<NamedDecl *> Params =
7350 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7351 assert(CanonArgs.size() <= Params.size());
7352 // A deduced template name which deduces the same default arguments already
7353 // declared in the underlying template is the same template as the
7354 // underlying template. We need need to note any arguments which differ from
7355 // the corresponding declaration. If any argument differs, we must build a
7356 // deduced template name.
7357 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7359 if (!A)
7360 break;
7361 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7362 TemplateArgument &CanonDefArg = CanonArgs[I];
7363 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7364 continue;
7365 // Keep popping from the back any deault arguments which are the same.
7366 if (I == int(CanonArgs.size() - 1))
7367 CanonArgs.pop_back();
7368 NonCanonical = true;
7369 }
7370 return NonCanonical ? getDeducedTemplateName(
7371 CanonUnderlying,
7372 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7373 : Name;
7374 }
7378 llvm_unreachable("always sugar node");
7379 }
7380
7381 llvm_unreachable("bad template name!");
7382}
7383
7385 const TemplateName &Y,
7386 bool IgnoreDeduced) const {
7387 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7388 getCanonicalTemplateName(Y, IgnoreDeduced);
7389}
7390
7392 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7393 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7394 return false;
7396 return false;
7397 return true;
7398}
7399
7400bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7401 if (!XCE != !YCE)
7402 return false;
7403
7404 if (!XCE)
7405 return true;
7406
7407 llvm::FoldingSetNodeID XCEID, YCEID;
7408 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7409 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7410 return XCEID == YCEID;
7411}
7412
7414 const TypeConstraint *YTC) const {
7415 if (!XTC != !YTC)
7416 return false;
7417
7418 if (!XTC)
7419 return true;
7420
7421 auto *NCX = XTC->getNamedConcept();
7422 auto *NCY = YTC->getNamedConcept();
7423 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7424 return false;
7427 return false;
7429 if (XTC->getConceptReference()
7431 ->NumTemplateArgs !=
7433 return false;
7434
7435 // Compare slowly by profiling.
7436 //
7437 // We couldn't compare the profiling result for the template
7438 // args here. Consider the following example in different modules:
7439 //
7440 // template <__integer_like _Tp, C<_Tp> Sentinel>
7441 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7442 // return __t;
7443 // }
7444 //
7445 // When we compare the profiling result for `C<_Tp>` in different
7446 // modules, it will compare the type of `_Tp` in different modules.
7447 // However, the type of `_Tp` in different modules refer to different
7448 // types here naturally. So we couldn't compare the profiling result
7449 // for the template args directly.
7452}
7453
7455 const NamedDecl *Y) const {
7456 if (X->getKind() != Y->getKind())
7457 return false;
7458
7459 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7460 auto *TY = cast<TemplateTypeParmDecl>(Y);
7461 if (TX->isParameterPack() != TY->isParameterPack())
7462 return false;
7463 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7464 return false;
7465 return isSameTypeConstraint(TX->getTypeConstraint(),
7466 TY->getTypeConstraint());
7467 }
7468
7469 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7470 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7471 return TX->isParameterPack() == TY->isParameterPack() &&
7472 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7473 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7474 TY->getPlaceholderTypeConstraint());
7475 }
7476
7478 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7479 return TX->isParameterPack() == TY->isParameterPack() &&
7480 isSameTemplateParameterList(TX->getTemplateParameters(),
7481 TY->getTemplateParameters());
7482}
7483
7485 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7486 if (X->size() != Y->size())
7487 return false;
7488
7489 for (unsigned I = 0, N = X->size(); I != N; ++I)
7490 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7491 return false;
7492
7493 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7494}
7495
7497 const NamedDecl *Y) const {
7498 // If the type parameter isn't the same already, we don't need to check the
7499 // default argument further.
7500 if (!isSameTemplateParameter(X, Y))
7501 return false;
7502
7503 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7504 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7505 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7506 return false;
7507
7508 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7509 TTPY->getDefaultArgument().getArgument().getAsType());
7510 }
7511
7512 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7513 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7514 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7515 return false;
7516
7517 Expr *DefaultArgumentX =
7518 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7519 Expr *DefaultArgumentY =
7520 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7521 llvm::FoldingSetNodeID XID, YID;
7522 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7523 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7524 return XID == YID;
7525 }
7526
7527 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7528 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7529
7530 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7531 return false;
7532
7533 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7534 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7535 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7536}
7537
7539 const NestedNameSpecifier Y) {
7540 if (X == Y)
7541 return true;
7542 if (!X || !Y)
7543 return false;
7544
7545 auto Kind = X.getKind();
7546 if (Kind != Y.getKind())
7547 return false;
7548
7549 // FIXME: For namespaces and types, we're permitted to check that the entity
7550 // is named via the same tokens. We should probably do so.
7551 switch (Kind) {
7553 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7554 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7555 if (!declaresSameEntity(NamespaceX->getNamespace(),
7556 NamespaceY->getNamespace()))
7557 return false;
7558 return isSameQualifier(PrefixX, PrefixY);
7559 }
7561 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7562 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7563 return false;
7564 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7565 }
7569 return true;
7570 }
7571 llvm_unreachable("unhandled qualifier kind");
7572}
7573
7574static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7575 if (!A->getASTContext().getLangOpts().CUDA)
7576 return true; // Target attributes are overloadable in CUDA compilation only.
7577 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7578 return false;
7579 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7580 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7581 return true; // unattributed and __host__ functions are the same.
7582}
7583
7584/// Determine whether the attributes we can overload on are identical for A and
7585/// B. Will ignore any overloadable attrs represented in the type of A and B.
7587 const FunctionDecl *B) {
7588 // Note that pass_object_size attributes are represented in the function's
7589 // ExtParameterInfo, so we don't need to check them here.
7590
7591 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7592 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7593 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7594
7595 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7596 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7597 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7598
7599 // Return false if the number of enable_if attributes is different.
7600 if (!Cand1A || !Cand2A)
7601 return false;
7602
7603 Cand1ID.clear();
7604 Cand2ID.clear();
7605
7606 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7607 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7608
7609 // Return false if any of the enable_if expressions of A and B are
7610 // different.
7611 if (Cand1ID != Cand2ID)
7612 return false;
7613 }
7614 return hasSameCudaAttrs(A, B);
7615}
7616
7617bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7618 // Caution: this function is called by the AST reader during deserialization,
7619 // so it cannot rely on AST invariants being met. Non-trivial accessors
7620 // should be avoided, along with any traversal of redeclaration chains.
7621
7622 if (X == Y)
7623 return true;
7624
7625 if (X->getDeclName() != Y->getDeclName())
7626 return false;
7627
7628 // Must be in the same context.
7629 //
7630 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7631 // could be two different declarations of the same function. (We will fix the
7632 // semantic DC to refer to the primary definition after merging.)
7633 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7635 return false;
7636
7637 // If either X or Y are local to the owning module, they are only possible to
7638 // be the same entity if they are in the same module.
7639 if (X->isModuleLocal() || Y->isModuleLocal())
7640 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7641 return false;
7642
7643 // Two typedefs refer to the same entity if they have the same underlying
7644 // type.
7645 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7646 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7647 return hasSameType(TypedefX->getUnderlyingType(),
7648 TypedefY->getUnderlyingType());
7649
7650 // Must have the same kind.
7651 if (X->getKind() != Y->getKind())
7652 return false;
7653
7654 // Objective-C classes and protocols with the same name always match.
7656 return true;
7657
7659 // No need to handle these here: we merge them when adding them to the
7660 // template.
7661 return false;
7662 }
7663
7664 // Compatible tags match.
7665 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7666 const auto *TagY = cast<TagDecl>(Y);
7667 return (TagX->getTagKind() == TagY->getTagKind()) ||
7668 ((TagX->getTagKind() == TagTypeKind::Struct ||
7669 TagX->getTagKind() == TagTypeKind::Class ||
7670 TagX->getTagKind() == TagTypeKind::Interface) &&
7671 (TagY->getTagKind() == TagTypeKind::Struct ||
7672 TagY->getTagKind() == TagTypeKind::Class ||
7673 TagY->getTagKind() == TagTypeKind::Interface));
7674 }
7675
7676 // Functions with the same type and linkage match.
7677 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7678 // functions, etc.
7679 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7680 const auto *FuncY = cast<FunctionDecl>(Y);
7681 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7682 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7683 if (CtorX->getInheritedConstructor() &&
7684 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7685 CtorY->getInheritedConstructor().getConstructor()))
7686 return false;
7687 }
7688
7689 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7690 return false;
7691
7692 // Multiversioned functions with different feature strings are represented
7693 // as separate declarations.
7694 if (FuncX->isMultiVersion()) {
7695 const auto *TAX = FuncX->getAttr<TargetAttr>();
7696 const auto *TAY = FuncY->getAttr<TargetAttr>();
7697 assert(TAX && TAY && "Multiversion Function without target attribute");
7698
7699 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7700 return false;
7701 }
7702
7703 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7704 // not the same entity if they are constrained.
7705 if ((FuncX->isMemberLikeConstrainedFriend() ||
7706 FuncY->isMemberLikeConstrainedFriend()) &&
7707 !FuncX->getLexicalDeclContext()->Equals(
7708 FuncY->getLexicalDeclContext())) {
7709 return false;
7710 }
7711
7712 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7713 FuncY->getTrailingRequiresClause()))
7714 return false;
7715
7716 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7717 // Map to the first declaration that we've already merged into this one.
7718 // The TSI of redeclarations might not match (due to calling conventions
7719 // being inherited onto the type but not the TSI), but the TSI type of
7720 // the first declaration of the function should match across modules.
7721 FD = FD->getCanonicalDecl();
7722 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7723 : FD->getType();
7724 };
7725 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7726 if (!hasSameType(XT, YT)) {
7727 // We can get functions with different types on the redecl chain in C++17
7728 // if they have differing exception specifications and at least one of
7729 // the excpetion specs is unresolved.
7730 auto *XFPT = XT->getAs<FunctionProtoType>();
7731 auto *YFPT = YT->getAs<FunctionProtoType>();
7732 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7733 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7736 return true;
7737 return false;
7738 }
7739
7740 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7741 hasSameOverloadableAttrs(FuncX, FuncY);
7742 }
7743
7744 // Variables with the same type and linkage match.
7745 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7746 const auto *VarY = cast<VarDecl>(Y);
7747 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7748 // During deserialization, we might compare variables before we load
7749 // their types. Assume the types will end up being the same.
7750 if (VarX->getType().isNull() || VarY->getType().isNull())
7751 return true;
7752
7753 if (hasSameType(VarX->getType(), VarY->getType()))
7754 return true;
7755
7756 // We can get decls with different types on the redecl chain. Eg.
7757 // template <typename T> struct S { static T Var[]; }; // #1
7758 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7759 // Only? happens when completing an incomplete array type. In this case
7760 // when comparing #1 and #2 we should go through their element type.
7761 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7762 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7763 if (!VarXTy || !VarYTy)
7764 return false;
7765 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7766 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7767 }
7768 return false;
7769 }
7770
7771 // Namespaces with the same name and inlinedness match.
7772 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7773 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7774 return NamespaceX->isInline() == NamespaceY->isInline();
7775 }
7776
7777 // Identical template names and kinds match if their template parameter lists
7778 // and patterns match.
7779 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7780 const auto *TemplateY = cast<TemplateDecl>(Y);
7781
7782 // ConceptDecl wouldn't be the same if their constraint expression differs.
7783 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7784 const auto *ConceptY = cast<ConceptDecl>(Y);
7785 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7786 ConceptY->getConstraintExpr()))
7787 return false;
7788 }
7789
7790 return isSameEntity(TemplateX->getTemplatedDecl(),
7791 TemplateY->getTemplatedDecl()) &&
7792 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7793 TemplateY->getTemplateParameters());
7794 }
7795
7796 // Fields with the same name and the same type match.
7797 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7798 const auto *FDY = cast<FieldDecl>(Y);
7799 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7800 return hasSameType(FDX->getType(), FDY->getType());
7801 }
7802
7803 // Indirect fields with the same target field match.
7804 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7805 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7806 return IFDX->getAnonField()->getCanonicalDecl() ==
7807 IFDY->getAnonField()->getCanonicalDecl();
7808 }
7809
7810 // Enumerators with the same name match.
7812 // FIXME: Also check the value is odr-equivalent.
7813 return true;
7814
7815 // Using shadow declarations with the same target match.
7816 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7817 const auto *USY = cast<UsingShadowDecl>(Y);
7818 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7819 }
7820
7821 // Using declarations with the same qualifier match. (We already know that
7822 // the name matches.)
7823 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7824 const auto *UY = cast<UsingDecl>(Y);
7825 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7826 UX->hasTypename() == UY->hasTypename() &&
7827 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7828 }
7829 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7830 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7831 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7832 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7833 }
7834 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7835 return isSameQualifier(
7836 UX->getQualifier(),
7837 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7838 }
7839
7840 // Using-pack declarations are only created by instantiation, and match if
7841 // they're instantiated from matching UnresolvedUsing...Decls.
7842 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7843 return declaresSameEntity(
7844 UX->getInstantiatedFromUsingDecl(),
7845 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7846 }
7847
7848 // Namespace alias definitions with the same target match.
7849 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7850 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7851 return NAX->getNamespace()->Equals(NAY->getNamespace());
7852 }
7853
7854 return false;
7855}
7856
7859 switch (Arg.getKind()) {
7861 return Arg;
7862
7864 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7865 Arg.getIsDefaulted());
7866
7868 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7870 Arg.getIsDefaulted());
7871 }
7872
7875 /*isNullPtr*/ true, Arg.getIsDefaulted());
7876
7879 Arg.getIsDefaulted());
7880
7882 return TemplateArgument(
7885
7888
7890 return TemplateArgument(*this,
7893
7896 /*isNullPtr*/ false, Arg.getIsDefaulted());
7897
7899 bool AnyNonCanonArgs = false;
7900 auto CanonArgs = ::getCanonicalTemplateArguments(
7901 *this, Arg.pack_elements(), AnyNonCanonArgs);
7902 if (!AnyNonCanonArgs)
7903 return Arg;
7905 const_cast<ASTContext &>(*this), CanonArgs);
7906 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7907 return NewArg;
7908 }
7909 }
7910
7911 // Silence GCC warning
7912 llvm_unreachable("Unhandled template argument kind");
7913}
7914
7916 const TemplateArgument &Arg2) const {
7917 if (Arg1.getKind() != Arg2.getKind())
7918 return false;
7919
7920 switch (Arg1.getKind()) {
7922 llvm_unreachable("Comparing NULL template argument");
7923
7925 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7926
7928 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7930
7932 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7933
7938
7940 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
7941 Arg2.getAsIntegral());
7942
7944 return Arg1.structurallyEquals(Arg2);
7945
7947 llvm::FoldingSetNodeID ID1, ID2;
7948 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
7949 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
7950 return ID1 == ID2;
7951 }
7952
7954 return llvm::equal(
7955 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
7956 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
7957 return isSameTemplateArgument(Arg1, Arg2);
7958 });
7959 }
7960
7961 llvm_unreachable("Unhandled template argument kind");
7962}
7963
7965 // Handle the non-qualified case efficiently.
7966 if (!T.hasLocalQualifiers()) {
7967 // Handle the common positive case fast.
7968 if (const auto *AT = dyn_cast<ArrayType>(T))
7969 return AT;
7970 }
7971
7972 // Handle the common negative case fast.
7973 if (!isa<ArrayType>(T.getCanonicalType()))
7974 return nullptr;
7975
7976 // Apply any qualifiers from the array type to the element type. This
7977 // implements C99 6.7.3p8: "If the specification of an array type includes
7978 // any type qualifiers, the element type is so qualified, not the array type."
7979
7980 // If we get here, we either have type qualifiers on the type, or we have
7981 // sugar such as a typedef in the way. If we have type qualifiers on the type
7982 // we must propagate them down into the element type.
7983
7984 SplitQualType split = T.getSplitDesugaredType();
7985 Qualifiers qs = split.Quals;
7986
7987 // If we have a simple case, just return now.
7988 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
7989 if (!ATy || qs.empty())
7990 return ATy;
7991
7992 // Otherwise, we have an array and we have qualifiers on it. Push the
7993 // qualifiers into the array element type and return a new array type.
7994 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
7995
7996 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
7997 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
7998 CAT->getSizeExpr(),
7999 CAT->getSizeModifier(),
8000 CAT->getIndexTypeCVRQualifiers()));
8001 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8003 IAT->getSizeModifier(),
8004 IAT->getIndexTypeCVRQualifiers()));
8005
8006 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8008 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8009 DSAT->getIndexTypeCVRQualifiers()));
8010
8011 const auto *VAT = cast<VariableArrayType>(ATy);
8012 return cast<ArrayType>(
8013 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8014 VAT->getIndexTypeCVRQualifiers()));
8015}
8016
8018 if (getLangOpts().HLSL && T->isConstantArrayType())
8019 return getArrayParameterType(T);
8020 if (T->isArrayType() || T->isFunctionType())
8021 return getDecayedType(T);
8022 return T;
8023}
8024
8028 return T.getUnqualifiedType();
8029}
8030
8032 // C++ [except.throw]p3:
8033 // A throw-expression initializes a temporary object, called the exception
8034 // object, the type of which is determined by removing any top-level
8035 // cv-qualifiers from the static type of the operand of throw and adjusting
8036 // the type from "array of T" or "function returning T" to "pointer to T"
8037 // or "pointer to function returning T", [...]
8039 if (T->isArrayType() || T->isFunctionType())
8040 T = getDecayedType(T);
8041 return T.getUnqualifiedType();
8042}
8043
8044/// getArrayDecayedType - Return the properly qualified result of decaying the
8045/// specified array type to a pointer. This operation is non-trivial when
8046/// handling typedefs etc. The canonical type of "T" must be an array type,
8047/// this returns a pointer to a properly qualified element of the array.
8048///
8049/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8051 // Get the element type with 'getAsArrayType' so that we don't lose any
8052 // typedefs in the element type of the array. This also handles propagation
8053 // of type qualifiers from the array type into the element type if present
8054 // (C99 6.7.3p8).
8055 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8056 assert(PrettyArrayType && "Not an array type!");
8057
8058 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8059
8060 // int x[restrict 4] -> int *restrict
8062 PrettyArrayType->getIndexTypeQualifiers());
8063
8064 // int x[_Nullable] -> int * _Nullable
8065 if (auto Nullability = Ty->getNullability()) {
8066 Result = const_cast<ASTContext *>(this)->getAttributedType(*Nullability,
8067 Result, Result);
8068 }
8069 return Result;
8070}
8071
8073 return getBaseElementType(array->getElementType());
8074}
8075
8077 Qualifiers qs;
8078 while (true) {
8079 SplitQualType split = type.getSplitDesugaredType();
8080 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8081 if (!array) break;
8082
8083 type = array->getElementType();
8085 }
8086
8087 return getQualifiedType(type, qs);
8088}
8089
8090/// getConstantArrayElementCount - Returns number of constant array elements.
8091uint64_t
8093 uint64_t ElementCount = 1;
8094 do {
8095 ElementCount *= CA->getZExtSize();
8096 CA = dyn_cast_or_null<ConstantArrayType>(
8098 } while (CA);
8099 return ElementCount;
8100}
8101
8103 const ArrayInitLoopExpr *AILE) const {
8104 if (!AILE)
8105 return 0;
8106
8107 uint64_t ElementCount = 1;
8108
8109 do {
8110 ElementCount *= AILE->getArraySize().getZExtValue();
8111 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8112 } while (AILE);
8113
8114 return ElementCount;
8115}
8116
8117/// getFloatingRank - Return a relative rank for floating point types.
8118/// This routine will assert if passed a built-in type that isn't a float.
8120 if (const auto *CT = T->getAs<ComplexType>())
8121 return getFloatingRank(CT->getElementType());
8122
8123 switch (T->castAs<BuiltinType>()->getKind()) {
8124 default: llvm_unreachable("getFloatingRank(): not a floating type");
8125 case BuiltinType::Float16: return Float16Rank;
8126 case BuiltinType::Half: return HalfRank;
8127 case BuiltinType::Float: return FloatRank;
8128 case BuiltinType::Double: return DoubleRank;
8129 case BuiltinType::LongDouble: return LongDoubleRank;
8130 case BuiltinType::Float128: return Float128Rank;
8131 case BuiltinType::BFloat16: return BFloat16Rank;
8132 case BuiltinType::Ibm128: return Ibm128Rank;
8133 }
8134}
8135
8136/// getFloatingTypeOrder - Compare the rank of the two specified floating
8137/// point types, ignoring the domain of the type (i.e. 'double' ==
8138/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8139/// LHS < RHS, return -1.
8141 FloatingRank LHSR = getFloatingRank(LHS);
8142 FloatingRank RHSR = getFloatingRank(RHS);
8143
8144 if (LHSR == RHSR)
8145 return 0;
8146 if (LHSR > RHSR)
8147 return 1;
8148 return -1;
8149}
8150
8153 return 0;
8154 return getFloatingTypeOrder(LHS, RHS);
8155}
8156
8157/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8158/// routine will assert if passed a built-in type that isn't an integer or enum,
8159/// or if it is not canonicalized.
8160unsigned ASTContext::getIntegerRank(const Type *T) const {
8161 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8162
8163 // Results in this 'losing' to any type of the same size, but winning if
8164 // larger.
8165 if (const auto *EIT = dyn_cast<BitIntType>(T))
8166 return 0 + (EIT->getNumBits() << 3);
8167
8168 switch (cast<BuiltinType>(T)->getKind()) {
8169 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8170 case BuiltinType::Bool:
8171 return 1 + (getIntWidth(BoolTy) << 3);
8172 case BuiltinType::Char_S:
8173 case BuiltinType::Char_U:
8174 case BuiltinType::SChar:
8175 case BuiltinType::UChar:
8176 return 2 + (getIntWidth(CharTy) << 3);
8177 case BuiltinType::Short:
8178 case BuiltinType::UShort:
8179 return 3 + (getIntWidth(ShortTy) << 3);
8180 case BuiltinType::Int:
8181 case BuiltinType::UInt:
8182 return 4 + (getIntWidth(IntTy) << 3);
8183 case BuiltinType::Long:
8184 case BuiltinType::ULong:
8185 return 5 + (getIntWidth(LongTy) << 3);
8186 case BuiltinType::LongLong:
8187 case BuiltinType::ULongLong:
8188 return 6 + (getIntWidth(LongLongTy) << 3);
8189 case BuiltinType::Int128:
8190 case BuiltinType::UInt128:
8191 return 7 + (getIntWidth(Int128Ty) << 3);
8192
8193 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8194 // their underlying types" [c++20 conv.rank]
8195 case BuiltinType::Char8:
8196 return getIntegerRank(UnsignedCharTy.getTypePtr());
8197 case BuiltinType::Char16:
8198 return getIntegerRank(
8199 getFromTargetType(Target->getChar16Type()).getTypePtr());
8200 case BuiltinType::Char32:
8201 return getIntegerRank(
8202 getFromTargetType(Target->getChar32Type()).getTypePtr());
8203 case BuiltinType::WChar_S:
8204 case BuiltinType::WChar_U:
8205 return getIntegerRank(
8206 getFromTargetType(Target->getWCharType()).getTypePtr());
8207 }
8208}
8209
8210/// Whether this is a promotable bitfield reference according
8211/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8212///
8213/// \returns the type this bit-field will promote to, or NULL if no
8214/// promotion occurs.
8216 if (E->isTypeDependent() || E->isValueDependent())
8217 return {};
8218
8219 // C++ [conv.prom]p5:
8220 // If the bit-field has an enumerated type, it is treated as any other
8221 // value of that type for promotion purposes.
8223 return {};
8224
8225 // FIXME: We should not do this unless E->refersToBitField() is true. This
8226 // matters in C where getSourceBitField() will find bit-fields for various
8227 // cases where the source expression is not a bit-field designator.
8228
8229 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8230 if (!Field)
8231 return {};
8232
8233 QualType FT = Field->getType();
8234
8235 uint64_t BitWidth = Field->getBitWidthValue();
8236 uint64_t IntSize = getTypeSize(IntTy);
8237 // C++ [conv.prom]p5:
8238 // A prvalue for an integral bit-field can be converted to a prvalue of type
8239 // int if int can represent all the values of the bit-field; otherwise, it
8240 // can be converted to unsigned int if unsigned int can represent all the
8241 // values of the bit-field. If the bit-field is larger yet, no integral
8242 // promotion applies to it.
8243 // C11 6.3.1.1/2:
8244 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8245 // If an int can represent all values of the original type (as restricted by
8246 // the width, for a bit-field), the value is converted to an int; otherwise,
8247 // it is converted to an unsigned int.
8248 //
8249 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8250 // We perform that promotion here to match GCC and C++.
8251 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8252 // greater than that of 'int'. We perform that promotion to match GCC.
8253 //
8254 // C23 6.3.1.1p2:
8255 // The value from a bit-field of a bit-precise integer type is converted to
8256 // the corresponding bit-precise integer type. (The rest is the same as in
8257 // C11.)
8258 if (QualType QT = Field->getType(); QT->isBitIntType())
8259 return QT;
8260
8261 if (BitWidth < IntSize)
8262 return IntTy;
8263
8264 if (BitWidth == IntSize)
8265 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8266
8267 // Bit-fields wider than int are not subject to promotions, and therefore act
8268 // like the base type. GCC has some weird bugs in this area that we
8269 // deliberately do not follow (GCC follows a pre-standard resolution to
8270 // C's DR315 which treats bit-width as being part of the type, and this leaks
8271 // into their semantics in some cases).
8272 return {};
8273}
8274
8275/// getPromotedIntegerType - Returns the type that Promotable will
8276/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8277/// integer type.
8279 assert(!Promotable.isNull());
8280 assert(isPromotableIntegerType(Promotable));
8281 if (const auto *ED = Promotable->getAsEnumDecl())
8282 return ED->getPromotionType();
8283
8284 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8285 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8286 // (3.9.1) can be converted to a prvalue of the first of the following
8287 // types that can represent all the values of its underlying type:
8288 // int, unsigned int, long int, unsigned long int, long long int, or
8289 // unsigned long long int [...]
8290 // FIXME: Is there some better way to compute this?
8291 if (BT->getKind() == BuiltinType::WChar_S ||
8292 BT->getKind() == BuiltinType::WChar_U ||
8293 BT->getKind() == BuiltinType::Char8 ||
8294 BT->getKind() == BuiltinType::Char16 ||
8295 BT->getKind() == BuiltinType::Char32) {
8296 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8297 uint64_t FromSize = getTypeSize(BT);
8298 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8300 for (const auto &PT : PromoteTypes) {
8301 uint64_t ToSize = getTypeSize(PT);
8302 if (FromSize < ToSize ||
8303 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8304 return PT;
8305 }
8306 llvm_unreachable("char type should fit into long long");
8307 }
8308 }
8309
8310 // At this point, we should have a signed or unsigned integer type.
8311 if (Promotable->isSignedIntegerType())
8312 return IntTy;
8313 uint64_t PromotableSize = getIntWidth(Promotable);
8314 uint64_t IntSize = getIntWidth(IntTy);
8315 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8316 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8317}
8318
8319/// Recurses in pointer/array types until it finds an objc retainable
8320/// type and returns its ownership.
8322 while (!T.isNull()) {
8323 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8324 return T.getObjCLifetime();
8325 if (T->isArrayType())
8327 else if (const auto *PT = T->getAs<PointerType>())
8328 T = PT->getPointeeType();
8329 else if (const auto *RT = T->getAs<ReferenceType>())
8330 T = RT->getPointeeType();
8331 else
8332 break;
8333 }
8334
8335 return Qualifiers::OCL_None;
8336}
8337
8338static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8339 // Incomplete enum types are not treated as integer types.
8340 // FIXME: In C++, enum types are never integer types.
8341 const EnumDecl *ED = ET->getOriginalDecl()->getDefinitionOrSelf();
8342 if (ED->isComplete() && !ED->isScoped())
8343 return ED->getIntegerType().getTypePtr();
8344 return nullptr;
8345}
8346
8347/// getIntegerTypeOrder - Returns the highest ranked integer type:
8348/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8349/// LHS < RHS, return -1.
8351 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8352 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8353
8354 // Unwrap enums to their underlying type.
8355 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8356 LHSC = getIntegerTypeForEnum(ET);
8357 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8358 RHSC = getIntegerTypeForEnum(ET);
8359
8360 if (LHSC == RHSC) return 0;
8361
8362 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8363 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8364
8365 unsigned LHSRank = getIntegerRank(LHSC);
8366 unsigned RHSRank = getIntegerRank(RHSC);
8367
8368 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8369 if (LHSRank == RHSRank) return 0;
8370 return LHSRank > RHSRank ? 1 : -1;
8371 }
8372
8373 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8374 if (LHSUnsigned) {
8375 // If the unsigned [LHS] type is larger, return it.
8376 if (LHSRank >= RHSRank)
8377 return 1;
8378
8379 // If the signed type can represent all values of the unsigned type, it
8380 // wins. Because we are dealing with 2's complement and types that are
8381 // powers of two larger than each other, this is always safe.
8382 return -1;
8383 }
8384
8385 // If the unsigned [RHS] type is larger, return it.
8386 if (RHSRank >= LHSRank)
8387 return -1;
8388
8389 // If the signed type can represent all values of the unsigned type, it
8390 // wins. Because we are dealing with 2's complement and types that are
8391 // powers of two larger than each other, this is always safe.
8392 return 1;
8393}
8394
8396 if (CFConstantStringTypeDecl)
8397 return CFConstantStringTypeDecl;
8398
8399 assert(!CFConstantStringTagDecl &&
8400 "tag and typedef should be initialized together");
8401 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8402 CFConstantStringTagDecl->startDefinition();
8403
8404 struct {
8405 QualType Type;
8406 const char *Name;
8407 } Fields[5];
8408 unsigned Count = 0;
8409
8410 /// Objective-C ABI
8411 ///
8412 /// typedef struct __NSConstantString_tag {
8413 /// const int *isa;
8414 /// int flags;
8415 /// const char *str;
8416 /// long length;
8417 /// } __NSConstantString;
8418 ///
8419 /// Swift ABI (4.1, 4.2)
8420 ///
8421 /// typedef struct __NSConstantString_tag {
8422 /// uintptr_t _cfisa;
8423 /// uintptr_t _swift_rc;
8424 /// _Atomic(uint64_t) _cfinfoa;
8425 /// const char *_ptr;
8426 /// uint32_t _length;
8427 /// } __NSConstantString;
8428 ///
8429 /// Swift ABI (5.0)
8430 ///
8431 /// typedef struct __NSConstantString_tag {
8432 /// uintptr_t _cfisa;
8433 /// uintptr_t _swift_rc;
8434 /// _Atomic(uint64_t) _cfinfoa;
8435 /// const char *_ptr;
8436 /// uintptr_t _length;
8437 /// } __NSConstantString;
8438
8439 const auto CFRuntime = getLangOpts().CFRuntime;
8440 if (static_cast<unsigned>(CFRuntime) <
8441 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8442 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8443 Fields[Count++] = { IntTy, "flags" };
8444 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8445 Fields[Count++] = { LongTy, "length" };
8446 } else {
8447 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8448 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8449 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8450 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8453 Fields[Count++] = { IntTy, "_ptr" };
8454 else
8455 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8456 }
8457
8458 // Create fields
8459 for (unsigned i = 0; i < Count; ++i) {
8460 FieldDecl *Field =
8461 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8462 SourceLocation(), &Idents.get(Fields[i].Name),
8463 Fields[i].Type, /*TInfo=*/nullptr,
8464 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8465 Field->setAccess(AS_public);
8466 CFConstantStringTagDecl->addDecl(Field);
8467 }
8468
8469 CFConstantStringTagDecl->completeDefinition();
8470 // This type is designed to be compatible with NSConstantString, but cannot
8471 // use the same name, since NSConstantString is an interface.
8472 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8473 CFConstantStringTypeDecl =
8474 buildImplicitTypedef(tagType, "__NSConstantString");
8475
8476 return CFConstantStringTypeDecl;
8477}
8478
8480 if (!CFConstantStringTagDecl)
8481 getCFConstantStringDecl(); // Build the tag and the typedef.
8482 return CFConstantStringTagDecl;
8483}
8484
8485// getCFConstantStringType - Return the type used for constant CFStrings.
8490
8492 if (ObjCSuperType.isNull()) {
8493 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8494 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8495 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8496 }
8497 return ObjCSuperType;
8498}
8499
8501 const auto *TT = T->castAs<TypedefType>();
8502 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8503 CFConstantStringTagDecl = TT->castAsRecordDecl();
8504}
8505
8507 if (BlockDescriptorType)
8508 return getCanonicalTagType(BlockDescriptorType);
8509
8510 RecordDecl *RD;
8511 // FIXME: Needs the FlagAppleBlock bit.
8512 RD = buildImplicitRecord("__block_descriptor");
8513 RD->startDefinition();
8514
8515 QualType FieldTypes[] = {
8518 };
8519
8520 static const char *const FieldNames[] = {
8521 "reserved",
8522 "Size"
8523 };
8524
8525 for (size_t i = 0; i < 2; ++i) {
8527 *this, RD, SourceLocation(), SourceLocation(),
8528 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8529 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8530 Field->setAccess(AS_public);
8531 RD->addDecl(Field);
8532 }
8533
8534 RD->completeDefinition();
8535
8536 BlockDescriptorType = RD;
8537
8538 return getCanonicalTagType(BlockDescriptorType);
8539}
8540
8542 if (BlockDescriptorExtendedType)
8543 return getCanonicalTagType(BlockDescriptorExtendedType);
8544
8545 RecordDecl *RD;
8546 // FIXME: Needs the FlagAppleBlock bit.
8547 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8548 RD->startDefinition();
8549
8550 QualType FieldTypes[] = {
8555 };
8556
8557 static const char *const FieldNames[] = {
8558 "reserved",
8559 "Size",
8560 "CopyFuncPtr",
8561 "DestroyFuncPtr"
8562 };
8563
8564 for (size_t i = 0; i < 4; ++i) {
8566 *this, RD, SourceLocation(), SourceLocation(),
8567 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8568 /*BitWidth=*/nullptr,
8569 /*Mutable=*/false, ICIS_NoInit);
8570 Field->setAccess(AS_public);
8571 RD->addDecl(Field);
8572 }
8573
8574 RD->completeDefinition();
8575
8576 BlockDescriptorExtendedType = RD;
8577 return getCanonicalTagType(BlockDescriptorExtendedType);
8578}
8579
8581 const auto *BT = dyn_cast<BuiltinType>(T);
8582
8583 if (!BT) {
8584 if (isa<PipeType>(T))
8585 return OCLTK_Pipe;
8586
8587 return OCLTK_Default;
8588 }
8589
8590 switch (BT->getKind()) {
8591#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8592 case BuiltinType::Id: \
8593 return OCLTK_Image;
8594#include "clang/Basic/OpenCLImageTypes.def"
8595
8596 case BuiltinType::OCLClkEvent:
8597 return OCLTK_ClkEvent;
8598
8599 case BuiltinType::OCLEvent:
8600 return OCLTK_Event;
8601
8602 case BuiltinType::OCLQueue:
8603 return OCLTK_Queue;
8604
8605 case BuiltinType::OCLReserveID:
8606 return OCLTK_ReserveID;
8607
8608 case BuiltinType::OCLSampler:
8609 return OCLTK_Sampler;
8610
8611 default:
8612 return OCLTK_Default;
8613 }
8614}
8615
8617 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8618}
8619
8620/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8621/// requires copy/dispose. Note that this must match the logic
8622/// in buildByrefHelpers.
8624 const VarDecl *D) {
8625 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8626 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8627 if (!copyExpr && record->hasTrivialDestructor()) return false;
8628
8629 return true;
8630 }
8631
8633 return true;
8634
8635 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8636 // move or destroy.
8638 return true;
8639
8640 if (!Ty->isObjCRetainableType()) return false;
8641
8642 Qualifiers qs = Ty.getQualifiers();
8643
8644 // If we have lifetime, that dominates.
8645 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8646 switch (lifetime) {
8647 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8648
8649 // These are just bits as far as the runtime is concerned.
8652 return false;
8653
8654 // These cases should have been taken care of when checking the type's
8655 // non-triviality.
8658 llvm_unreachable("impossible");
8659 }
8660 llvm_unreachable("fell out of lifetime switch!");
8661 }
8662 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8664}
8665
8667 Qualifiers::ObjCLifetime &LifeTime,
8668 bool &HasByrefExtendedLayout) const {
8669 if (!getLangOpts().ObjC ||
8670 getLangOpts().getGC() != LangOptions::NonGC)
8671 return false;
8672
8673 HasByrefExtendedLayout = false;
8674 if (Ty->isRecordType()) {
8675 HasByrefExtendedLayout = true;
8676 LifeTime = Qualifiers::OCL_None;
8677 } else if ((LifeTime = Ty.getObjCLifetime())) {
8678 // Honor the ARC qualifiers.
8679 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8680 // The MRR rule.
8682 } else {
8683 LifeTime = Qualifiers::OCL_None;
8684 }
8685 return true;
8686}
8687
8689 assert(Target && "Expected target to be initialized");
8690 const llvm::Triple &T = Target->getTriple();
8691 // Windows is LLP64 rather than LP64
8692 if (T.isOSWindows() && T.isArch64Bit())
8693 return UnsignedLongLongTy;
8694 return UnsignedLongTy;
8695}
8696
8698 assert(Target && "Expected target to be initialized");
8699 const llvm::Triple &T = Target->getTriple();
8700 // Windows is LLP64 rather than LP64
8701 if (T.isOSWindows() && T.isArch64Bit())
8702 return LongLongTy;
8703 return LongTy;
8704}
8705
8707 if (!ObjCInstanceTypeDecl)
8708 ObjCInstanceTypeDecl =
8709 buildImplicitTypedef(getObjCIdType(), "instancetype");
8710 return ObjCInstanceTypeDecl;
8711}
8712
8713// This returns true if a type has been typedefed to BOOL:
8714// typedef <type> BOOL;
8716 if (const auto *TT = dyn_cast<TypedefType>(T))
8717 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8718 return II->isStr("BOOL");
8719
8720 return false;
8721}
8722
8723/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8724/// purpose.
8726 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8727 return CharUnits::Zero();
8728
8730
8731 // Make all integer and enum types at least as large as an int
8732 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8733 sz = std::max(sz, getTypeSizeInChars(IntTy));
8734 // Treat arrays as pointers, since that's how they're passed in.
8735 else if (type->isArrayType())
8737 return sz;
8738}
8739
8746
8749 if (!VD->isInline())
8751
8752 // In almost all cases, it's a weak definition.
8753 auto *First = VD->getFirstDecl();
8754 if (First->isInlineSpecified() || !First->isStaticDataMember())
8756
8757 // If there's a file-context declaration in this translation unit, it's a
8758 // non-discardable definition.
8759 for (auto *D : VD->redecls())
8761 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8763
8764 // If we've not seen one yet, we don't know.
8766}
8767
8768static std::string charUnitsToString(const CharUnits &CU) {
8769 return llvm::itostr(CU.getQuantity());
8770}
8771
8772/// getObjCEncodingForBlock - Return the encoded type for this block
8773/// declaration.
8775 std::string S;
8776
8777 const BlockDecl *Decl = Expr->getBlockDecl();
8778 QualType BlockTy =
8780 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8781 // Encode result type.
8782 if (getLangOpts().EncodeExtendedBlockSig)
8784 true /*Extended*/);
8785 else
8786 getObjCEncodingForType(BlockReturnTy, S);
8787 // Compute size of all parameters.
8788 // Start with computing size of a pointer in number of bytes.
8789 // FIXME: There might(should) be a better way of doing this computation!
8791 CharUnits ParmOffset = PtrSize;
8792 for (auto *PI : Decl->parameters()) {
8793 QualType PType = PI->getType();
8795 if (sz.isZero())
8796 continue;
8797 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8798 ParmOffset += sz;
8799 }
8800 // Size of the argument frame
8801 S += charUnitsToString(ParmOffset);
8802 // Block pointer and offset.
8803 S += "@?0";
8804
8805 // Argument types.
8806 ParmOffset = PtrSize;
8807 for (auto *PVDecl : Decl->parameters()) {
8808 QualType PType = PVDecl->getOriginalType();
8809 if (const auto *AT =
8810 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8811 // Use array's original type only if it has known number of
8812 // elements.
8813 if (!isa<ConstantArrayType>(AT))
8814 PType = PVDecl->getType();
8815 } else if (PType->isFunctionType())
8816 PType = PVDecl->getType();
8817 if (getLangOpts().EncodeExtendedBlockSig)
8819 S, true /*Extended*/);
8820 else
8821 getObjCEncodingForType(PType, S);
8822 S += charUnitsToString(ParmOffset);
8823 ParmOffset += getObjCEncodingTypeSize(PType);
8824 }
8825
8826 return S;
8827}
8828
8829std::string
8831 std::string S;
8832 // Encode result type.
8833 getObjCEncodingForType(Decl->getReturnType(), S);
8834 CharUnits ParmOffset;
8835 // Compute size of all parameters.
8836 for (auto *PI : Decl->parameters()) {
8837 QualType PType = PI->getType();
8839 if (sz.isZero())
8840 continue;
8841
8842 assert(sz.isPositive() &&
8843 "getObjCEncodingForFunctionDecl - Incomplete param type");
8844 ParmOffset += sz;
8845 }
8846 S += charUnitsToString(ParmOffset);
8847 ParmOffset = CharUnits::Zero();
8848
8849 // Argument types.
8850 for (auto *PVDecl : Decl->parameters()) {
8851 QualType PType = PVDecl->getOriginalType();
8852 if (const auto *AT =
8853 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8854 // Use array's original type only if it has known number of
8855 // elements.
8856 if (!isa<ConstantArrayType>(AT))
8857 PType = PVDecl->getType();
8858 } else if (PType->isFunctionType())
8859 PType = PVDecl->getType();
8860 getObjCEncodingForType(PType, S);
8861 S += charUnitsToString(ParmOffset);
8862 ParmOffset += getObjCEncodingTypeSize(PType);
8863 }
8864
8865 return S;
8866}
8867
8868/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8869/// method parameter or return type. If Extended, include class names and
8870/// block object types.
8872 QualType T, std::string& S,
8873 bool Extended) const {
8874 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8876 // Encode parameter type.
8877 ObjCEncOptions Options = ObjCEncOptions()
8878 .setExpandPointedToStructures()
8879 .setExpandStructures()
8880 .setIsOutermostType();
8881 if (Extended)
8882 Options.setEncodeBlockParameters().setEncodeClassNames();
8883 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8884}
8885
8886/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8887/// declaration.
8889 bool Extended) const {
8890 // FIXME: This is not very efficient.
8891 // Encode return type.
8892 std::string S;
8893 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8894 Decl->getReturnType(), S, Extended);
8895 // Compute size of all parameters.
8896 // Start with computing size of a pointer in number of bytes.
8897 // FIXME: There might(should) be a better way of doing this computation!
8899 // The first two arguments (self and _cmd) are pointers; account for
8900 // their size.
8901 CharUnits ParmOffset = 2 * PtrSize;
8902 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8903 E = Decl->sel_param_end(); PI != E; ++PI) {
8904 QualType PType = (*PI)->getType();
8906 if (sz.isZero())
8907 continue;
8908
8909 assert(sz.isPositive() &&
8910 "getObjCEncodingForMethodDecl - Incomplete param type");
8911 ParmOffset += sz;
8912 }
8913 S += charUnitsToString(ParmOffset);
8914 S += "@0:";
8915 S += charUnitsToString(PtrSize);
8916
8917 // Argument types.
8918 ParmOffset = 2 * PtrSize;
8919 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8920 E = Decl->sel_param_end(); PI != E; ++PI) {
8921 const ParmVarDecl *PVDecl = *PI;
8922 QualType PType = PVDecl->getOriginalType();
8923 if (const auto *AT =
8924 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8925 // Use array's original type only if it has known number of
8926 // elements.
8927 if (!isa<ConstantArrayType>(AT))
8928 PType = PVDecl->getType();
8929 } else if (PType->isFunctionType())
8930 PType = PVDecl->getType();
8932 PType, S, Extended);
8933 S += charUnitsToString(ParmOffset);
8934 ParmOffset += getObjCEncodingTypeSize(PType);
8935 }
8936
8937 return S;
8938}
8939
8942 const ObjCPropertyDecl *PD,
8943 const Decl *Container) const {
8944 if (!Container)
8945 return nullptr;
8946 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
8947 for (auto *PID : CID->property_impls())
8948 if (PID->getPropertyDecl() == PD)
8949 return PID;
8950 } else {
8951 const auto *OID = cast<ObjCImplementationDecl>(Container);
8952 for (auto *PID : OID->property_impls())
8953 if (PID->getPropertyDecl() == PD)
8954 return PID;
8955 }
8956 return nullptr;
8957}
8958
8959/// getObjCEncodingForPropertyDecl - Return the encoded type for this
8960/// property declaration. If non-NULL, Container must be either an
8961/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
8962/// NULL when getting encodings for protocol properties.
8963/// Property attributes are stored as a comma-delimited C string. The simple
8964/// attributes readonly and bycopy are encoded as single characters. The
8965/// parametrized attributes, getter=name, setter=name, and ivar=name, are
8966/// encoded as single characters, followed by an identifier. Property types
8967/// are also encoded as a parametrized attribute. The characters used to encode
8968/// these attributes are defined by the following enumeration:
8969/// @code
8970/// enum PropertyAttributes {
8971/// kPropertyReadOnly = 'R', // property is read-only.
8972/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
8973/// kPropertyByref = '&', // property is a reference to the value last assigned
8974/// kPropertyDynamic = 'D', // property is dynamic
8975/// kPropertyGetter = 'G', // followed by getter selector name
8976/// kPropertySetter = 'S', // followed by setter selector name
8977/// kPropertyInstanceVariable = 'V' // followed by instance variable name
8978/// kPropertyType = 'T' // followed by old-style type encoding.
8979/// kPropertyWeak = 'W' // 'weak' property
8980/// kPropertyStrong = 'P' // property GC'able
8981/// kPropertyNonAtomic = 'N' // property non-atomic
8982/// kPropertyOptional = '?' // property optional
8983/// };
8984/// @endcode
8985std::string
8987 const Decl *Container) const {
8988 // Collect information from the property implementation decl(s).
8989 bool Dynamic = false;
8990 ObjCPropertyImplDecl *SynthesizePID = nullptr;
8991
8992 if (ObjCPropertyImplDecl *PropertyImpDecl =
8994 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
8995 Dynamic = true;
8996 else
8997 SynthesizePID = PropertyImpDecl;
8998 }
8999
9000 // FIXME: This is not very efficient.
9001 std::string S = "T";
9002
9003 // Encode result type.
9004 // GCC has some special rules regarding encoding of properties which
9005 // closely resembles encoding of ivars.
9007
9008 if (PD->isOptional())
9009 S += ",?";
9010
9011 if (PD->isReadOnly()) {
9012 S += ",R";
9014 S += ",C";
9016 S += ",&";
9018 S += ",W";
9019 } else {
9020 switch (PD->getSetterKind()) {
9021 case ObjCPropertyDecl::Assign: break;
9022 case ObjCPropertyDecl::Copy: S += ",C"; break;
9023 case ObjCPropertyDecl::Retain: S += ",&"; break;
9024 case ObjCPropertyDecl::Weak: S += ",W"; break;
9025 }
9026 }
9027
9028 // It really isn't clear at all what this means, since properties
9029 // are "dynamic by default".
9030 if (Dynamic)
9031 S += ",D";
9032
9034 S += ",N";
9035
9037 S += ",G";
9038 S += PD->getGetterName().getAsString();
9039 }
9040
9042 S += ",S";
9043 S += PD->getSetterName().getAsString();
9044 }
9045
9046 if (SynthesizePID) {
9047 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9048 S += ",V";
9049 S += OID->getNameAsString();
9050 }
9051
9052 // FIXME: OBJCGC: weak & strong
9053 return S;
9054}
9055
9056/// getLegacyIntegralTypeEncoding -
9057/// Another legacy compatibility encoding: 32-bit longs are encoded as
9058/// 'l' or 'L' , but not always. For typedefs, we need to use
9059/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9061 if (PointeeTy->getAs<TypedefType>()) {
9062 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9063 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9064 PointeeTy = UnsignedIntTy;
9065 else
9066 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9067 PointeeTy = IntTy;
9068 }
9069 }
9070}
9071
9073 const FieldDecl *Field,
9074 QualType *NotEncodedT) const {
9075 // We follow the behavior of gcc, expanding structures which are
9076 // directly pointed to, and expanding embedded structures. Note that
9077 // these rules are sufficient to prevent recursive encoding of the
9078 // same type.
9079 getObjCEncodingForTypeImpl(T, S,
9080 ObjCEncOptions()
9081 .setExpandPointedToStructures()
9082 .setExpandStructures()
9083 .setIsOutermostType(),
9084 Field, NotEncodedT);
9085}
9086
9088 std::string& S) const {
9089 // Encode result type.
9090 // GCC has some special rules regarding encoding of properties which
9091 // closely resembles encoding of ivars.
9092 getObjCEncodingForTypeImpl(T, S,
9093 ObjCEncOptions()
9094 .setExpandPointedToStructures()
9095 .setExpandStructures()
9096 .setIsOutermostType()
9097 .setEncodingProperty(),
9098 /*Field=*/nullptr);
9099}
9100
9102 const BuiltinType *BT) {
9103 BuiltinType::Kind kind = BT->getKind();
9104 switch (kind) {
9105 case BuiltinType::Void: return 'v';
9106 case BuiltinType::Bool: return 'B';
9107 case BuiltinType::Char8:
9108 case BuiltinType::Char_U:
9109 case BuiltinType::UChar: return 'C';
9110 case BuiltinType::Char16:
9111 case BuiltinType::UShort: return 'S';
9112 case BuiltinType::Char32:
9113 case BuiltinType::UInt: return 'I';
9114 case BuiltinType::ULong:
9115 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9116 case BuiltinType::UInt128: return 'T';
9117 case BuiltinType::ULongLong: return 'Q';
9118 case BuiltinType::Char_S:
9119 case BuiltinType::SChar: return 'c';
9120 case BuiltinType::Short: return 's';
9121 case BuiltinType::WChar_S:
9122 case BuiltinType::WChar_U:
9123 case BuiltinType::Int: return 'i';
9124 case BuiltinType::Long:
9125 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9126 case BuiltinType::LongLong: return 'q';
9127 case BuiltinType::Int128: return 't';
9128 case BuiltinType::Float: return 'f';
9129 case BuiltinType::Double: return 'd';
9130 case BuiltinType::LongDouble: return 'D';
9131 case BuiltinType::NullPtr: return '*'; // like char*
9132
9133 case BuiltinType::BFloat16:
9134 case BuiltinType::Float16:
9135 case BuiltinType::Float128:
9136 case BuiltinType::Ibm128:
9137 case BuiltinType::Half:
9138 case BuiltinType::ShortAccum:
9139 case BuiltinType::Accum:
9140 case BuiltinType::LongAccum:
9141 case BuiltinType::UShortAccum:
9142 case BuiltinType::UAccum:
9143 case BuiltinType::ULongAccum:
9144 case BuiltinType::ShortFract:
9145 case BuiltinType::Fract:
9146 case BuiltinType::LongFract:
9147 case BuiltinType::UShortFract:
9148 case BuiltinType::UFract:
9149 case BuiltinType::ULongFract:
9150 case BuiltinType::SatShortAccum:
9151 case BuiltinType::SatAccum:
9152 case BuiltinType::SatLongAccum:
9153 case BuiltinType::SatUShortAccum:
9154 case BuiltinType::SatUAccum:
9155 case BuiltinType::SatULongAccum:
9156 case BuiltinType::SatShortFract:
9157 case BuiltinType::SatFract:
9158 case BuiltinType::SatLongFract:
9159 case BuiltinType::SatUShortFract:
9160 case BuiltinType::SatUFract:
9161 case BuiltinType::SatULongFract:
9162 // FIXME: potentially need @encodes for these!
9163 return ' ';
9164
9165#define SVE_TYPE(Name, Id, SingletonId) \
9166 case BuiltinType::Id:
9167#include "clang/Basic/AArch64ACLETypes.def"
9168#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9169#include "clang/Basic/RISCVVTypes.def"
9170#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9171#include "clang/Basic/WebAssemblyReferenceTypes.def"
9172#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9173#include "clang/Basic/AMDGPUTypes.def"
9174 {
9175 DiagnosticsEngine &Diags = C->getDiagnostics();
9176 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
9177 "cannot yet @encode type %0");
9178 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
9179 return ' ';
9180 }
9181
9182 case BuiltinType::ObjCId:
9183 case BuiltinType::ObjCClass:
9184 case BuiltinType::ObjCSel:
9185 llvm_unreachable("@encoding ObjC primitive type");
9186
9187 // OpenCL and placeholder types don't need @encodings.
9188#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9189 case BuiltinType::Id:
9190#include "clang/Basic/OpenCLImageTypes.def"
9191#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9192 case BuiltinType::Id:
9193#include "clang/Basic/OpenCLExtensionTypes.def"
9194 case BuiltinType::OCLEvent:
9195 case BuiltinType::OCLClkEvent:
9196 case BuiltinType::OCLQueue:
9197 case BuiltinType::OCLReserveID:
9198 case BuiltinType::OCLSampler:
9199 case BuiltinType::Dependent:
9200#define PPC_VECTOR_TYPE(Name, Id, Size) \
9201 case BuiltinType::Id:
9202#include "clang/Basic/PPCTypes.def"
9203#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9204#include "clang/Basic/HLSLIntangibleTypes.def"
9205#define BUILTIN_TYPE(KIND, ID)
9206#define PLACEHOLDER_TYPE(KIND, ID) \
9207 case BuiltinType::KIND:
9208#include "clang/AST/BuiltinTypes.def"
9209 llvm_unreachable("invalid builtin type for @encode");
9210 }
9211 llvm_unreachable("invalid BuiltinType::Kind value");
9212}
9213
9214static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9216
9217 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9218 if (!Enum->isFixed())
9219 return 'i';
9220
9221 // The encoding of a fixed enum type matches its fixed underlying type.
9222 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9224}
9225
9226static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9227 QualType T, const FieldDecl *FD) {
9228 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9229 S += 'b';
9230 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9231 // The GNU runtime requires more information; bitfields are encoded as b,
9232 // then the offset (in bits) of the first element, then the type of the
9233 // bitfield, then the size in bits. For example, in this structure:
9234 //
9235 // struct
9236 // {
9237 // int integer;
9238 // int flags:2;
9239 // };
9240 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9241 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9242 // information is not especially sensible, but we're stuck with it for
9243 // compatibility with GCC, although providing it breaks anything that
9244 // actually uses runtime introspection and wants to work on both runtimes...
9245 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9246 uint64_t Offset;
9247
9248 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9249 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9250 } else {
9251 const RecordDecl *RD = FD->getParent();
9252 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9253 Offset = RL.getFieldOffset(FD->getFieldIndex());
9254 }
9255
9256 S += llvm::utostr(Offset);
9257
9258 if (const auto *ET = T->getAsCanonical<EnumType>())
9259 S += ObjCEncodingForEnumDecl(Ctx, ET->getOriginalDecl());
9260 else {
9261 const auto *BT = T->castAs<BuiltinType>();
9262 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9263 }
9264 }
9265 S += llvm::utostr(FD->getBitWidthValue());
9266}
9267
9268// Helper function for determining whether the encoded type string would include
9269// a template specialization type.
9271 bool VisitBasesAndFields) {
9272 T = T->getBaseElementTypeUnsafe();
9273
9274 if (auto *PT = T->getAs<PointerType>())
9276 PT->getPointeeType().getTypePtr(), false);
9277
9278 auto *CXXRD = T->getAsCXXRecordDecl();
9279
9280 if (!CXXRD)
9281 return false;
9282
9284 return true;
9285
9286 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9287 return false;
9288
9289 for (const auto &B : CXXRD->bases())
9290 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9291 true))
9292 return true;
9293
9294 for (auto *FD : CXXRD->fields())
9295 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9296 true))
9297 return true;
9298
9299 return false;
9300}
9301
9302// FIXME: Use SmallString for accumulating string.
9303void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9304 const ObjCEncOptions Options,
9305 const FieldDecl *FD,
9306 QualType *NotEncodedT) const {
9308 switch (CT->getTypeClass()) {
9309 case Type::Builtin:
9310 case Type::Enum:
9311 if (FD && FD->isBitField())
9312 return EncodeBitField(this, S, T, FD);
9313 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9314 S += getObjCEncodingForPrimitiveType(this, BT);
9315 else
9316 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getOriginalDecl());
9317 return;
9318
9319 case Type::Complex:
9320 S += 'j';
9321 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9322 ObjCEncOptions(),
9323 /*Field=*/nullptr);
9324 return;
9325
9326 case Type::Atomic:
9327 S += 'A';
9328 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9329 ObjCEncOptions(),
9330 /*Field=*/nullptr);
9331 return;
9332
9333 // encoding for pointer or reference types.
9334 case Type::Pointer:
9335 case Type::LValueReference:
9336 case Type::RValueReference: {
9337 QualType PointeeTy;
9338 if (isa<PointerType>(CT)) {
9339 const auto *PT = T->castAs<PointerType>();
9340 if (PT->isObjCSelType()) {
9341 S += ':';
9342 return;
9343 }
9344 PointeeTy = PT->getPointeeType();
9345 } else {
9346 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9347 }
9348
9349 bool isReadOnly = false;
9350 // For historical/compatibility reasons, the read-only qualifier of the
9351 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9352 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9353 // Also, do not emit the 'r' for anything but the outermost type!
9354 if (T->getAs<TypedefType>()) {
9355 if (Options.IsOutermostType() && T.isConstQualified()) {
9356 isReadOnly = true;
9357 S += 'r';
9358 }
9359 } else if (Options.IsOutermostType()) {
9360 QualType P = PointeeTy;
9361 while (auto PT = P->getAs<PointerType>())
9362 P = PT->getPointeeType();
9363 if (P.isConstQualified()) {
9364 isReadOnly = true;
9365 S += 'r';
9366 }
9367 }
9368 if (isReadOnly) {
9369 // Another legacy compatibility encoding. Some ObjC qualifier and type
9370 // combinations need to be rearranged.
9371 // Rewrite "in const" from "nr" to "rn"
9372 if (StringRef(S).ends_with("nr"))
9373 S.replace(S.end()-2, S.end(), "rn");
9374 }
9375
9376 if (PointeeTy->isCharType()) {
9377 // char pointer types should be encoded as '*' unless it is a
9378 // type that has been typedef'd to 'BOOL'.
9379 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9380 S += '*';
9381 return;
9382 }
9383 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9384 const IdentifierInfo *II = RTy->getOriginalDecl()->getIdentifier();
9385 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9386 if (II == &Idents.get("objc_class")) {
9387 S += '#';
9388 return;
9389 }
9390 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9391 if (II == &Idents.get("objc_object")) {
9392 S += '@';
9393 return;
9394 }
9395 // If the encoded string for the class includes template names, just emit
9396 // "^v" for pointers to the class.
9397 if (getLangOpts().CPlusPlus &&
9398 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9400 RTy, Options.ExpandPointedToStructures()))) {
9401 S += "^v";
9402 return;
9403 }
9404 // fall through...
9405 }
9406 S += '^';
9408
9409 ObjCEncOptions NewOptions;
9410 if (Options.ExpandPointedToStructures())
9411 NewOptions.setExpandStructures();
9412 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9413 /*Field=*/nullptr, NotEncodedT);
9414 return;
9415 }
9416
9417 case Type::ConstantArray:
9418 case Type::IncompleteArray:
9419 case Type::VariableArray: {
9420 const auto *AT = cast<ArrayType>(CT);
9421
9422 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9423 // Incomplete arrays are encoded as a pointer to the array element.
9424 S += '^';
9425
9426 getObjCEncodingForTypeImpl(
9427 AT->getElementType(), S,
9428 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9429 } else {
9430 S += '[';
9431
9432 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9433 S += llvm::utostr(CAT->getZExtSize());
9434 else {
9435 //Variable length arrays are encoded as a regular array with 0 elements.
9437 "Unknown array type!");
9438 S += '0';
9439 }
9440
9441 getObjCEncodingForTypeImpl(
9442 AT->getElementType(), S,
9443 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9444 NotEncodedT);
9445 S += ']';
9446 }
9447 return;
9448 }
9449
9450 case Type::FunctionNoProto:
9451 case Type::FunctionProto:
9452 S += '?';
9453 return;
9454
9455 case Type::Record: {
9456 RecordDecl *RDecl = cast<RecordType>(CT)->getOriginalDecl();
9457 S += RDecl->isUnion() ? '(' : '{';
9458 // Anonymous structures print as '?'
9459 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9460 S += II->getName();
9461 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9462 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9463 llvm::raw_string_ostream OS(S);
9464 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9466 }
9467 } else {
9468 S += '?';
9469 }
9470 if (Options.ExpandStructures()) {
9471 S += '=';
9472 if (!RDecl->isUnion()) {
9473 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9474 } else {
9475 for (const auto *Field : RDecl->fields()) {
9476 if (FD) {
9477 S += '"';
9478 S += Field->getNameAsString();
9479 S += '"';
9480 }
9481
9482 // Special case bit-fields.
9483 if (Field->isBitField()) {
9484 getObjCEncodingForTypeImpl(Field->getType(), S,
9485 ObjCEncOptions().setExpandStructures(),
9486 Field);
9487 } else {
9488 QualType qt = Field->getType();
9490 getObjCEncodingForTypeImpl(
9491 qt, S,
9492 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9493 NotEncodedT);
9494 }
9495 }
9496 }
9497 }
9498 S += RDecl->isUnion() ? ')' : '}';
9499 return;
9500 }
9501
9502 case Type::BlockPointer: {
9503 const auto *BT = T->castAs<BlockPointerType>();
9504 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9505 if (Options.EncodeBlockParameters()) {
9506 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9507
9508 S += '<';
9509 // Block return type
9510 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9511 Options.forComponentType(), FD, NotEncodedT);
9512 // Block self
9513 S += "@?";
9514 // Block parameters
9515 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9516 for (const auto &I : FPT->param_types())
9517 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9518 NotEncodedT);
9519 }
9520 S += '>';
9521 }
9522 return;
9523 }
9524
9525 case Type::ObjCObject: {
9526 // hack to match legacy encoding of *id and *Class
9527 QualType Ty = getObjCObjectPointerType(CT);
9528 if (Ty->isObjCIdType()) {
9529 S += "{objc_object=}";
9530 return;
9531 }
9532 else if (Ty->isObjCClassType()) {
9533 S += "{objc_class=}";
9534 return;
9535 }
9536 // TODO: Double check to make sure this intentionally falls through.
9537 [[fallthrough]];
9538 }
9539
9540 case Type::ObjCInterface: {
9541 // Ignore protocol qualifiers when mangling at this level.
9542 // @encode(class_name)
9543 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9544 S += '{';
9545 S += OI->getObjCRuntimeNameAsString();
9546 if (Options.ExpandStructures()) {
9547 S += '=';
9548 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9549 DeepCollectObjCIvars(OI, true, Ivars);
9550 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9551 const FieldDecl *Field = Ivars[i];
9552 if (Field->isBitField())
9553 getObjCEncodingForTypeImpl(Field->getType(), S,
9554 ObjCEncOptions().setExpandStructures(),
9555 Field);
9556 else
9557 getObjCEncodingForTypeImpl(Field->getType(), S,
9558 ObjCEncOptions().setExpandStructures(), FD,
9559 NotEncodedT);
9560 }
9561 }
9562 S += '}';
9563 return;
9564 }
9565
9566 case Type::ObjCObjectPointer: {
9567 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9568 if (OPT->isObjCIdType()) {
9569 S += '@';
9570 return;
9571 }
9572
9573 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9574 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9575 // Since this is a binary compatibility issue, need to consult with
9576 // runtime folks. Fortunately, this is a *very* obscure construct.
9577 S += '#';
9578 return;
9579 }
9580
9581 if (OPT->isObjCQualifiedIdType()) {
9582 getObjCEncodingForTypeImpl(
9583 getObjCIdType(), S,
9584 Options.keepingOnly(ObjCEncOptions()
9585 .setExpandPointedToStructures()
9586 .setExpandStructures()),
9587 FD);
9588 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9589 // Note that we do extended encoding of protocol qualifier list
9590 // Only when doing ivar or property encoding.
9591 S += '"';
9592 for (const auto *I : OPT->quals()) {
9593 S += '<';
9594 S += I->getObjCRuntimeNameAsString();
9595 S += '>';
9596 }
9597 S += '"';
9598 }
9599 return;
9600 }
9601
9602 S += '@';
9603 if (OPT->getInterfaceDecl() &&
9604 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9605 S += '"';
9606 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9607 for (const auto *I : OPT->quals()) {
9608 S += '<';
9609 S += I->getObjCRuntimeNameAsString();
9610 S += '>';
9611 }
9612 S += '"';
9613 }
9614 return;
9615 }
9616
9617 // gcc just blithely ignores member pointers.
9618 // FIXME: we should do better than that. 'M' is available.
9619 case Type::MemberPointer:
9620 // This matches gcc's encoding, even though technically it is insufficient.
9621 //FIXME. We should do a better job than gcc.
9622 case Type::Vector:
9623 case Type::ExtVector:
9624 // Until we have a coherent encoding of these three types, issue warning.
9625 if (NotEncodedT)
9626 *NotEncodedT = T;
9627 return;
9628
9629 case Type::ConstantMatrix:
9630 if (NotEncodedT)
9631 *NotEncodedT = T;
9632 return;
9633
9634 case Type::BitInt:
9635 if (NotEncodedT)
9636 *NotEncodedT = T;
9637 return;
9638
9639 // We could see an undeduced auto type here during error recovery.
9640 // Just ignore it.
9641 case Type::Auto:
9642 case Type::DeducedTemplateSpecialization:
9643 return;
9644
9645 case Type::HLSLAttributedResource:
9646 case Type::HLSLInlineSpirv:
9647 llvm_unreachable("unexpected type");
9648
9649 case Type::ArrayParameter:
9650 case Type::Pipe:
9651#define ABSTRACT_TYPE(KIND, BASE)
9652#define TYPE(KIND, BASE)
9653#define DEPENDENT_TYPE(KIND, BASE) \
9654 case Type::KIND:
9655#define NON_CANONICAL_TYPE(KIND, BASE) \
9656 case Type::KIND:
9657#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9658 case Type::KIND:
9659#include "clang/AST/TypeNodes.inc"
9660 llvm_unreachable("@encode for dependent type!");
9661 }
9662 llvm_unreachable("bad type kind!");
9663}
9664
9665void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9666 std::string &S,
9667 const FieldDecl *FD,
9668 bool includeVBases,
9669 QualType *NotEncodedT) const {
9670 assert(RDecl && "Expected non-null RecordDecl");
9671 assert(!RDecl->isUnion() && "Should not be called for unions");
9672 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9673 return;
9674
9675 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9676 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9677 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9678
9679 if (CXXRec) {
9680 for (const auto &BI : CXXRec->bases()) {
9681 if (!BI.isVirtual()) {
9682 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9683 if (base->isEmpty())
9684 continue;
9685 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9686 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9687 std::make_pair(offs, base));
9688 }
9689 }
9690 }
9691
9692 for (FieldDecl *Field : RDecl->fields()) {
9693 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9694 continue;
9695 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9696 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9697 std::make_pair(offs, Field));
9698 }
9699
9700 if (CXXRec && includeVBases) {
9701 for (const auto &BI : CXXRec->vbases()) {
9702 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9703 if (base->isEmpty())
9704 continue;
9705 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9706 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9707 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9708 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9709 std::make_pair(offs, base));
9710 }
9711 }
9712
9713 CharUnits size;
9714 if (CXXRec) {
9715 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9716 } else {
9717 size = layout.getSize();
9718 }
9719
9720#ifndef NDEBUG
9721 uint64_t CurOffs = 0;
9722#endif
9723 std::multimap<uint64_t, NamedDecl *>::iterator
9724 CurLayObj = FieldOrBaseOffsets.begin();
9725
9726 if (CXXRec && CXXRec->isDynamicClass() &&
9727 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9728 if (FD) {
9729 S += "\"_vptr$";
9730 std::string recname = CXXRec->getNameAsString();
9731 if (recname.empty()) recname = "?";
9732 S += recname;
9733 S += '"';
9734 }
9735 S += "^^?";
9736#ifndef NDEBUG
9737 CurOffs += getTypeSize(VoidPtrTy);
9738#endif
9739 }
9740
9741 if (!RDecl->hasFlexibleArrayMember()) {
9742 // Mark the end of the structure.
9743 uint64_t offs = toBits(size);
9744 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9745 std::make_pair(offs, nullptr));
9746 }
9747
9748 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9749#ifndef NDEBUG
9750 assert(CurOffs <= CurLayObj->first);
9751 if (CurOffs < CurLayObj->first) {
9752 uint64_t padding = CurLayObj->first - CurOffs;
9753 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9754 // packing/alignment of members is different that normal, in which case
9755 // the encoding will be out-of-sync with the real layout.
9756 // If the runtime switches to just consider the size of types without
9757 // taking into account alignment, we could make padding explicit in the
9758 // encoding (e.g. using arrays of chars). The encoding strings would be
9759 // longer then though.
9760 CurOffs += padding;
9761 }
9762#endif
9763
9764 NamedDecl *dcl = CurLayObj->second;
9765 if (!dcl)
9766 break; // reached end of structure.
9767
9768 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9769 // We expand the bases without their virtual bases since those are going
9770 // in the initial structure. Note that this differs from gcc which
9771 // expands virtual bases each time one is encountered in the hierarchy,
9772 // making the encoding type bigger than it really is.
9773 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9774 NotEncodedT);
9775 assert(!base->isEmpty());
9776#ifndef NDEBUG
9777 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9778#endif
9779 } else {
9780 const auto *field = cast<FieldDecl>(dcl);
9781 if (FD) {
9782 S += '"';
9783 S += field->getNameAsString();
9784 S += '"';
9785 }
9786
9787 if (field->isBitField()) {
9788 EncodeBitField(this, S, field->getType(), field);
9789#ifndef NDEBUG
9790 CurOffs += field->getBitWidthValue();
9791#endif
9792 } else {
9793 QualType qt = field->getType();
9795 getObjCEncodingForTypeImpl(
9796 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9797 FD, NotEncodedT);
9798#ifndef NDEBUG
9799 CurOffs += getTypeSize(field->getType());
9800#endif
9801 }
9802 }
9803 }
9804}
9805
9807 std::string& S) const {
9808 if (QT & Decl::OBJC_TQ_In)
9809 S += 'n';
9810 if (QT & Decl::OBJC_TQ_Inout)
9811 S += 'N';
9812 if (QT & Decl::OBJC_TQ_Out)
9813 S += 'o';
9814 if (QT & Decl::OBJC_TQ_Bycopy)
9815 S += 'O';
9816 if (QT & Decl::OBJC_TQ_Byref)
9817 S += 'R';
9818 if (QT & Decl::OBJC_TQ_Oneway)
9819 S += 'V';
9820}
9821
9823 if (!ObjCIdDecl) {
9826 ObjCIdDecl = buildImplicitTypedef(T, "id");
9827 }
9828 return ObjCIdDecl;
9829}
9830
9832 if (!ObjCSelDecl) {
9834 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9835 }
9836 return ObjCSelDecl;
9837}
9838
9840 if (!ObjCClassDecl) {
9843 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9844 }
9845 return ObjCClassDecl;
9846}
9847
9849 if (!ObjCProtocolClassDecl) {
9850 ObjCProtocolClassDecl
9853 &Idents.get("Protocol"),
9854 /*typeParamList=*/nullptr,
9855 /*PrevDecl=*/nullptr,
9856 SourceLocation(), true);
9857 }
9858
9859 return ObjCProtocolClassDecl;
9860}
9861
9863 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9864 return PointerAuthQualifier();
9866 getLangOpts().PointerAuthObjcInterfaceSelKey,
9867 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9869 /*isIsaPointer=*/false,
9870 /*authenticatesNullValues=*/false);
9871}
9872
9873//===----------------------------------------------------------------------===//
9874// __builtin_va_list Construction Functions
9875//===----------------------------------------------------------------------===//
9876
9878 StringRef Name) {
9879 // typedef char* __builtin[_ms]_va_list;
9880 QualType T = Context->getPointerType(Context->CharTy);
9881 return Context->buildImplicitTypedef(T, Name);
9882}
9883
9885 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9886}
9887
9889 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9890}
9891
9893 // typedef void* __builtin_va_list;
9894 QualType T = Context->getPointerType(Context->VoidTy);
9895 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9896}
9897
9898static TypedefDecl *
9900 // struct __va_list
9901 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9902 if (Context->getLangOpts().CPlusPlus) {
9903 // namespace std { struct __va_list {
9904 auto *NS = NamespaceDecl::Create(
9905 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9906 /*Inline=*/false, SourceLocation(), SourceLocation(),
9907 &Context->Idents.get("std"),
9908 /*PrevDecl=*/nullptr, /*Nested=*/false);
9909 NS->setImplicit();
9911 }
9912
9913 VaListTagDecl->startDefinition();
9914
9915 const size_t NumFields = 5;
9916 QualType FieldTypes[NumFields];
9917 const char *FieldNames[NumFields];
9918
9919 // void *__stack;
9920 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
9921 FieldNames[0] = "__stack";
9922
9923 // void *__gr_top;
9924 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
9925 FieldNames[1] = "__gr_top";
9926
9927 // void *__vr_top;
9928 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
9929 FieldNames[2] = "__vr_top";
9930
9931 // int __gr_offs;
9932 FieldTypes[3] = Context->IntTy;
9933 FieldNames[3] = "__gr_offs";
9934
9935 // int __vr_offs;
9936 FieldTypes[4] = Context->IntTy;
9937 FieldNames[4] = "__vr_offs";
9938
9939 // Create fields
9940 for (unsigned i = 0; i < NumFields; ++i) {
9941 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
9945 &Context->Idents.get(FieldNames[i]),
9946 FieldTypes[i], /*TInfo=*/nullptr,
9947 /*BitWidth=*/nullptr,
9948 /*Mutable=*/false,
9949 ICIS_NoInit);
9950 Field->setAccess(AS_public);
9951 VaListTagDecl->addDecl(Field);
9952 }
9953 VaListTagDecl->completeDefinition();
9954 Context->VaListTagDecl = VaListTagDecl;
9955 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
9956
9957 // } __builtin_va_list;
9958 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
9959}
9960
9962 // typedef struct __va_list_tag {
9964
9965 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
9966 VaListTagDecl->startDefinition();
9967
9968 const size_t NumFields = 5;
9969 QualType FieldTypes[NumFields];
9970 const char *FieldNames[NumFields];
9971
9972 // unsigned char gpr;
9973 FieldTypes[0] = Context->UnsignedCharTy;
9974 FieldNames[0] = "gpr";
9975
9976 // unsigned char fpr;
9977 FieldTypes[1] = Context->UnsignedCharTy;
9978 FieldNames[1] = "fpr";
9979
9980 // unsigned short reserved;
9981 FieldTypes[2] = Context->UnsignedShortTy;
9982 FieldNames[2] = "reserved";
9983
9984 // void* overflow_arg_area;
9985 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
9986 FieldNames[3] = "overflow_arg_area";
9987
9988 // void* reg_save_area;
9989 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
9990 FieldNames[4] = "reg_save_area";
9991
9992 // Create fields
9993 for (unsigned i = 0; i < NumFields; ++i) {
9994 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
9997 &Context->Idents.get(FieldNames[i]),
9998 FieldTypes[i], /*TInfo=*/nullptr,
9999 /*BitWidth=*/nullptr,
10000 /*Mutable=*/false,
10001 ICIS_NoInit);
10002 Field->setAccess(AS_public);
10003 VaListTagDecl->addDecl(Field);
10004 }
10005 VaListTagDecl->completeDefinition();
10006 Context->VaListTagDecl = VaListTagDecl;
10007 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10008
10009 // } __va_list_tag;
10010 TypedefDecl *VaListTagTypedefDecl =
10011 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10012
10013 QualType VaListTagTypedefType =
10014 Context->getTypedefType(ElaboratedTypeKeyword::None,
10015 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10016
10017 // typedef __va_list_tag __builtin_va_list[1];
10018 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10019 QualType VaListTagArrayType = Context->getConstantArrayType(
10020 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10021 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10022}
10023
10024static TypedefDecl *
10026 // struct __va_list_tag {
10028 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10029 VaListTagDecl->startDefinition();
10030
10031 const size_t NumFields = 4;
10032 QualType FieldTypes[NumFields];
10033 const char *FieldNames[NumFields];
10034
10035 // unsigned gp_offset;
10036 FieldTypes[0] = Context->UnsignedIntTy;
10037 FieldNames[0] = "gp_offset";
10038
10039 // unsigned fp_offset;
10040 FieldTypes[1] = Context->UnsignedIntTy;
10041 FieldNames[1] = "fp_offset";
10042
10043 // void* overflow_arg_area;
10044 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10045 FieldNames[2] = "overflow_arg_area";
10046
10047 // void* reg_save_area;
10048 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10049 FieldNames[3] = "reg_save_area";
10050
10051 // Create fields
10052 for (unsigned i = 0; i < NumFields; ++i) {
10053 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10057 &Context->Idents.get(FieldNames[i]),
10058 FieldTypes[i], /*TInfo=*/nullptr,
10059 /*BitWidth=*/nullptr,
10060 /*Mutable=*/false,
10061 ICIS_NoInit);
10062 Field->setAccess(AS_public);
10063 VaListTagDecl->addDecl(Field);
10064 }
10065 VaListTagDecl->completeDefinition();
10066 Context->VaListTagDecl = VaListTagDecl;
10067 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10068
10069 // };
10070
10071 // typedef struct __va_list_tag __builtin_va_list[1];
10072 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10073 QualType VaListTagArrayType = Context->getConstantArrayType(
10074 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10075 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10076}
10077
10078static TypedefDecl *
10080 // struct __va_list
10081 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10082 if (Context->getLangOpts().CPlusPlus) {
10083 // namespace std { struct __va_list {
10084 NamespaceDecl *NS;
10085 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10086 Context->getTranslationUnitDecl(),
10087 /*Inline=*/false, SourceLocation(),
10088 SourceLocation(), &Context->Idents.get("std"),
10089 /*PrevDecl=*/nullptr, /*Nested=*/false);
10090 NS->setImplicit();
10091 VaListDecl->setDeclContext(NS);
10092 }
10093
10094 VaListDecl->startDefinition();
10095
10096 // void * __ap;
10097 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10098 VaListDecl,
10101 &Context->Idents.get("__ap"),
10102 Context->getPointerType(Context->VoidTy),
10103 /*TInfo=*/nullptr,
10104 /*BitWidth=*/nullptr,
10105 /*Mutable=*/false,
10106 ICIS_NoInit);
10107 Field->setAccess(AS_public);
10108 VaListDecl->addDecl(Field);
10109
10110 // };
10111 VaListDecl->completeDefinition();
10112 Context->VaListTagDecl = VaListDecl;
10113
10114 // typedef struct __va_list __builtin_va_list;
10115 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10116 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10117}
10118
10119static TypedefDecl *
10121 // struct __va_list_tag {
10123 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10124 VaListTagDecl->startDefinition();
10125
10126 const size_t NumFields = 4;
10127 QualType FieldTypes[NumFields];
10128 const char *FieldNames[NumFields];
10129
10130 // long __gpr;
10131 FieldTypes[0] = Context->LongTy;
10132 FieldNames[0] = "__gpr";
10133
10134 // long __fpr;
10135 FieldTypes[1] = Context->LongTy;
10136 FieldNames[1] = "__fpr";
10137
10138 // void *__overflow_arg_area;
10139 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10140 FieldNames[2] = "__overflow_arg_area";
10141
10142 // void *__reg_save_area;
10143 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10144 FieldNames[3] = "__reg_save_area";
10145
10146 // Create fields
10147 for (unsigned i = 0; i < NumFields; ++i) {
10148 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10152 &Context->Idents.get(FieldNames[i]),
10153 FieldTypes[i], /*TInfo=*/nullptr,
10154 /*BitWidth=*/nullptr,
10155 /*Mutable=*/false,
10156 ICIS_NoInit);
10157 Field->setAccess(AS_public);
10158 VaListTagDecl->addDecl(Field);
10159 }
10160 VaListTagDecl->completeDefinition();
10161 Context->VaListTagDecl = VaListTagDecl;
10162 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10163
10164 // };
10165
10166 // typedef __va_list_tag __builtin_va_list[1];
10167 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10168 QualType VaListTagArrayType = Context->getConstantArrayType(
10169 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10170
10171 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10172}
10173
10175 // typedef struct __va_list_tag {
10177 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10178 VaListTagDecl->startDefinition();
10179
10180 const size_t NumFields = 3;
10181 QualType FieldTypes[NumFields];
10182 const char *FieldNames[NumFields];
10183
10184 // void *CurrentSavedRegisterArea;
10185 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10186 FieldNames[0] = "__current_saved_reg_area_pointer";
10187
10188 // void *SavedRegAreaEnd;
10189 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10190 FieldNames[1] = "__saved_reg_area_end_pointer";
10191
10192 // void *OverflowArea;
10193 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10194 FieldNames[2] = "__overflow_area_pointer";
10195
10196 // Create fields
10197 for (unsigned i = 0; i < NumFields; ++i) {
10199 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10200 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10201 /*TInfo=*/nullptr,
10202 /*BitWidth=*/nullptr,
10203 /*Mutable=*/false, ICIS_NoInit);
10204 Field->setAccess(AS_public);
10205 VaListTagDecl->addDecl(Field);
10206 }
10207 VaListTagDecl->completeDefinition();
10208 Context->VaListTagDecl = VaListTagDecl;
10209 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10210
10211 // } __va_list_tag;
10212 TypedefDecl *VaListTagTypedefDecl =
10213 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10214
10215 QualType VaListTagTypedefType =
10216 Context->getTypedefType(ElaboratedTypeKeyword::None,
10217 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10218
10219 // typedef __va_list_tag __builtin_va_list[1];
10220 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10221 QualType VaListTagArrayType = Context->getConstantArrayType(
10222 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10223
10224 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10225}
10226
10227static TypedefDecl *
10229 // typedef struct __va_list_tag {
10230 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10231
10232 VaListTagDecl->startDefinition();
10233
10234 // int* __va_stk;
10235 // int* __va_reg;
10236 // int __va_ndx;
10237 constexpr size_t NumFields = 3;
10238 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10239 Context->getPointerType(Context->IntTy),
10240 Context->IntTy};
10241 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10242
10243 // Create fields
10244 for (unsigned i = 0; i < NumFields; ++i) {
10247 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10248 /*BitWidth=*/nullptr,
10249 /*Mutable=*/false, ICIS_NoInit);
10250 Field->setAccess(AS_public);
10251 VaListTagDecl->addDecl(Field);
10252 }
10253 VaListTagDecl->completeDefinition();
10254 Context->VaListTagDecl = VaListTagDecl;
10255 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10256
10257 // } __va_list_tag;
10258 TypedefDecl *VaListTagTypedefDecl =
10259 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10260
10261 return VaListTagTypedefDecl;
10262}
10263
10266 switch (Kind) {
10268 return CreateCharPtrBuiltinVaListDecl(Context);
10270 return CreateVoidPtrBuiltinVaListDecl(Context);
10272 return CreateAArch64ABIBuiltinVaListDecl(Context);
10274 return CreatePowerABIBuiltinVaListDecl(Context);
10276 return CreateX86_64ABIBuiltinVaListDecl(Context);
10278 return CreateAAPCSABIBuiltinVaListDecl(Context);
10280 return CreateSystemZBuiltinVaListDecl(Context);
10282 return CreateHexagonBuiltinVaListDecl(Context);
10284 return CreateXtensaABIBuiltinVaListDecl(Context);
10285 }
10286
10287 llvm_unreachable("Unhandled __builtin_va_list type kind");
10288}
10289
10291 if (!BuiltinVaListDecl) {
10292 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10293 assert(BuiltinVaListDecl->isImplicit());
10294 }
10295
10296 return BuiltinVaListDecl;
10297}
10298
10300 // Force the creation of VaListTagDecl by building the __builtin_va_list
10301 // declaration.
10302 if (!VaListTagDecl)
10303 (void)getBuiltinVaListDecl();
10304
10305 return VaListTagDecl;
10306}
10307
10309 if (!BuiltinMSVaListDecl)
10310 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10311
10312 return BuiltinMSVaListDecl;
10313}
10314
10316 // Allow redecl custom type checking builtin for HLSL.
10317 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10318 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10319 return true;
10320 // Allow redecl custom type checking builtin for SPIR-V.
10321 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10322 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10323 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10324 return true;
10325 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10326}
10327
10329 assert(ObjCConstantStringType.isNull() &&
10330 "'NSConstantString' type already set!");
10331
10332 ObjCConstantStringType = getObjCInterfaceType(Decl);
10333}
10334
10335/// Retrieve the template name that corresponds to a non-empty
10336/// lookup.
10339 UnresolvedSetIterator End) const {
10340 unsigned size = End - Begin;
10341 assert(size > 1 && "set is not overloaded!");
10342
10343 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10344 size * sizeof(FunctionTemplateDecl*));
10345 auto *OT = new (memory) OverloadedTemplateStorage(size);
10346
10347 NamedDecl **Storage = OT->getStorage();
10348 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10349 NamedDecl *D = *I;
10350 assert(isa<FunctionTemplateDecl>(D) ||
10354 *Storage++ = D;
10355 }
10356
10357 return TemplateName(OT);
10358}
10359
10360/// Retrieve a template name representing an unqualified-id that has been
10361/// assumed to name a template for ADL purposes.
10363 auto *OT = new (*this) AssumedTemplateStorage(Name);
10364 return TemplateName(OT);
10365}
10366
10367/// Retrieve the template name that represents a qualified
10368/// template name such as \c std::vector.
10370 bool TemplateKeyword,
10371 TemplateName Template) const {
10372 assert(Template.getKind() == TemplateName::Template ||
10374
10375 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10376 assert(!Qualifier && "unexpected qualified template template parameter");
10377 assert(TemplateKeyword == false);
10378 return Template;
10379 }
10380
10381 // FIXME: Canonicalization?
10382 llvm::FoldingSetNodeID ID;
10383 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10384
10385 void *InsertPos = nullptr;
10387 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10388 if (!QTN) {
10389 QTN = new (*this, alignof(QualifiedTemplateName))
10390 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10391 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10392 }
10393
10394 return TemplateName(QTN);
10395}
10396
10397/// Retrieve the template name that represents a dependent
10398/// template name such as \c MetaFun::template operator+.
10401 llvm::FoldingSetNodeID ID;
10402 S.Profile(ID);
10403
10404 void *InsertPos = nullptr;
10405 if (DependentTemplateName *QTN =
10406 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10407 return TemplateName(QTN);
10408
10410 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10411 DependentTemplateNames.InsertNode(QTN, InsertPos);
10412 return TemplateName(QTN);
10413}
10414
10416 Decl *AssociatedDecl,
10417 unsigned Index,
10418 UnsignedOrNone PackIndex,
10419 bool Final) const {
10420 llvm::FoldingSetNodeID ID;
10421 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10422 Index, PackIndex, Final);
10423
10424 void *insertPos = nullptr;
10426 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10427
10428 if (!subst) {
10429 subst = new (*this) SubstTemplateTemplateParmStorage(
10430 Replacement, AssociatedDecl, Index, PackIndex, Final);
10431 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10432 }
10433
10434 return TemplateName(subst);
10435}
10436
10439 Decl *AssociatedDecl,
10440 unsigned Index, bool Final) const {
10441 auto &Self = const_cast<ASTContext &>(*this);
10442 llvm::FoldingSetNodeID ID;
10444 AssociatedDecl, Index, Final);
10445
10446 void *InsertPos = nullptr;
10448 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10449
10450 if (!Subst) {
10451 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10452 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10453 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10454 }
10455
10456 return TemplateName(Subst);
10457}
10458
10459/// Retrieve the template name that represents a template name
10460/// deduced from a specialization.
10463 DefaultArguments DefaultArgs) const {
10464 if (!DefaultArgs)
10465 return Underlying;
10466
10467 llvm::FoldingSetNodeID ID;
10468 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10469
10470 void *InsertPos = nullptr;
10472 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10473 if (!DTS) {
10474 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10475 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10476 alignof(DeducedTemplateStorage));
10477 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10478 DeducedTemplates.InsertNode(DTS, InsertPos);
10479 }
10480 return TemplateName(DTS);
10481}
10482
10483/// getFromTargetType - Given one of the integer types provided by
10484/// TargetInfo, produce the corresponding type. The unsigned @p Type
10485/// is actually a value of type @c TargetInfo::IntType.
10486CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10487 switch (Type) {
10488 case TargetInfo::NoInt: return {};
10491 case TargetInfo::SignedShort: return ShortTy;
10493 case TargetInfo::SignedInt: return IntTy;
10495 case TargetInfo::SignedLong: return LongTy;
10499 }
10500
10501 llvm_unreachable("Unhandled TargetInfo::IntType value");
10502}
10503
10504//===----------------------------------------------------------------------===//
10505// Type Predicates.
10506//===----------------------------------------------------------------------===//
10507
10508/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10509/// garbage collection attribute.
10510///
10512 if (getLangOpts().getGC() == LangOptions::NonGC)
10513 return Qualifiers::GCNone;
10514
10515 assert(getLangOpts().ObjC);
10516 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10517
10518 // Default behaviour under objective-C's gc is for ObjC pointers
10519 // (or pointers to them) be treated as though they were declared
10520 // as __strong.
10521 if (GCAttrs == Qualifiers::GCNone) {
10523 return Qualifiers::Strong;
10524 else if (Ty->isPointerType())
10526 } else {
10527 // It's not valid to set GC attributes on anything that isn't a
10528 // pointer.
10529#ifndef NDEBUG
10531 while (const auto *AT = dyn_cast<ArrayType>(CT))
10532 CT = AT->getElementType();
10533 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10534#endif
10535 }
10536 return GCAttrs;
10537}
10538
10539//===----------------------------------------------------------------------===//
10540// Type Compatibility Testing
10541//===----------------------------------------------------------------------===//
10542
10543/// areCompatVectorTypes - Return true if the two specified vector types are
10544/// compatible.
10545static bool areCompatVectorTypes(const VectorType *LHS,
10546 const VectorType *RHS) {
10547 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10548 return LHS->getElementType() == RHS->getElementType() &&
10549 LHS->getNumElements() == RHS->getNumElements();
10550}
10551
10552/// areCompatMatrixTypes - Return true if the two specified matrix types are
10553/// compatible.
10555 const ConstantMatrixType *RHS) {
10556 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10557 return LHS->getElementType() == RHS->getElementType() &&
10558 LHS->getNumRows() == RHS->getNumRows() &&
10559 LHS->getNumColumns() == RHS->getNumColumns();
10560}
10561
10563 QualType SecondVec) {
10564 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10565 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10566
10567 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10568 return true;
10569
10570 // Treat Neon vector types and most AltiVec vector types as if they are the
10571 // equivalent GCC vector types.
10572 const auto *First = FirstVec->castAs<VectorType>();
10573 const auto *Second = SecondVec->castAs<VectorType>();
10574 if (First->getNumElements() == Second->getNumElements() &&
10575 hasSameType(First->getElementType(), Second->getElementType()) &&
10576 First->getVectorKind() != VectorKind::AltiVecPixel &&
10577 First->getVectorKind() != VectorKind::AltiVecBool &&
10580 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10581 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10584 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10586 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10588 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10590 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10592 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10594 return true;
10595
10596 return false;
10597}
10598
10599/// getRVVTypeSize - Return RVV vector register size.
10600static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10601 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10602 auto VScale = Context.getTargetInfo().getVScaleRange(
10603 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10604 if (!VScale)
10605 return 0;
10606
10607 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10608
10609 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10610 if (Info.ElementType == Context.BoolTy)
10611 EltSize = 1;
10612
10613 uint64_t MinElts = Info.EC.getKnownMinValue();
10614 return VScale->first * MinElts * EltSize;
10615}
10616
10618 QualType SecondType) {
10619 assert(
10620 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10621 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10622 "Expected RVV builtin type and vector type!");
10623
10624 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10625 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10626 if (const auto *VT = SecondType->getAs<VectorType>()) {
10627 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10629 return FirstType->isRVVVLSBuiltinType() &&
10630 Info.ElementType == BoolTy &&
10631 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10632 }
10633 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10635 return FirstType->isRVVVLSBuiltinType() &&
10636 Info.ElementType == BoolTy &&
10637 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10638 }
10639 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10641 return FirstType->isRVVVLSBuiltinType() &&
10642 Info.ElementType == BoolTy &&
10643 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10644 }
10645 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10647 return FirstType->isRVVVLSBuiltinType() &&
10648 Info.ElementType == BoolTy &&
10649 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10650 }
10651 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10652 VT->getVectorKind() == VectorKind::Generic)
10653 return FirstType->isRVVVLSBuiltinType() &&
10654 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10655 hasSameType(VT->getElementType(),
10656 getBuiltinVectorTypeInfo(BT).ElementType);
10657 }
10658 }
10659 return false;
10660 };
10661
10662 return IsValidCast(FirstType, SecondType) ||
10663 IsValidCast(SecondType, FirstType);
10664}
10665
10667 QualType SecondType) {
10668 assert(
10669 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10670 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10671 "Expected RVV builtin type and vector type!");
10672
10673 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10674 const auto *BT = FirstType->getAs<BuiltinType>();
10675 if (!BT)
10676 return false;
10677
10678 if (!BT->isRVVVLSBuiltinType())
10679 return false;
10680
10681 const auto *VecTy = SecondType->getAs<VectorType>();
10682 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10684 getLangOpts().getLaxVectorConversions();
10685
10686 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10687 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10688 return false;
10689
10690 // If -flax-vector-conversions=all is specified, the types are
10691 // certainly compatible.
10693 return true;
10694
10695 // If -flax-vector-conversions=integer is specified, the types are
10696 // compatible if the elements are integer types.
10698 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10699 FirstType->getRVVEltType(*this)->isIntegerType();
10700 }
10701
10702 return false;
10703 };
10704
10705 return IsLaxCompatible(FirstType, SecondType) ||
10706 IsLaxCompatible(SecondType, FirstType);
10707}
10708
10710 while (true) {
10711 // __strong id
10712 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10713 if (Attr->getAttrKind() == attr::ObjCOwnership)
10714 return true;
10715
10716 Ty = Attr->getModifiedType();
10717
10718 // X *__strong (...)
10719 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10720 Ty = Paren->getInnerType();
10721
10722 // We do not want to look through typedefs, typeof(expr),
10723 // typeof(type), or any other way that the type is somehow
10724 // abstracted.
10725 } else {
10726 return false;
10727 }
10728 }
10729}
10730
10731//===----------------------------------------------------------------------===//
10732// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10733//===----------------------------------------------------------------------===//
10734
10735/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10736/// inheritance hierarchy of 'rProto'.
10737bool
10739 ObjCProtocolDecl *rProto) const {
10740 if (declaresSameEntity(lProto, rProto))
10741 return true;
10742 for (auto *PI : rProto->protocols())
10743 if (ProtocolCompatibleWithProtocol(lProto, PI))
10744 return true;
10745 return false;
10746}
10747
10748/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10749/// Class<pr1, ...>.
10751 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10752 for (auto *lhsProto : lhs->quals()) {
10753 bool match = false;
10754 for (auto *rhsProto : rhs->quals()) {
10755 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10756 match = true;
10757 break;
10758 }
10759 }
10760 if (!match)
10761 return false;
10762 }
10763 return true;
10764}
10765
10766/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10767/// ObjCQualifiedIDType.
10769 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10770 bool compare) {
10771 // Allow id<P..> and an 'id' in all cases.
10772 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10773 return true;
10774
10775 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10776 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10778 return false;
10779
10780 if (lhs->isObjCQualifiedIdType()) {
10781 if (rhs->qual_empty()) {
10782 // If the RHS is a unqualified interface pointer "NSString*",
10783 // make sure we check the class hierarchy.
10784 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10785 for (auto *I : lhs->quals()) {
10786 // when comparing an id<P> on lhs with a static type on rhs,
10787 // see if static class implements all of id's protocols, directly or
10788 // through its super class and categories.
10789 if (!rhsID->ClassImplementsProtocol(I, true))
10790 return false;
10791 }
10792 }
10793 // If there are no qualifiers and no interface, we have an 'id'.
10794 return true;
10795 }
10796 // Both the right and left sides have qualifiers.
10797 for (auto *lhsProto : lhs->quals()) {
10798 bool match = false;
10799
10800 // when comparing an id<P> on lhs with a static type on rhs,
10801 // see if static class implements all of id's protocols, directly or
10802 // through its super class and categories.
10803 for (auto *rhsProto : rhs->quals()) {
10804 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10805 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10806 match = true;
10807 break;
10808 }
10809 }
10810 // If the RHS is a qualified interface pointer "NSString<P>*",
10811 // make sure we check the class hierarchy.
10812 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10813 for (auto *I : lhs->quals()) {
10814 // when comparing an id<P> on lhs with a static type on rhs,
10815 // see if static class implements all of id's protocols, directly or
10816 // through its super class and categories.
10817 if (rhsID->ClassImplementsProtocol(I, true)) {
10818 match = true;
10819 break;
10820 }
10821 }
10822 }
10823 if (!match)
10824 return false;
10825 }
10826
10827 return true;
10828 }
10829
10830 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10831
10832 if (lhs->getInterfaceType()) {
10833 // If both the right and left sides have qualifiers.
10834 for (auto *lhsProto : lhs->quals()) {
10835 bool match = false;
10836
10837 // when comparing an id<P> on rhs with a static type on lhs,
10838 // see if static class implements all of id's protocols, directly or
10839 // through its super class and categories.
10840 // First, lhs protocols in the qualifier list must be found, direct
10841 // or indirect in rhs's qualifier list or it is a mismatch.
10842 for (auto *rhsProto : rhs->quals()) {
10843 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10844 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10845 match = true;
10846 break;
10847 }
10848 }
10849 if (!match)
10850 return false;
10851 }
10852
10853 // Static class's protocols, or its super class or category protocols
10854 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
10855 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
10856 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
10857 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
10858 // This is rather dubious but matches gcc's behavior. If lhs has
10859 // no type qualifier and its class has no static protocol(s)
10860 // assume that it is mismatch.
10861 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
10862 return false;
10863 for (auto *lhsProto : LHSInheritedProtocols) {
10864 bool match = false;
10865 for (auto *rhsProto : rhs->quals()) {
10866 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10867 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10868 match = true;
10869 break;
10870 }
10871 }
10872 if (!match)
10873 return false;
10874 }
10875 }
10876 return true;
10877 }
10878 return false;
10879}
10880
10881/// canAssignObjCInterfaces - Return true if the two interface types are
10882/// compatible for assignment from RHS to LHS. This handles validation of any
10883/// protocol qualifiers on the LHS or RHS.
10885 const ObjCObjectPointerType *RHSOPT) {
10886 const ObjCObjectType* LHS = LHSOPT->getObjectType();
10887 const ObjCObjectType* RHS = RHSOPT->getObjectType();
10888
10889 // If either type represents the built-in 'id' type, return true.
10890 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
10891 return true;
10892
10893 // Function object that propagates a successful result or handles
10894 // __kindof types.
10895 auto finish = [&](bool succeeded) -> bool {
10896 if (succeeded)
10897 return true;
10898
10899 if (!RHS->isKindOfType())
10900 return false;
10901
10902 // Strip off __kindof and protocol qualifiers, then check whether
10903 // we can assign the other way.
10905 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
10906 };
10907
10908 // Casts from or to id<P> are allowed when the other side has compatible
10909 // protocols.
10910 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
10911 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
10912 }
10913
10914 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
10915 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
10916 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
10917 }
10918
10919 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
10920 if (LHS->isObjCClass() && RHS->isObjCClass()) {
10921 return true;
10922 }
10923
10924 // If we have 2 user-defined types, fall into that path.
10925 if (LHS->getInterface() && RHS->getInterface()) {
10926 return finish(canAssignObjCInterfaces(LHS, RHS));
10927 }
10928
10929 return false;
10930}
10931
10932/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
10933/// for providing type-safety for objective-c pointers used to pass/return
10934/// arguments in block literals. When passed as arguments, passing 'A*' where
10935/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
10936/// not OK. For the return type, the opposite is not OK.
10938 const ObjCObjectPointerType *LHSOPT,
10939 const ObjCObjectPointerType *RHSOPT,
10940 bool BlockReturnType) {
10941
10942 // Function object that propagates a successful result or handles
10943 // __kindof types.
10944 auto finish = [&](bool succeeded) -> bool {
10945 if (succeeded)
10946 return true;
10947
10948 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
10949 if (!Expected->isKindOfType())
10950 return false;
10951
10952 // Strip off __kindof and protocol qualifiers, then check whether
10953 // we can assign the other way.
10955 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
10956 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
10957 BlockReturnType);
10958 };
10959
10960 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
10961 return true;
10962
10963 if (LHSOPT->isObjCBuiltinType()) {
10964 return finish(RHSOPT->isObjCBuiltinType() ||
10965 RHSOPT->isObjCQualifiedIdType());
10966 }
10967
10968 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
10969 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
10970 // Use for block parameters previous type checking for compatibility.
10971 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
10972 // Or corrected type checking as in non-compat mode.
10973 (!BlockReturnType &&
10974 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
10975 else
10977 (BlockReturnType ? LHSOPT : RHSOPT),
10978 (BlockReturnType ? RHSOPT : LHSOPT), false));
10979 }
10980
10981 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
10982 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
10983 if (LHS && RHS) { // We have 2 user-defined types.
10984 if (LHS != RHS) {
10985 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
10986 return finish(BlockReturnType);
10987 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
10988 return finish(!BlockReturnType);
10989 }
10990 else
10991 return true;
10992 }
10993 return false;
10994}
10995
10996/// Comparison routine for Objective-C protocols to be used with
10997/// llvm::array_pod_sort.
10999 ObjCProtocolDecl * const *rhs) {
11000 return (*lhs)->getName().compare((*rhs)->getName());
11001}
11002
11003/// getIntersectionOfProtocols - This routine finds the intersection of set
11004/// of protocols inherited from two distinct objective-c pointer objects with
11005/// the given common base.
11006/// It is used to build composite qualifier list of the composite type of
11007/// the conditional expression involving two objective-c pointer objects.
11008static
11010 const ObjCInterfaceDecl *CommonBase,
11011 const ObjCObjectPointerType *LHSOPT,
11012 const ObjCObjectPointerType *RHSOPT,
11013 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11014
11015 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11016 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11017 assert(LHS->getInterface() && "LHS must have an interface base");
11018 assert(RHS->getInterface() && "RHS must have an interface base");
11019
11020 // Add all of the protocols for the LHS.
11022
11023 // Start with the protocol qualifiers.
11024 for (auto *proto : LHS->quals()) {
11025 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11026 }
11027
11028 // Also add the protocols associated with the LHS interface.
11029 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11030
11031 // Add all of the protocols for the RHS.
11033
11034 // Start with the protocol qualifiers.
11035 for (auto *proto : RHS->quals()) {
11036 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11037 }
11038
11039 // Also add the protocols associated with the RHS interface.
11040 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11041
11042 // Compute the intersection of the collected protocol sets.
11043 for (auto *proto : LHSProtocolSet) {
11044 if (RHSProtocolSet.count(proto))
11045 IntersectionSet.push_back(proto);
11046 }
11047
11048 // Compute the set of protocols that is implied by either the common type or
11049 // the protocols within the intersection.
11051 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11052
11053 // Remove any implied protocols from the list of inherited protocols.
11054 if (!ImpliedProtocols.empty()) {
11055 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11056 return ImpliedProtocols.contains(proto);
11057 });
11058 }
11059
11060 // Sort the remaining protocols by name.
11061 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11063}
11064
11065/// Determine whether the first type is a subtype of the second.
11067 QualType rhs) {
11068 // Common case: two object pointers.
11069 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11070 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11071 if (lhsOPT && rhsOPT)
11072 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11073
11074 // Two block pointers.
11075 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11076 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11077 if (lhsBlock && rhsBlock)
11078 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11079
11080 // If either is an unqualified 'id' and the other is a block, it's
11081 // acceptable.
11082 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11083 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11084 return true;
11085
11086 return false;
11087}
11088
11089// Check that the given Objective-C type argument lists are equivalent.
11091 const ObjCInterfaceDecl *iface,
11092 ArrayRef<QualType> lhsArgs,
11093 ArrayRef<QualType> rhsArgs,
11094 bool stripKindOf) {
11095 if (lhsArgs.size() != rhsArgs.size())
11096 return false;
11097
11098 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11099 if (!typeParams)
11100 return false;
11101
11102 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11103 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11104 continue;
11105
11106 switch (typeParams->begin()[i]->getVariance()) {
11108 if (!stripKindOf ||
11109 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11110 rhsArgs[i].stripObjCKindOfType(ctx))) {
11111 return false;
11112 }
11113 break;
11114
11116 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11117 return false;
11118 break;
11119
11121 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11122 return false;
11123 break;
11124 }
11125 }
11126
11127 return true;
11128}
11129
11131 const ObjCObjectPointerType *Lptr,
11132 const ObjCObjectPointerType *Rptr) {
11133 const ObjCObjectType *LHS = Lptr->getObjectType();
11134 const ObjCObjectType *RHS = Rptr->getObjectType();
11135 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11136 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11137
11138 if (!LDecl || !RDecl)
11139 return {};
11140
11141 // When either LHS or RHS is a kindof type, we should return a kindof type.
11142 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11143 // kindof(A).
11144 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11145
11146 // Follow the left-hand side up the class hierarchy until we either hit a
11147 // root or find the RHS. Record the ancestors in case we don't find it.
11148 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11149 LHSAncestors;
11150 while (true) {
11151 // Record this ancestor. We'll need this if the common type isn't in the
11152 // path from the LHS to the root.
11153 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11154
11155 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11156 // Get the type arguments.
11157 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11158 bool anyChanges = false;
11159 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11160 // Both have type arguments, compare them.
11161 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11162 LHS->getTypeArgs(), RHS->getTypeArgs(),
11163 /*stripKindOf=*/true))
11164 return {};
11165 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11166 // If only one has type arguments, the result will not have type
11167 // arguments.
11168 LHSTypeArgs = {};
11169 anyChanges = true;
11170 }
11171
11172 // Compute the intersection of protocols.
11174 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11175 Protocols);
11176 if (!Protocols.empty())
11177 anyChanges = true;
11178
11179 // If anything in the LHS will have changed, build a new result type.
11180 // If we need to return a kindof type but LHS is not a kindof type, we
11181 // build a new result type.
11182 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11183 QualType Result = getObjCInterfaceType(LHS->getInterface());
11184 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11185 anyKindOf || LHS->isKindOfType());
11187 }
11188
11189 return getObjCObjectPointerType(QualType(LHS, 0));
11190 }
11191
11192 // Find the superclass.
11193 QualType LHSSuperType = LHS->getSuperClassType();
11194 if (LHSSuperType.isNull())
11195 break;
11196
11197 LHS = LHSSuperType->castAs<ObjCObjectType>();
11198 }
11199
11200 // We didn't find anything by following the LHS to its root; now check
11201 // the RHS against the cached set of ancestors.
11202 while (true) {
11203 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11204 if (KnownLHS != LHSAncestors.end()) {
11205 LHS = KnownLHS->second;
11206
11207 // Get the type arguments.
11208 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11209 bool anyChanges = false;
11210 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11211 // Both have type arguments, compare them.
11212 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11213 LHS->getTypeArgs(), RHS->getTypeArgs(),
11214 /*stripKindOf=*/true))
11215 return {};
11216 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11217 // If only one has type arguments, the result will not have type
11218 // arguments.
11219 RHSTypeArgs = {};
11220 anyChanges = true;
11221 }
11222
11223 // Compute the intersection of protocols.
11225 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11226 Protocols);
11227 if (!Protocols.empty())
11228 anyChanges = true;
11229
11230 // If we need to return a kindof type but RHS is not a kindof type, we
11231 // build a new result type.
11232 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11233 QualType Result = getObjCInterfaceType(RHS->getInterface());
11234 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11235 anyKindOf || RHS->isKindOfType());
11237 }
11238
11239 return getObjCObjectPointerType(QualType(RHS, 0));
11240 }
11241
11242 // Find the superclass of the RHS.
11243 QualType RHSSuperType = RHS->getSuperClassType();
11244 if (RHSSuperType.isNull())
11245 break;
11246
11247 RHS = RHSSuperType->castAs<ObjCObjectType>();
11248 }
11249
11250 return {};
11251}
11252
11254 const ObjCObjectType *RHS) {
11255 assert(LHS->getInterface() && "LHS is not an interface type");
11256 assert(RHS->getInterface() && "RHS is not an interface type");
11257
11258 // Verify that the base decls are compatible: the RHS must be a subclass of
11259 // the LHS.
11260 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11261 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11262 if (!IsSuperClass)
11263 return false;
11264
11265 // If the LHS has protocol qualifiers, determine whether all of them are
11266 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11267 // LHS).
11268 if (LHS->getNumProtocols() > 0) {
11269 // OK if conversion of LHS to SuperClass results in narrowing of types
11270 // ; i.e., SuperClass may implement at least one of the protocols
11271 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11272 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11273 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11274 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11275 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11276 // qualifiers.
11277 for (auto *RHSPI : RHS->quals())
11278 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11279 // If there is no protocols associated with RHS, it is not a match.
11280 if (SuperClassInheritedProtocols.empty())
11281 return false;
11282
11283 for (const auto *LHSProto : LHS->quals()) {
11284 bool SuperImplementsProtocol = false;
11285 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11286 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11287 SuperImplementsProtocol = true;
11288 break;
11289 }
11290 if (!SuperImplementsProtocol)
11291 return false;
11292 }
11293 }
11294
11295 // If the LHS is specialized, we may need to check type arguments.
11296 if (LHS->isSpecialized()) {
11297 // Follow the superclass chain until we've matched the LHS class in the
11298 // hierarchy. This substitutes type arguments through.
11299 const ObjCObjectType *RHSSuper = RHS;
11300 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11301 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11302
11303 // If the RHS is specializd, compare type arguments.
11304 if (RHSSuper->isSpecialized() &&
11305 !sameObjCTypeArgs(*this, LHS->getInterface(),
11306 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11307 /*stripKindOf=*/true)) {
11308 return false;
11309 }
11310 }
11311
11312 return true;
11313}
11314
11316 // get the "pointed to" types
11317 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11318 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11319
11320 if (!LHSOPT || !RHSOPT)
11321 return false;
11322
11323 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11324 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11325}
11326
11329 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11330 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11331}
11332
11333/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11334/// both shall have the identically qualified version of a compatible type.
11335/// C99 6.2.7p1: Two types have compatible types if their types are the
11336/// same. See 6.7.[2,3,5] for additional rules.
11338 bool CompareUnqualified) {
11339 if (getLangOpts().CPlusPlus)
11340 return hasSameType(LHS, RHS);
11341
11342 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11343}
11344
11346 return typesAreCompatible(LHS, RHS);
11347}
11348
11350 return !mergeTypes(LHS, RHS, true).isNull();
11351}
11352
11353/// mergeTransparentUnionType - if T is a transparent union type and a member
11354/// of T is compatible with SubType, return the merged type, else return
11355/// QualType()
11357 bool OfBlockPointer,
11358 bool Unqualified) {
11359 if (const RecordType *UT = T->getAsUnionType()) {
11360 RecordDecl *UD = UT->getOriginalDecl()->getMostRecentDecl();
11361 if (UD->hasAttr<TransparentUnionAttr>()) {
11362 for (const auto *I : UD->fields()) {
11363 QualType ET = I->getType().getUnqualifiedType();
11364 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11365 if (!MT.isNull())
11366 return MT;
11367 }
11368 }
11369 }
11370
11371 return {};
11372}
11373
11374/// mergeFunctionParameterTypes - merge two types which appear as function
11375/// parameter types
11377 bool OfBlockPointer,
11378 bool Unqualified) {
11379 // GNU extension: two types are compatible if they appear as a function
11380 // argument, one of the types is a transparent union type and the other
11381 // type is compatible with a union member
11382 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11383 Unqualified);
11384 if (!lmerge.isNull())
11385 return lmerge;
11386
11387 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11388 Unqualified);
11389 if (!rmerge.isNull())
11390 return rmerge;
11391
11392 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11393}
11394
11396 bool OfBlockPointer, bool Unqualified,
11397 bool AllowCXX,
11398 bool IsConditionalOperator) {
11399 const auto *lbase = lhs->castAs<FunctionType>();
11400 const auto *rbase = rhs->castAs<FunctionType>();
11401 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11402 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11403 bool allLTypes = true;
11404 bool allRTypes = true;
11405
11406 // Check return type
11407 QualType retType;
11408 if (OfBlockPointer) {
11409 QualType RHS = rbase->getReturnType();
11410 QualType LHS = lbase->getReturnType();
11411 bool UnqualifiedResult = Unqualified;
11412 if (!UnqualifiedResult)
11413 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11414 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11415 }
11416 else
11417 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11418 Unqualified);
11419 if (retType.isNull())
11420 return {};
11421
11422 if (Unqualified)
11423 retType = retType.getUnqualifiedType();
11424
11425 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11426 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11427 if (Unqualified) {
11428 LRetType = LRetType.getUnqualifiedType();
11429 RRetType = RRetType.getUnqualifiedType();
11430 }
11431
11432 if (getCanonicalType(retType) != LRetType)
11433 allLTypes = false;
11434 if (getCanonicalType(retType) != RRetType)
11435 allRTypes = false;
11436
11437 // FIXME: double check this
11438 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11439 // rbase->getRegParmAttr() != 0 &&
11440 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11441 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11442 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11443
11444 // Compatible functions must have compatible calling conventions
11445 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11446 return {};
11447
11448 // Regparm is part of the calling convention.
11449 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11450 return {};
11451 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11452 return {};
11453
11454 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11455 return {};
11456 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11457 return {};
11458 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11459 return {};
11460
11461 // When merging declarations, it's common for supplemental information like
11462 // attributes to only be present in one of the declarations, and we generally
11463 // want type merging to preserve the union of information. So a merged
11464 // function type should be noreturn if it was noreturn in *either* operand
11465 // type.
11466 //
11467 // But for the conditional operator, this is backwards. The result of the
11468 // operator could be either operand, and its type should conservatively
11469 // reflect that. So a function type in a composite type is noreturn only
11470 // if it's noreturn in *both* operand types.
11471 //
11472 // Arguably, noreturn is a kind of subtype, and the conditional operator
11473 // ought to produce the most specific common supertype of its operand types.
11474 // That would differ from this rule in contravariant positions. However,
11475 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11476 // as a practical matter, it would only affect C code that does abstraction of
11477 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11478 // say the least. So we use the simpler rule.
11479 bool NoReturn = IsConditionalOperator
11480 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11481 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11482 if (lbaseInfo.getNoReturn() != NoReturn)
11483 allLTypes = false;
11484 if (rbaseInfo.getNoReturn() != NoReturn)
11485 allRTypes = false;
11486
11487 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11488
11489 std::optional<FunctionEffectSet> MergedFX;
11490
11491 if (lproto && rproto) { // two C99 style function prototypes
11492 assert((AllowCXX ||
11493 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11494 "C++ shouldn't be here");
11495 // Compatible functions must have the same number of parameters
11496 if (lproto->getNumParams() != rproto->getNumParams())
11497 return {};
11498
11499 // Variadic and non-variadic functions aren't compatible
11500 if (lproto->isVariadic() != rproto->isVariadic())
11501 return {};
11502
11503 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11504 return {};
11505
11506 // Function protos with different 'cfi_salt' values aren't compatible.
11507 if (lproto->getExtraAttributeInfo().CFISalt !=
11508 rproto->getExtraAttributeInfo().CFISalt)
11509 return {};
11510
11511 // Function effects are handled similarly to noreturn, see above.
11512 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11513 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11514 if (LHSFX != RHSFX) {
11515 if (IsConditionalOperator)
11516 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11517 else {
11519 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11520 // Here we're discarding a possible error due to conflicts in the effect
11521 // sets. But we're not in a context where we can report it. The
11522 // operation does however guarantee maintenance of invariants.
11523 }
11524 if (*MergedFX != LHSFX)
11525 allLTypes = false;
11526 if (*MergedFX != RHSFX)
11527 allRTypes = false;
11528 }
11529
11531 bool canUseLeft, canUseRight;
11532 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11533 newParamInfos))
11534 return {};
11535
11536 if (!canUseLeft)
11537 allLTypes = false;
11538 if (!canUseRight)
11539 allRTypes = false;
11540
11541 // Check parameter type compatibility
11543 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11544 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11545 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11547 lParamType, rParamType, OfBlockPointer, Unqualified);
11548 if (paramType.isNull())
11549 return {};
11550
11551 if (Unqualified)
11552 paramType = paramType.getUnqualifiedType();
11553
11554 types.push_back(paramType);
11555 if (Unqualified) {
11556 lParamType = lParamType.getUnqualifiedType();
11557 rParamType = rParamType.getUnqualifiedType();
11558 }
11559
11560 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11561 allLTypes = false;
11562 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11563 allRTypes = false;
11564 }
11565
11566 if (allLTypes) return lhs;
11567 if (allRTypes) return rhs;
11568
11569 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11570 EPI.ExtInfo = einfo;
11571 EPI.ExtParameterInfos =
11572 newParamInfos.empty() ? nullptr : newParamInfos.data();
11573 if (MergedFX)
11574 EPI.FunctionEffects = *MergedFX;
11575 return getFunctionType(retType, types, EPI);
11576 }
11577
11578 if (lproto) allRTypes = false;
11579 if (rproto) allLTypes = false;
11580
11581 const FunctionProtoType *proto = lproto ? lproto : rproto;
11582 if (proto) {
11583 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11584 if (proto->isVariadic())
11585 return {};
11586 // Check that the types are compatible with the types that
11587 // would result from default argument promotions (C99 6.7.5.3p15).
11588 // The only types actually affected are promotable integer
11589 // types and floats, which would be passed as a different
11590 // type depending on whether the prototype is visible.
11591 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11592 QualType paramTy = proto->getParamType(i);
11593
11594 // Look at the converted type of enum types, since that is the type used
11595 // to pass enum values.
11596 if (const auto *ED = paramTy->getAsEnumDecl()) {
11597 paramTy = ED->getIntegerType();
11598 if (paramTy.isNull())
11599 return {};
11600 }
11601
11602 if (isPromotableIntegerType(paramTy) ||
11603 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11604 return {};
11605 }
11606
11607 if (allLTypes) return lhs;
11608 if (allRTypes) return rhs;
11609
11611 EPI.ExtInfo = einfo;
11612 if (MergedFX)
11613 EPI.FunctionEffects = *MergedFX;
11614 return getFunctionType(retType, proto->getParamTypes(), EPI);
11615 }
11616
11617 if (allLTypes) return lhs;
11618 if (allRTypes) return rhs;
11619 return getFunctionNoProtoType(retType, einfo);
11620}
11621
11622/// Given that we have an enum type and a non-enum type, try to merge them.
11623static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11624 QualType other, bool isBlockReturnType) {
11625 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11626 // a signed integer type, or an unsigned integer type.
11627 // Compatibility is based on the underlying type, not the promotion
11628 // type.
11629 QualType underlyingType =
11630 ET->getOriginalDecl()->getDefinitionOrSelf()->getIntegerType();
11631 if (underlyingType.isNull())
11632 return {};
11633 if (Context.hasSameType(underlyingType, other))
11634 return other;
11635
11636 // In block return types, we're more permissive and accept any
11637 // integral type of the same size.
11638 if (isBlockReturnType && other->isIntegerType() &&
11639 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11640 return other;
11641
11642 return {};
11643}
11644
11646 // C17 and earlier and C++ disallow two tag definitions within the same TU
11647 // from being compatible.
11648 if (LangOpts.CPlusPlus || !LangOpts.C23)
11649 return {};
11650
11651 // C23, on the other hand, requires the members to be "the same enough", so
11652 // we use a structural equivalence check.
11655 getLangOpts(), *this, *this, NonEquivalentDecls,
11656 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11657 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11658 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11659}
11660
11661QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11662 bool Unqualified, bool BlockReturnType,
11663 bool IsConditionalOperator) {
11664 // For C++ we will not reach this code with reference types (see below),
11665 // for OpenMP variant call overloading we might.
11666 //
11667 // C++ [expr]: If an expression initially has the type "reference to T", the
11668 // type is adjusted to "T" prior to any further analysis, the expression
11669 // designates the object or function denoted by the reference, and the
11670 // expression is an lvalue unless the reference is an rvalue reference and
11671 // the expression is a function call (possibly inside parentheses).
11672 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11673 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11674 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11675 LHS->getTypeClass() == RHS->getTypeClass())
11676 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11677 OfBlockPointer, Unqualified, BlockReturnType);
11678 if (LHSRefTy || RHSRefTy)
11679 return {};
11680
11681 if (Unqualified) {
11682 LHS = LHS.getUnqualifiedType();
11683 RHS = RHS.getUnqualifiedType();
11684 }
11685
11686 QualType LHSCan = getCanonicalType(LHS),
11687 RHSCan = getCanonicalType(RHS);
11688
11689 // If two types are identical, they are compatible.
11690 if (LHSCan == RHSCan)
11691 return LHS;
11692
11693 // If the qualifiers are different, the types aren't compatible... mostly.
11694 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11695 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11696 if (LQuals != RQuals) {
11697 // If any of these qualifiers are different, we have a type
11698 // mismatch.
11699 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11700 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11701 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11702 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11703 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11704 return {};
11705
11706 // Exactly one GC qualifier difference is allowed: __strong is
11707 // okay if the other type has no GC qualifier but is an Objective
11708 // C object pointer (i.e. implicitly strong by default). We fix
11709 // this by pretending that the unqualified type was actually
11710 // qualified __strong.
11711 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11712 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11713 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11714
11715 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11716 return {};
11717
11718 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11720 }
11721 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11723 }
11724 return {};
11725 }
11726
11727 // Okay, qualifiers are equal.
11728
11729 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11730 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11731
11732 // We want to consider the two function types to be the same for these
11733 // comparisons, just force one to the other.
11734 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11735 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11736
11737 // Same as above for arrays
11738 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11739 LHSClass = Type::ConstantArray;
11740 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11741 RHSClass = Type::ConstantArray;
11742
11743 // ObjCInterfaces are just specialized ObjCObjects.
11744 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11745 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11746
11747 // Canonicalize ExtVector -> Vector.
11748 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11749 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11750
11751 // If the canonical type classes don't match.
11752 if (LHSClass != RHSClass) {
11753 // Note that we only have special rules for turning block enum
11754 // returns into block int returns, not vice-versa.
11755 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11756 return mergeEnumWithInteger(*this, ETy, RHS, false);
11757 }
11758 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11759 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11760 }
11761 // allow block pointer type to match an 'id' type.
11762 if (OfBlockPointer && !BlockReturnType) {
11763 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11764 return LHS;
11765 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11766 return RHS;
11767 }
11768 // Allow __auto_type to match anything; it merges to the type with more
11769 // information.
11770 if (const auto *AT = LHS->getAs<AutoType>()) {
11771 if (!AT->isDeduced() && AT->isGNUAutoType())
11772 return RHS;
11773 }
11774 if (const auto *AT = RHS->getAs<AutoType>()) {
11775 if (!AT->isDeduced() && AT->isGNUAutoType())
11776 return LHS;
11777 }
11778 return {};
11779 }
11780
11781 // The canonical type classes match.
11782 switch (LHSClass) {
11783#define TYPE(Class, Base)
11784#define ABSTRACT_TYPE(Class, Base)
11785#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11786#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11787#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11788#include "clang/AST/TypeNodes.inc"
11789 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11790
11791 case Type::Auto:
11792 case Type::DeducedTemplateSpecialization:
11793 case Type::LValueReference:
11794 case Type::RValueReference:
11795 case Type::MemberPointer:
11796 llvm_unreachable("C++ should never be in mergeTypes");
11797
11798 case Type::ObjCInterface:
11799 case Type::IncompleteArray:
11800 case Type::VariableArray:
11801 case Type::FunctionProto:
11802 case Type::ExtVector:
11803 llvm_unreachable("Types are eliminated above");
11804
11805 case Type::Pointer:
11806 {
11807 // Merge two pointer types, while trying to preserve typedef info
11808 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
11809 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
11810 if (Unqualified) {
11811 LHSPointee = LHSPointee.getUnqualifiedType();
11812 RHSPointee = RHSPointee.getUnqualifiedType();
11813 }
11814 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
11815 Unqualified);
11816 if (ResultType.isNull())
11817 return {};
11818 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11819 return LHS;
11820 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11821 return RHS;
11822 return getPointerType(ResultType);
11823 }
11824 case Type::BlockPointer:
11825 {
11826 // Merge two block pointer types, while trying to preserve typedef info
11827 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
11828 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
11829 if (Unqualified) {
11830 LHSPointee = LHSPointee.getUnqualifiedType();
11831 RHSPointee = RHSPointee.getUnqualifiedType();
11832 }
11833 if (getLangOpts().OpenCL) {
11834 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
11835 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
11836 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
11837 // 6.12.5) thus the following check is asymmetric.
11838 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
11839 return {};
11840 LHSPteeQual.removeAddressSpace();
11841 RHSPteeQual.removeAddressSpace();
11842 LHSPointee =
11843 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
11844 RHSPointee =
11845 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
11846 }
11847 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
11848 Unqualified);
11849 if (ResultType.isNull())
11850 return {};
11851 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
11852 return LHS;
11853 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
11854 return RHS;
11855 return getBlockPointerType(ResultType);
11856 }
11857 case Type::Atomic:
11858 {
11859 // Merge two pointer types, while trying to preserve typedef info
11860 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
11861 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
11862 if (Unqualified) {
11863 LHSValue = LHSValue.getUnqualifiedType();
11864 RHSValue = RHSValue.getUnqualifiedType();
11865 }
11866 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
11867 Unqualified);
11868 if (ResultType.isNull())
11869 return {};
11870 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
11871 return LHS;
11872 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
11873 return RHS;
11874 return getAtomicType(ResultType);
11875 }
11876 case Type::ConstantArray:
11877 {
11878 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
11879 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
11880 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
11881 return {};
11882
11883 QualType LHSElem = getAsArrayType(LHS)->getElementType();
11884 QualType RHSElem = getAsArrayType(RHS)->getElementType();
11885 if (Unqualified) {
11886 LHSElem = LHSElem.getUnqualifiedType();
11887 RHSElem = RHSElem.getUnqualifiedType();
11888 }
11889
11890 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
11891 if (ResultType.isNull())
11892 return {};
11893
11894 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
11895 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
11896
11897 // If either side is a variable array, and both are complete, check whether
11898 // the current dimension is definite.
11899 if (LVAT || RVAT) {
11900 auto SizeFetch = [this](const VariableArrayType* VAT,
11901 const ConstantArrayType* CAT)
11902 -> std::pair<bool,llvm::APInt> {
11903 if (VAT) {
11904 std::optional<llvm::APSInt> TheInt;
11905 Expr *E = VAT->getSizeExpr();
11906 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
11907 return std::make_pair(true, *TheInt);
11908 return std::make_pair(false, llvm::APSInt());
11909 }
11910 if (CAT)
11911 return std::make_pair(true, CAT->getSize());
11912 return std::make_pair(false, llvm::APInt());
11913 };
11914
11915 bool HaveLSize, HaveRSize;
11916 llvm::APInt LSize, RSize;
11917 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
11918 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
11919 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
11920 return {}; // Definite, but unequal, array dimension
11921 }
11922
11923 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11924 return LHS;
11925 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11926 return RHS;
11927 if (LCAT)
11928 return getConstantArrayType(ResultType, LCAT->getSize(),
11929 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
11930 if (RCAT)
11931 return getConstantArrayType(ResultType, RCAT->getSize(),
11932 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
11933 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
11934 return LHS;
11935 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
11936 return RHS;
11937 if (LVAT) {
11938 // FIXME: This isn't correct! But tricky to implement because
11939 // the array's size has to be the size of LHS, but the type
11940 // has to be different.
11941 return LHS;
11942 }
11943 if (RVAT) {
11944 // FIXME: This isn't correct! But tricky to implement because
11945 // the array's size has to be the size of RHS, but the type
11946 // has to be different.
11947 return RHS;
11948 }
11949 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
11950 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
11951 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
11952 }
11953 case Type::FunctionNoProto:
11954 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
11955 /*AllowCXX=*/false, IsConditionalOperator);
11956 case Type::Record:
11957 case Type::Enum:
11958 return mergeTagDefinitions(LHS, RHS);
11959 case Type::Builtin:
11960 // Only exactly equal builtin types are compatible, which is tested above.
11961 return {};
11962 case Type::Complex:
11963 // Distinct complex types are incompatible.
11964 return {};
11965 case Type::Vector:
11966 // FIXME: The merged type should be an ExtVector!
11967 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
11968 RHSCan->castAs<VectorType>()))
11969 return LHS;
11970 return {};
11971 case Type::ConstantMatrix:
11973 RHSCan->castAs<ConstantMatrixType>()))
11974 return LHS;
11975 return {};
11976 case Type::ObjCObject: {
11977 // Check if the types are assignment compatible.
11978 // FIXME: This should be type compatibility, e.g. whether
11979 // "LHS x; RHS x;" at global scope is legal.
11981 RHS->castAs<ObjCObjectType>()))
11982 return LHS;
11983 return {};
11984 }
11985 case Type::ObjCObjectPointer:
11986 if (OfBlockPointer) {
11989 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
11990 return LHS;
11991 return {};
11992 }
11995 return LHS;
11996 return {};
11997 case Type::Pipe:
11998 assert(LHS != RHS &&
11999 "Equivalent pipe types should have already been handled!");
12000 return {};
12001 case Type::ArrayParameter:
12002 assert(LHS != RHS &&
12003 "Equivalent ArrayParameter types should have already been handled!");
12004 return {};
12005 case Type::BitInt: {
12006 // Merge two bit-precise int types, while trying to preserve typedef info.
12007 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12008 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12009 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12010 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12011
12012 // Like unsigned/int, shouldn't have a type if they don't match.
12013 if (LHSUnsigned != RHSUnsigned)
12014 return {};
12015
12016 if (LHSBits != RHSBits)
12017 return {};
12018 return LHS;
12019 }
12020 case Type::HLSLAttributedResource: {
12021 const HLSLAttributedResourceType *LHSTy =
12022 LHS->castAs<HLSLAttributedResourceType>();
12023 const HLSLAttributedResourceType *RHSTy =
12024 RHS->castAs<HLSLAttributedResourceType>();
12025 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12026 LHSTy->getWrappedType()->isHLSLResourceType() &&
12027 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12028
12029 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12030 LHSTy->getContainedType() == RHSTy->getContainedType())
12031 return LHS;
12032 return {};
12033 }
12034 case Type::HLSLInlineSpirv:
12035 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12036 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12037
12038 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12039 LHSTy->getSize() == RHSTy->getSize() &&
12040 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12041 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12042 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12043 return {};
12044
12045 return LHS;
12046 }
12047 return {};
12048 }
12049
12050 llvm_unreachable("Invalid Type::Class!");
12051}
12052
12054 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12055 bool &CanUseFirst, bool &CanUseSecond,
12057 assert(NewParamInfos.empty() && "param info list not empty");
12058 CanUseFirst = CanUseSecond = true;
12059 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12060 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12061
12062 // Fast path: if the first type doesn't have ext parameter infos,
12063 // we match if and only if the second type also doesn't have them.
12064 if (!FirstHasInfo && !SecondHasInfo)
12065 return true;
12066
12067 bool NeedParamInfo = false;
12068 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12069 : SecondFnType->getExtParameterInfos().size();
12070
12071 for (size_t I = 0; I < E; ++I) {
12072 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12073 if (FirstHasInfo)
12074 FirstParam = FirstFnType->getExtParameterInfo(I);
12075 if (SecondHasInfo)
12076 SecondParam = SecondFnType->getExtParameterInfo(I);
12077
12078 // Cannot merge unless everything except the noescape flag matches.
12079 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12080 return false;
12081
12082 bool FirstNoEscape = FirstParam.isNoEscape();
12083 bool SecondNoEscape = SecondParam.isNoEscape();
12084 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12085 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12086 if (NewParamInfos.back().getOpaqueValue())
12087 NeedParamInfo = true;
12088 if (FirstNoEscape != IsNoEscape)
12089 CanUseFirst = false;
12090 if (SecondNoEscape != IsNoEscape)
12091 CanUseSecond = false;
12092 }
12093
12094 if (!NeedParamInfo)
12095 NewParamInfos.clear();
12096
12097 return true;
12098}
12099
12101 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12102 It->second = nullptr;
12103 for (auto *SubClass : ObjCSubClasses[D])
12104 ResetObjCLayout(SubClass);
12105 }
12106}
12107
12108/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12109/// 'RHS' attributes and returns the merged version; including for function
12110/// return types.
12112 QualType LHSCan = getCanonicalType(LHS),
12113 RHSCan = getCanonicalType(RHS);
12114 // If two types are identical, they are compatible.
12115 if (LHSCan == RHSCan)
12116 return LHS;
12117 if (RHSCan->isFunctionType()) {
12118 if (!LHSCan->isFunctionType())
12119 return {};
12120 QualType OldReturnType =
12121 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12122 QualType NewReturnType =
12123 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12124 QualType ResReturnType =
12125 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12126 if (ResReturnType.isNull())
12127 return {};
12128 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12129 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12130 // In either case, use OldReturnType to build the new function type.
12131 const auto *F = LHS->castAs<FunctionType>();
12132 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12133 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12134 EPI.ExtInfo = getFunctionExtInfo(LHS);
12135 QualType ResultType =
12136 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12137 return ResultType;
12138 }
12139 }
12140 return {};
12141 }
12142
12143 // If the qualifiers are different, the types can still be merged.
12144 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12145 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12146 if (LQuals != RQuals) {
12147 // If any of these qualifiers are different, we have a type mismatch.
12148 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12149 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12150 return {};
12151
12152 // Exactly one GC qualifier difference is allowed: __strong is
12153 // okay if the other type has no GC qualifier but is an Objective
12154 // C object pointer (i.e. implicitly strong by default). We fix
12155 // this by pretending that the unqualified type was actually
12156 // qualified __strong.
12157 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12158 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12159 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12160
12161 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12162 return {};
12163
12164 if (GC_L == Qualifiers::Strong)
12165 return LHS;
12166 if (GC_R == Qualifiers::Strong)
12167 return RHS;
12168 return {};
12169 }
12170
12171 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12172 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12173 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12174 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12175 if (ResQT == LHSBaseQT)
12176 return LHS;
12177 if (ResQT == RHSBaseQT)
12178 return RHS;
12179 }
12180 return {};
12181}
12182
12183//===----------------------------------------------------------------------===//
12184// Integer Predicates
12185//===----------------------------------------------------------------------===//
12186
12188 if (const auto *ED = T->getAsEnumDecl())
12189 T = ED->getIntegerType();
12190 if (T->isBooleanType())
12191 return 1;
12192 if (const auto *EIT = T->getAs<BitIntType>())
12193 return EIT->getNumBits();
12194 // For builtin types, just use the standard type sizing method
12195 return (unsigned)getTypeSize(T);
12196}
12197
12199 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12200 T->isFixedPointType()) &&
12201 "Unexpected type");
12202
12203 // Turn <4 x signed int> -> <4 x unsigned int>
12204 if (const auto *VTy = T->getAs<VectorType>())
12205 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12206 VTy->getNumElements(), VTy->getVectorKind());
12207
12208 // For _BitInt, return an unsigned _BitInt with same width.
12209 if (const auto *EITy = T->getAs<BitIntType>())
12210 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12211
12212 // For enums, get the underlying integer type of the enum, and let the general
12213 // integer type signchanging code handle it.
12214 if (const auto *ED = T->getAsEnumDecl())
12215 T = ED->getIntegerType();
12216
12217 switch (T->castAs<BuiltinType>()->getKind()) {
12218 case BuiltinType::Char_U:
12219 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12220 case BuiltinType::Char_S:
12221 case BuiltinType::SChar:
12222 case BuiltinType::Char8:
12223 return UnsignedCharTy;
12224 case BuiltinType::Short:
12225 return UnsignedShortTy;
12226 case BuiltinType::Int:
12227 return UnsignedIntTy;
12228 case BuiltinType::Long:
12229 return UnsignedLongTy;
12230 case BuiltinType::LongLong:
12231 return UnsignedLongLongTy;
12232 case BuiltinType::Int128:
12233 return UnsignedInt128Ty;
12234 // wchar_t is special. It is either signed or not, but when it's signed,
12235 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12236 // version of its underlying type instead.
12237 case BuiltinType::WChar_S:
12238 return getUnsignedWCharType();
12239
12240 case BuiltinType::ShortAccum:
12241 return UnsignedShortAccumTy;
12242 case BuiltinType::Accum:
12243 return UnsignedAccumTy;
12244 case BuiltinType::LongAccum:
12245 return UnsignedLongAccumTy;
12246 case BuiltinType::SatShortAccum:
12248 case BuiltinType::SatAccum:
12249 return SatUnsignedAccumTy;
12250 case BuiltinType::SatLongAccum:
12252 case BuiltinType::ShortFract:
12253 return UnsignedShortFractTy;
12254 case BuiltinType::Fract:
12255 return UnsignedFractTy;
12256 case BuiltinType::LongFract:
12257 return UnsignedLongFractTy;
12258 case BuiltinType::SatShortFract:
12260 case BuiltinType::SatFract:
12261 return SatUnsignedFractTy;
12262 case BuiltinType::SatLongFract:
12264 default:
12265 assert((T->hasUnsignedIntegerRepresentation() ||
12266 T->isUnsignedFixedPointType()) &&
12267 "Unexpected signed integer or fixed point type");
12268 return T;
12269 }
12270}
12271
12273 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12274 T->isFixedPointType()) &&
12275 "Unexpected type");
12276
12277 // Turn <4 x unsigned int> -> <4 x signed int>
12278 if (const auto *VTy = T->getAs<VectorType>())
12279 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12280 VTy->getNumElements(), VTy->getVectorKind());
12281
12282 // For _BitInt, return a signed _BitInt with same width.
12283 if (const auto *EITy = T->getAs<BitIntType>())
12284 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12285
12286 // For enums, get the underlying integer type of the enum, and let the general
12287 // integer type signchanging code handle it.
12288 if (const auto *ED = T->getAsEnumDecl())
12289 T = ED->getIntegerType();
12290
12291 switch (T->castAs<BuiltinType>()->getKind()) {
12292 case BuiltinType::Char_S:
12293 // Plain `char` is mapped to `signed char` even if it's already signed
12294 case BuiltinType::Char_U:
12295 case BuiltinType::UChar:
12296 case BuiltinType::Char8:
12297 return SignedCharTy;
12298 case BuiltinType::UShort:
12299 return ShortTy;
12300 case BuiltinType::UInt:
12301 return IntTy;
12302 case BuiltinType::ULong:
12303 return LongTy;
12304 case BuiltinType::ULongLong:
12305 return LongLongTy;
12306 case BuiltinType::UInt128:
12307 return Int128Ty;
12308 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12309 // there's no matching "signed wchar_t". Therefore we return the signed
12310 // version of its underlying type instead.
12311 case BuiltinType::WChar_U:
12312 return getSignedWCharType();
12313
12314 case BuiltinType::UShortAccum:
12315 return ShortAccumTy;
12316 case BuiltinType::UAccum:
12317 return AccumTy;
12318 case BuiltinType::ULongAccum:
12319 return LongAccumTy;
12320 case BuiltinType::SatUShortAccum:
12321 return SatShortAccumTy;
12322 case BuiltinType::SatUAccum:
12323 return SatAccumTy;
12324 case BuiltinType::SatULongAccum:
12325 return SatLongAccumTy;
12326 case BuiltinType::UShortFract:
12327 return ShortFractTy;
12328 case BuiltinType::UFract:
12329 return FractTy;
12330 case BuiltinType::ULongFract:
12331 return LongFractTy;
12332 case BuiltinType::SatUShortFract:
12333 return SatShortFractTy;
12334 case BuiltinType::SatUFract:
12335 return SatFractTy;
12336 case BuiltinType::SatULongFract:
12337 return SatLongFractTy;
12338 default:
12339 assert(
12340 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12341 "Unexpected signed integer or fixed point type");
12342 return T;
12343 }
12344}
12345
12347
12350
12351//===----------------------------------------------------------------------===//
12352// Builtin Type Computation
12353//===----------------------------------------------------------------------===//
12354
12355/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12356/// pointer over the consumed characters. This returns the resultant type. If
12357/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12358/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12359/// a vector of "i*".
12360///
12361/// RequiresICE is filled in on return to indicate whether the value is required
12362/// to be an Integer Constant Expression.
12363static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12365 bool &RequiresICE,
12366 bool AllowTypeModifiers) {
12367 // Modifiers.
12368 int HowLong = 0;
12369 bool Signed = false, Unsigned = false;
12370 RequiresICE = false;
12371
12372 // Read the prefixed modifiers first.
12373 bool Done = false;
12374 #ifndef NDEBUG
12375 bool IsSpecial = false;
12376 #endif
12377 while (!Done) {
12378 switch (*Str++) {
12379 default: Done = true; --Str; break;
12380 case 'I':
12381 RequiresICE = true;
12382 break;
12383 case 'S':
12384 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12385 assert(!Signed && "Can't use 'S' modifier multiple times!");
12386 Signed = true;
12387 break;
12388 case 'U':
12389 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12390 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12391 Unsigned = true;
12392 break;
12393 case 'L':
12394 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
12395 assert(HowLong <= 2 && "Can't have LLLL modifier");
12396 ++HowLong;
12397 break;
12398 case 'N':
12399 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12400 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12401 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12402 #ifndef NDEBUG
12403 IsSpecial = true;
12404 #endif
12405 if (Context.getTargetInfo().getLongWidth() == 32)
12406 ++HowLong;
12407 break;
12408 case 'W':
12409 // This modifier represents int64 type.
12410 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12411 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12412 #ifndef NDEBUG
12413 IsSpecial = true;
12414 #endif
12415 switch (Context.getTargetInfo().getInt64Type()) {
12416 default:
12417 llvm_unreachable("Unexpected integer type");
12419 HowLong = 1;
12420 break;
12422 HowLong = 2;
12423 break;
12424 }
12425 break;
12426 case 'Z':
12427 // This modifier represents int32 type.
12428 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12429 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12430 #ifndef NDEBUG
12431 IsSpecial = true;
12432 #endif
12433 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12434 default:
12435 llvm_unreachable("Unexpected integer type");
12437 HowLong = 0;
12438 break;
12440 HowLong = 1;
12441 break;
12443 HowLong = 2;
12444 break;
12445 }
12446 break;
12447 case 'O':
12448 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12449 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12450 #ifndef NDEBUG
12451 IsSpecial = true;
12452 #endif
12453 if (Context.getLangOpts().OpenCL)
12454 HowLong = 1;
12455 else
12456 HowLong = 2;
12457 break;
12458 }
12459 }
12460
12461 QualType Type;
12462
12463 // Read the base type.
12464 switch (*Str++) {
12465 default: llvm_unreachable("Unknown builtin type letter!");
12466 case 'x':
12467 assert(HowLong == 0 && !Signed && !Unsigned &&
12468 "Bad modifiers used with 'x'!");
12469 Type = Context.Float16Ty;
12470 break;
12471 case 'y':
12472 assert(HowLong == 0 && !Signed && !Unsigned &&
12473 "Bad modifiers used with 'y'!");
12474 Type = Context.BFloat16Ty;
12475 break;
12476 case 'v':
12477 assert(HowLong == 0 && !Signed && !Unsigned &&
12478 "Bad modifiers used with 'v'!");
12479 Type = Context.VoidTy;
12480 break;
12481 case 'h':
12482 assert(HowLong == 0 && !Signed && !Unsigned &&
12483 "Bad modifiers used with 'h'!");
12484 Type = Context.HalfTy;
12485 break;
12486 case 'f':
12487 assert(HowLong == 0 && !Signed && !Unsigned &&
12488 "Bad modifiers used with 'f'!");
12489 Type = Context.FloatTy;
12490 break;
12491 case 'd':
12492 assert(HowLong < 3 && !Signed && !Unsigned &&
12493 "Bad modifiers used with 'd'!");
12494 if (HowLong == 1)
12495 Type = Context.LongDoubleTy;
12496 else if (HowLong == 2)
12497 Type = Context.Float128Ty;
12498 else
12499 Type = Context.DoubleTy;
12500 break;
12501 case 's':
12502 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12503 if (Unsigned)
12504 Type = Context.UnsignedShortTy;
12505 else
12506 Type = Context.ShortTy;
12507 break;
12508 case 'i':
12509 if (HowLong == 3)
12510 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12511 else if (HowLong == 2)
12512 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12513 else if (HowLong == 1)
12514 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12515 else
12516 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12517 break;
12518 case 'c':
12519 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12520 if (Signed)
12521 Type = Context.SignedCharTy;
12522 else if (Unsigned)
12523 Type = Context.UnsignedCharTy;
12524 else
12525 Type = Context.CharTy;
12526 break;
12527 case 'b': // boolean
12528 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12529 Type = Context.BoolTy;
12530 break;
12531 case 'z': // size_t.
12532 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12533 Type = Context.getSizeType();
12534 break;
12535 case 'w': // wchar_t.
12536 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12537 Type = Context.getWideCharType();
12538 break;
12539 case 'F':
12540 Type = Context.getCFConstantStringType();
12541 break;
12542 case 'G':
12543 Type = Context.getObjCIdType();
12544 break;
12545 case 'H':
12546 Type = Context.getObjCSelType();
12547 break;
12548 case 'M':
12549 Type = Context.getObjCSuperType();
12550 break;
12551 case 'a':
12552 Type = Context.getBuiltinVaListType();
12553 assert(!Type.isNull() && "builtin va list type not initialized!");
12554 break;
12555 case 'A':
12556 // This is a "reference" to a va_list; however, what exactly
12557 // this means depends on how va_list is defined. There are two
12558 // different kinds of va_list: ones passed by value, and ones
12559 // passed by reference. An example of a by-value va_list is
12560 // x86, where va_list is a char*. An example of by-ref va_list
12561 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12562 // we want this argument to be a char*&; for x86-64, we want
12563 // it to be a __va_list_tag*.
12564 Type = Context.getBuiltinVaListType();
12565 assert(!Type.isNull() && "builtin va list type not initialized!");
12566 if (Type->isArrayType())
12567 Type = Context.getArrayDecayedType(Type);
12568 else
12569 Type = Context.getLValueReferenceType(Type);
12570 break;
12571 case 'q': {
12572 char *End;
12573 unsigned NumElements = strtoul(Str, &End, 10);
12574 assert(End != Str && "Missing vector size");
12575 Str = End;
12576
12577 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12578 RequiresICE, false);
12579 assert(!RequiresICE && "Can't require vector ICE");
12580
12581 Type = Context.getScalableVectorType(ElementType, NumElements);
12582 break;
12583 }
12584 case 'Q': {
12585 switch (*Str++) {
12586 case 'a': {
12587 Type = Context.SveCountTy;
12588 break;
12589 }
12590 case 'b': {
12591 Type = Context.AMDGPUBufferRsrcTy;
12592 break;
12593 }
12594 case 't': {
12595 Type = Context.AMDGPUTextureTy;
12596 break;
12597 }
12598 default:
12599 llvm_unreachable("Unexpected target builtin type");
12600 }
12601 break;
12602 }
12603 case 'V': {
12604 char *End;
12605 unsigned NumElements = strtoul(Str, &End, 10);
12606 assert(End != Str && "Missing vector size");
12607 Str = End;
12608
12609 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12610 RequiresICE, false);
12611 assert(!RequiresICE && "Can't require vector ICE");
12612
12613 // TODO: No way to make AltiVec vectors in builtins yet.
12614 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12615 break;
12616 }
12617 case 'E': {
12618 char *End;
12619
12620 unsigned NumElements = strtoul(Str, &End, 10);
12621 assert(End != Str && "Missing vector size");
12622
12623 Str = End;
12624
12625 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12626 false);
12627 Type = Context.getExtVectorType(ElementType, NumElements);
12628 break;
12629 }
12630 case 'X': {
12631 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12632 false);
12633 assert(!RequiresICE && "Can't require complex ICE");
12634 Type = Context.getComplexType(ElementType);
12635 break;
12636 }
12637 case 'Y':
12638 Type = Context.getPointerDiffType();
12639 break;
12640 case 'P':
12641 Type = Context.getFILEType();
12642 if (Type.isNull()) {
12644 return {};
12645 }
12646 break;
12647 case 'J':
12648 if (Signed)
12649 Type = Context.getsigjmp_bufType();
12650 else
12651 Type = Context.getjmp_bufType();
12652
12653 if (Type.isNull()) {
12655 return {};
12656 }
12657 break;
12658 case 'K':
12659 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12660 Type = Context.getucontext_tType();
12661
12662 if (Type.isNull()) {
12664 return {};
12665 }
12666 break;
12667 case 'p':
12668 Type = Context.getProcessIDType();
12669 break;
12670 case 'm':
12671 Type = Context.MFloat8Ty;
12672 break;
12673 }
12674
12675 // If there are modifiers and if we're allowed to parse them, go for it.
12676 Done = !AllowTypeModifiers;
12677 while (!Done) {
12678 switch (char c = *Str++) {
12679 default: Done = true; --Str; break;
12680 case '*':
12681 case '&': {
12682 // Both pointers and references can have their pointee types
12683 // qualified with an address space.
12684 char *End;
12685 unsigned AddrSpace = strtoul(Str, &End, 10);
12686 if (End != Str) {
12687 // Note AddrSpace == 0 is not the same as an unspecified address space.
12688 Type = Context.getAddrSpaceQualType(
12689 Type,
12690 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12691 Str = End;
12692 }
12693 if (c == '*')
12694 Type = Context.getPointerType(Type);
12695 else
12696 Type = Context.getLValueReferenceType(Type);
12697 break;
12698 }
12699 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12700 case 'C':
12701 Type = Type.withConst();
12702 break;
12703 case 'D':
12704 Type = Context.getVolatileType(Type);
12705 break;
12706 case 'R':
12707 Type = Type.withRestrict();
12708 break;
12709 }
12710 }
12711
12712 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12713 "Integer constant 'I' type must be an integer");
12714
12715 return Type;
12716}
12717
12718// On some targets such as PowerPC, some of the builtins are defined with custom
12719// type descriptors for target-dependent types. These descriptors are decoded in
12720// other functions, but it may be useful to be able to fall back to default
12721// descriptor decoding to define builtins mixing target-dependent and target-
12722// independent types. This function allows decoding one type descriptor with
12723// default decoding.
12724QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12725 GetBuiltinTypeError &Error, bool &RequireICE,
12726 bool AllowTypeModifiers) const {
12727 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12728}
12729
12730/// GetBuiltinType - Return the type for the specified builtin.
12733 unsigned *IntegerConstantArgs) const {
12734 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12735 if (TypeStr[0] == '\0') {
12737 return {};
12738 }
12739
12740 SmallVector<QualType, 8> ArgTypes;
12741
12742 bool RequiresICE = false;
12743 Error = GE_None;
12744 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12745 RequiresICE, true);
12746 if (Error != GE_None)
12747 return {};
12748
12749 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
12750
12751 while (TypeStr[0] && TypeStr[0] != '.') {
12752 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
12753 if (Error != GE_None)
12754 return {};
12755
12756 // If this argument is required to be an IntegerConstantExpression and the
12757 // caller cares, fill in the bitmask we return.
12758 if (RequiresICE && IntegerConstantArgs)
12759 *IntegerConstantArgs |= 1 << ArgTypes.size();
12760
12761 // Do array -> pointer decay. The builtin should use the decayed type.
12762 if (Ty->isArrayType())
12763 Ty = getArrayDecayedType(Ty);
12764
12765 ArgTypes.push_back(Ty);
12766 }
12767
12768 if (Id == Builtin::BI__GetExceptionInfo)
12769 return {};
12770
12771 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
12772 "'.' should only occur at end of builtin type list!");
12773
12774 bool Variadic = (TypeStr[0] == '.');
12775
12776 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
12777 if (BuiltinInfo.isNoReturn(Id))
12778 EI = EI.withNoReturn(true);
12779
12780 // We really shouldn't be making a no-proto type here.
12781 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
12782 return getFunctionNoProtoType(ResType, EI);
12783
12785 EPI.ExtInfo = EI;
12786 EPI.Variadic = Variadic;
12787 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
12788 EPI.ExceptionSpec.Type =
12790
12791 return getFunctionType(ResType, ArgTypes, EPI);
12792}
12793
12795 const FunctionDecl *FD) {
12796 if (!FD->isExternallyVisible())
12797 return GVA_Internal;
12798
12799 // Non-user-provided functions get emitted as weak definitions with every
12800 // use, no matter whether they've been explicitly instantiated etc.
12801 if (!FD->isUserProvided())
12802 return GVA_DiscardableODR;
12803
12805 switch (FD->getTemplateSpecializationKind()) {
12806 case TSK_Undeclared:
12809 break;
12810
12812 return GVA_StrongODR;
12813
12814 // C++11 [temp.explicit]p10:
12815 // [ Note: The intent is that an inline function that is the subject of
12816 // an explicit instantiation declaration will still be implicitly
12817 // instantiated when used so that the body can be considered for
12818 // inlining, but that no out-of-line copy of the inline function would be
12819 // generated in the translation unit. -- end note ]
12822
12825 break;
12826 }
12827
12828 if (!FD->isInlined())
12829 return External;
12830
12831 if ((!Context.getLangOpts().CPlusPlus &&
12832 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12833 !FD->hasAttr<DLLExportAttr>()) ||
12834 FD->hasAttr<GNUInlineAttr>()) {
12835 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
12836
12837 // GNU or C99 inline semantics. Determine whether this symbol should be
12838 // externally visible.
12840 return External;
12841
12842 // C99 inline semantics, where the symbol is not externally visible.
12844 }
12845
12846 // Functions specified with extern and inline in -fms-compatibility mode
12847 // forcibly get emitted. While the body of the function cannot be later
12848 // replaced, the function definition cannot be discarded.
12849 if (FD->isMSExternInline())
12850 return GVA_StrongODR;
12851
12852 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12854 cast<CXXConstructorDecl>(FD)->isInheritingConstructor())
12855 // Our approach to inheriting constructors is fundamentally different from
12856 // that used by the MS ABI, so keep our inheriting constructor thunks
12857 // internal rather than trying to pick an unambiguous mangling for them.
12858 return GVA_Internal;
12859
12860 return GVA_DiscardableODR;
12861}
12862
12864 const Decl *D, GVALinkage L) {
12865 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
12866 // dllexport/dllimport on inline functions.
12867 if (D->hasAttr<DLLImportAttr>()) {
12868 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
12870 } else if (D->hasAttr<DLLExportAttr>()) {
12871 if (L == GVA_DiscardableODR)
12872 return GVA_StrongODR;
12873 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
12874 // Device-side functions with __global__ attribute must always be
12875 // visible externally so they can be launched from host.
12876 if (D->hasAttr<CUDAGlobalAttr>() &&
12877 (L == GVA_DiscardableODR || L == GVA_Internal))
12878 return GVA_StrongODR;
12879 // Single source offloading languages like CUDA/HIP need to be able to
12880 // access static device variables from host code of the same compilation
12881 // unit. This is done by externalizing the static variable with a shared
12882 // name between the host and device compilation which is the same for the
12883 // same compilation unit whereas different among different compilation
12884 // units.
12885 if (Context.shouldExternalize(D))
12886 return GVA_StrongExternal;
12887 }
12888 return L;
12889}
12890
12891/// Adjust the GVALinkage for a declaration based on what an external AST source
12892/// knows about whether there can be other definitions of this declaration.
12893static GVALinkage
12895 GVALinkage L) {
12896 ExternalASTSource *Source = Ctx.getExternalSource();
12897 if (!Source)
12898 return L;
12899
12900 switch (Source->hasExternalDefinitions(D)) {
12902 // Other translation units rely on us to provide the definition.
12903 if (L == GVA_DiscardableODR)
12904 return GVA_StrongODR;
12905 break;
12906
12909
12911 break;
12912 }
12913 return L;
12914}
12915
12921
12923 const VarDecl *VD) {
12924 // As an extension for interactive REPLs, make sure constant variables are
12925 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
12926 // marking them as internal.
12927 if (Context.getLangOpts().CPlusPlus &&
12928 Context.getLangOpts().IncrementalExtensions &&
12929 VD->getType().isConstQualified() &&
12930 !VD->getType().isVolatileQualified() && !VD->isInline() &&
12932 return GVA_DiscardableODR;
12933
12934 if (!VD->isExternallyVisible())
12935 return GVA_Internal;
12936
12937 if (VD->isStaticLocal()) {
12938 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
12939 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
12940 LexicalContext = LexicalContext->getLexicalParent();
12941
12942 // ObjC Blocks can create local variables that don't have a FunctionDecl
12943 // LexicalContext.
12944 if (!LexicalContext)
12945 return GVA_DiscardableODR;
12946
12947 // Otherwise, let the static local variable inherit its linkage from the
12948 // nearest enclosing function.
12949 auto StaticLocalLinkage =
12950 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
12951
12952 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
12953 // be emitted in any object with references to the symbol for the object it
12954 // contains, whether inline or out-of-line."
12955 // Similar behavior is observed with MSVC. An alternative ABI could use
12956 // StrongODR/AvailableExternally to match the function, but none are
12957 // known/supported currently.
12958 if (StaticLocalLinkage == GVA_StrongODR ||
12959 StaticLocalLinkage == GVA_AvailableExternally)
12960 return GVA_DiscardableODR;
12961 return StaticLocalLinkage;
12962 }
12963
12964 // MSVC treats in-class initialized static data members as definitions.
12965 // By giving them non-strong linkage, out-of-line definitions won't
12966 // cause link errors.
12967 if (Context.isMSStaticDataMemberInlineDefinition(VD))
12968 return GVA_DiscardableODR;
12969
12970 // Most non-template variables have strong linkage; inline variables are
12971 // linkonce_odr or (occasionally, for compatibility) weak_odr.
12972 GVALinkage StrongLinkage;
12973 switch (Context.getInlineVariableDefinitionKind(VD)) {
12975 StrongLinkage = GVA_StrongExternal;
12976 break;
12979 StrongLinkage = GVA_DiscardableODR;
12980 break;
12982 StrongLinkage = GVA_StrongODR;
12983 break;
12984 }
12985
12986 switch (VD->getTemplateSpecializationKind()) {
12987 case TSK_Undeclared:
12988 return StrongLinkage;
12989
12991 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12992 VD->isStaticDataMember()
12994 : StrongLinkage;
12995
12997 return GVA_StrongODR;
12998
13001
13003 return GVA_DiscardableODR;
13004 }
13005
13006 llvm_unreachable("Invalid Linkage!");
13007}
13008
13014
13016 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13017 if (!VD->isFileVarDecl())
13018 return false;
13019 // Global named register variables (GNU extension) are never emitted.
13020 if (VD->getStorageClass() == SC_Register)
13021 return false;
13022 if (VD->getDescribedVarTemplate() ||
13024 return false;
13025 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13026 // We never need to emit an uninstantiated function template.
13027 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13028 return false;
13029 } else if (isa<PragmaCommentDecl>(D))
13030 return true;
13032 return true;
13033 else if (isa<OMPRequiresDecl>(D))
13034 return true;
13035 else if (isa<OMPThreadPrivateDecl>(D))
13036 return !D->getDeclContext()->isDependentContext();
13037 else if (isa<OMPAllocateDecl>(D))
13038 return !D->getDeclContext()->isDependentContext();
13040 return !D->getDeclContext()->isDependentContext();
13041 else if (isa<ImportDecl>(D))
13042 return true;
13043 else
13044 return false;
13045
13046 // If this is a member of a class template, we do not need to emit it.
13048 return false;
13049
13050 // Weak references don't produce any output by themselves.
13051 if (D->hasAttr<WeakRefAttr>())
13052 return false;
13053
13054 // SYCL device compilation requires that functions defined with the
13055 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13056 // other entities are emitted only if they are used by a function
13057 // defined with one of those attributes.
13058 if (LangOpts.SYCLIsDevice)
13059 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13060 D->hasAttr<SYCLExternalAttr>());
13061
13062 // Aliases and used decls are required.
13063 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13064 return true;
13065
13066 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13067 // Forward declarations aren't required.
13068 if (!FD->doesThisDeclarationHaveABody())
13069 return FD->doesDeclarationForceExternallyVisibleDefinition();
13070
13071 // Constructors and destructors are required.
13072 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13073 return true;
13074
13075 // The key function for a class is required. This rule only comes
13076 // into play when inline functions can be key functions, though.
13077 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13078 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13079 const CXXRecordDecl *RD = MD->getParent();
13080 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13081 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13082 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13083 return true;
13084 }
13085 }
13086 }
13087
13089
13090 // static, static inline, always_inline, and extern inline functions can
13091 // always be deferred. Normal inline functions can be deferred in C99/C++.
13092 // Implicit template instantiations can also be deferred in C++.
13094 }
13095
13096 const auto *VD = cast<VarDecl>(D);
13097 assert(VD->isFileVarDecl() && "Expected file scoped var");
13098
13099 // If the decl is marked as `declare target to`, it should be emitted for the
13100 // host and for the device.
13101 if (LangOpts.OpenMP &&
13102 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13103 return true;
13104
13105 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13107 return false;
13108
13109 if (VD->shouldEmitInExternalSource())
13110 return false;
13111
13112 // Variables that can be needed in other TUs are required.
13115 return true;
13116
13117 // We never need to emit a variable that is available in another TU.
13119 return false;
13120
13121 // Variables that have destruction with side-effects are required.
13122 if (VD->needsDestruction(*this))
13123 return true;
13124
13125 // Variables that have initialization with side-effects are required.
13126 if (VD->hasInitWithSideEffects())
13127 return true;
13128
13129 // Likewise, variables with tuple-like bindings are required if their
13130 // bindings have side-effects.
13131 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13132 for (const auto *BD : DD->flat_bindings())
13133 if (const auto *BindingVD = BD->getHoldingVar())
13134 if (DeclMustBeEmitted(BindingVD))
13135 return true;
13136 }
13137
13138 return false;
13139}
13140
13142 const FunctionDecl *FD,
13143 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13144 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13145 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13146 FD = FD->getMostRecentDecl();
13147 // FIXME: The order of traversal here matters and depends on the order of
13148 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13149 // shouldn't rely on that.
13150 for (auto *CurDecl :
13152 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13153 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13154 SeenDecls.insert(CurFD).second) {
13155 Pred(CurFD);
13156 }
13157 }
13158}
13159
13161 bool IsCXXMethod) const {
13162 // Pass through to the C++ ABI object
13163 if (IsCXXMethod)
13164 return ABI->getDefaultMethodCallConv(IsVariadic);
13165
13166 switch (LangOpts.getDefaultCallingConv()) {
13168 break;
13170 return CC_C;
13172 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13173 return CC_X86FastCall;
13174 break;
13176 if (!IsVariadic)
13177 return CC_X86StdCall;
13178 break;
13180 // __vectorcall cannot be applied to variadic functions.
13181 if (!IsVariadic)
13182 return CC_X86VectorCall;
13183 break;
13185 // __regcall cannot be applied to variadic functions.
13186 if (!IsVariadic)
13187 return CC_X86RegCall;
13188 break;
13190 if (!IsVariadic)
13191 return CC_M68kRTD;
13192 break;
13193 }
13194 return Target->getDefaultCallingConv();
13195}
13196
13198 // Pass through to the C++ ABI object
13199 return ABI->isNearlyEmpty(RD);
13200}
13201
13203 if (!VTContext) {
13204 auto ABI = Target->getCXXABI();
13205 if (ABI.isMicrosoft())
13206 VTContext.reset(new MicrosoftVTableContext(*this));
13207 else {
13208 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
13211 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
13212 }
13213 }
13214 return VTContext.get();
13215}
13216
13218 if (!T)
13219 T = Target;
13220 switch (T->getCXXABI().getKind()) {
13221 case TargetCXXABI::AppleARM64:
13222 case TargetCXXABI::Fuchsia:
13223 case TargetCXXABI::GenericAArch64:
13224 case TargetCXXABI::GenericItanium:
13225 case TargetCXXABI::GenericARM:
13226 case TargetCXXABI::GenericMIPS:
13227 case TargetCXXABI::iOS:
13228 case TargetCXXABI::WebAssembly:
13229 case TargetCXXABI::WatchOS:
13230 case TargetCXXABI::XL:
13232 case TargetCXXABI::Microsoft:
13234 }
13235 llvm_unreachable("Unsupported ABI");
13236}
13237
13239 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13240 "Device mangle context does not support Microsoft mangling.");
13241 switch (T.getCXXABI().getKind()) {
13242 case TargetCXXABI::AppleARM64:
13243 case TargetCXXABI::Fuchsia:
13244 case TargetCXXABI::GenericAArch64:
13245 case TargetCXXABI::GenericItanium:
13246 case TargetCXXABI::GenericARM:
13247 case TargetCXXABI::GenericMIPS:
13248 case TargetCXXABI::iOS:
13249 case TargetCXXABI::WebAssembly:
13250 case TargetCXXABI::WatchOS:
13251 case TargetCXXABI::XL:
13253 *this, getDiagnostics(),
13254 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13255 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13256 return RD->getDeviceLambdaManglingNumber();
13257 return std::nullopt;
13258 },
13259 /*IsAux=*/true);
13260 case TargetCXXABI::Microsoft:
13262 /*IsAux=*/true);
13263 }
13264 llvm_unreachable("Unsupported ABI");
13265}
13266
13267CXXABI::~CXXABI() = default;
13268
13270 return ASTRecordLayouts.getMemorySize() +
13271 llvm::capacity_in_bytes(ObjCLayouts) +
13272 llvm::capacity_in_bytes(KeyFunctions) +
13273 llvm::capacity_in_bytes(ObjCImpls) +
13274 llvm::capacity_in_bytes(BlockVarCopyInits) +
13275 llvm::capacity_in_bytes(DeclAttrs) +
13276 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13277 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13278 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13279 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13280 llvm::capacity_in_bytes(OverriddenMethods) +
13281 llvm::capacity_in_bytes(Types) +
13282 llvm::capacity_in_bytes(VariableArrayTypes);
13283}
13284
13285/// getIntTypeForBitwidth -
13286/// sets integer QualTy according to specified details:
13287/// bitwidth, signed/unsigned.
13288/// Returns empty type if there is no appropriate target types.
13290 unsigned Signed) const {
13292 CanQualType QualTy = getFromTargetType(Ty);
13293 if (!QualTy && DestWidth == 128)
13294 return Signed ? Int128Ty : UnsignedInt128Ty;
13295 return QualTy;
13296}
13297
13298/// getRealTypeForBitwidth -
13299/// sets floating point QualTy according to specified bitwidth.
13300/// Returns empty type if there is no appropriate target types.
13302 FloatModeKind ExplicitType) const {
13303 FloatModeKind Ty =
13304 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13305 switch (Ty) {
13307 return HalfTy;
13309 return FloatTy;
13311 return DoubleTy;
13313 return LongDoubleTy;
13315 return Float128Ty;
13317 return Ibm128Ty;
13319 return {};
13320 }
13321
13322 llvm_unreachable("Unhandled TargetInfo::RealType value");
13323}
13324
13325void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13326 if (Number <= 1)
13327 return;
13328
13329 MangleNumbers[ND] = Number;
13330
13331 if (Listener)
13332 Listener->AddedManglingNumber(ND, Number);
13333}
13334
13336 bool ForAuxTarget) const {
13337 auto I = MangleNumbers.find(ND);
13338 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13339 // CUDA/HIP host compilation encodes host and device mangling numbers
13340 // as lower and upper half of 32 bit integer.
13341 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13342 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13343 } else {
13344 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13345 "number for aux target");
13346 }
13347 return Res > 1 ? Res : 1;
13348}
13349
13350void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13351 if (Number <= 1)
13352 return;
13353
13354 StaticLocalNumbers[VD] = Number;
13355
13356 if (Listener)
13357 Listener->AddedStaticLocalNumbers(VD, Number);
13358}
13359
13361 auto I = StaticLocalNumbers.find(VD);
13362 return I != StaticLocalNumbers.end() ? I->second : 1;
13363}
13364
13366 bool IsDestroying) {
13367 if (!IsDestroying) {
13368 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13369 return;
13370 }
13371 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13372}
13373
13375 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13376}
13377
13379 bool IsTypeAware) {
13380 if (!IsTypeAware) {
13381 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13382 return;
13383 }
13384 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13385}
13386
13388 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13389}
13390
13393 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13394 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13395 if (!MCtx)
13397 return *MCtx;
13398}
13399
13402 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13403 std::unique_ptr<MangleNumberingContext> &MCtx =
13404 ExtraMangleNumberingContexts[D];
13405 if (!MCtx)
13407 return *MCtx;
13408}
13409
13410std::unique_ptr<MangleNumberingContext>
13412 return ABI->createMangleNumberingContext();
13413}
13414
13415const CXXConstructorDecl *
13417 return ABI->getCopyConstructorForExceptionObject(
13419}
13420
13422 CXXConstructorDecl *CD) {
13423 return ABI->addCopyConstructorForExceptionObject(
13426}
13427
13429 TypedefNameDecl *DD) {
13430 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13431}
13432
13435 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13436}
13437
13439 DeclaratorDecl *DD) {
13440 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13441}
13442
13444 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13445}
13446
13448 ParamIndices[D] = index;
13449}
13450
13452 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13453 assert(I != ParamIndices.end() &&
13454 "ParmIndices lacks entry set by ParmVarDecl");
13455 return I->second;
13456}
13457
13459 unsigned Length) const {
13460 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13461 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13462 EltTy = EltTy.withConst();
13463
13464 EltTy = adjustStringLiteralBaseType(EltTy);
13465
13466 // Get an array type for the string, according to C99 6.4.5. This includes
13467 // the null terminator character.
13468 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13469 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13470}
13471
13474 StringLiteral *&Result = StringLiteralCache[Key];
13475 if (!Result)
13477 *this, Key, StringLiteralKind::Ordinary,
13478 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13479 SourceLocation());
13480 return Result;
13481}
13482
13483MSGuidDecl *
13485 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13486
13487 llvm::FoldingSetNodeID ID;
13488 MSGuidDecl::Profile(ID, Parts);
13489
13490 void *InsertPos;
13491 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13492 return Existing;
13493
13494 QualType GUIDType = getMSGuidType().withConst();
13495 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13496 MSGuidDecls.InsertNode(New, InsertPos);
13497 return New;
13498}
13499
13502 const APValue &APVal) const {
13503 llvm::FoldingSetNodeID ID;
13505
13506 void *InsertPos;
13507 if (UnnamedGlobalConstantDecl *Existing =
13508 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13509 return Existing;
13510
13512 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13513 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13514 return New;
13515}
13516
13519 assert(T->isRecordType() && "template param object of unexpected type");
13520
13521 // C++ [temp.param]p8:
13522 // [...] a static storage duration object of type 'const T' [...]
13523 T.addConst();
13524
13525 llvm::FoldingSetNodeID ID;
13527
13528 void *InsertPos;
13529 if (TemplateParamObjectDecl *Existing =
13530 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13531 return Existing;
13532
13533 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13534 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13535 return New;
13536}
13537
13539 const llvm::Triple &T = getTargetInfo().getTriple();
13540 if (!T.isOSDarwin())
13541 return false;
13542
13543 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13544 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13545 return false;
13546
13547 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13548 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13549 uint64_t Size = sizeChars.getQuantity();
13550 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13551 unsigned Align = alignChars.getQuantity();
13552 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13553 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13554}
13555
13556bool
13558 const ObjCMethodDecl *MethodImpl) {
13559 // No point trying to match an unavailable/deprecated mothod.
13560 if (MethodDecl->hasAttr<UnavailableAttr>()
13561 || MethodDecl->hasAttr<DeprecatedAttr>())
13562 return false;
13563 if (MethodDecl->getObjCDeclQualifier() !=
13564 MethodImpl->getObjCDeclQualifier())
13565 return false;
13566 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13567 return false;
13568
13569 if (MethodDecl->param_size() != MethodImpl->param_size())
13570 return false;
13571
13572 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13573 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13574 EF = MethodDecl->param_end();
13575 IM != EM && IF != EF; ++IM, ++IF) {
13576 const ParmVarDecl *DeclVar = (*IF);
13577 const ParmVarDecl *ImplVar = (*IM);
13578 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13579 return false;
13580 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13581 return false;
13582 }
13583
13584 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13585}
13586
13588 LangAS AS;
13590 AS = LangAS::Default;
13591 else
13592 AS = QT->getPointeeType().getAddressSpace();
13593
13595}
13596
13599}
13600
13601bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13602 if (X == Y)
13603 return true;
13604 if (!X || !Y)
13605 return false;
13606 llvm::FoldingSetNodeID IDX, IDY;
13607 X->Profile(IDX, *this, /*Canonical=*/true);
13608 Y->Profile(IDY, *this, /*Canonical=*/true);
13609 return IDX == IDY;
13610}
13611
13612// The getCommon* helpers return, for given 'same' X and Y entities given as
13613// inputs, another entity which is also the 'same' as the inputs, but which
13614// is closer to the canonical form of the inputs, each according to a given
13615// criteria.
13616// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13617// the regular ones.
13618
13620 if (!declaresSameEntity(X, Y))
13621 return nullptr;
13622 for (const Decl *DX : X->redecls()) {
13623 // If we reach Y before reaching the first decl, that means X is older.
13624 if (DX == Y)
13625 return X;
13626 // If we reach the first decl, then Y is older.
13627 if (DX->isFirstDecl())
13628 return Y;
13629 }
13630 llvm_unreachable("Corrupt redecls chain");
13631}
13632
13633template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13634static T *getCommonDecl(T *X, T *Y) {
13635 return cast_or_null<T>(
13636 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13637 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13638}
13639
13640template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13641static T *getCommonDeclChecked(T *X, T *Y) {
13642 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
13643 const_cast<Decl *>(cast<Decl>(Y))));
13644}
13645
13647 TemplateName Y,
13648 bool IgnoreDeduced = false) {
13649 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
13650 return X;
13651 // FIXME: There are cases here where we could find a common template name
13652 // with more sugar. For example one could be a SubstTemplateTemplate*
13653 // replacing the other.
13654 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
13655 if (CX.getAsVoidPointer() !=
13657 return TemplateName();
13658 return CX;
13659}
13660
13663 bool IgnoreDeduced) {
13664 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
13665 assert(R.getAsVoidPointer() != nullptr);
13666 return R;
13667}
13668
13670 ArrayRef<QualType> Ys, bool Unqualified = false) {
13671 assert(Xs.size() == Ys.size());
13672 SmallVector<QualType, 8> Rs(Xs.size());
13673 for (size_t I = 0; I < Rs.size(); ++I)
13674 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
13675 return Rs;
13676}
13677
13678template <class T>
13679static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
13680 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
13681 : SourceLocation();
13682}
13683
13685 const TemplateArgument &X,
13686 const TemplateArgument &Y) {
13687 if (X.getKind() != Y.getKind())
13688 return TemplateArgument();
13689
13690 switch (X.getKind()) {
13692 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
13693 return TemplateArgument();
13694 return TemplateArgument(
13695 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
13697 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
13698 return TemplateArgument();
13699 return TemplateArgument(
13700 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
13701 /*Unqualified=*/true);
13703 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
13704 return TemplateArgument();
13705 // FIXME: Try to keep the common sugar.
13706 return X;
13708 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
13709 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13710 if (!CTN.getAsVoidPointer())
13711 return TemplateArgument();
13712 return TemplateArgument(CTN);
13713 }
13715 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
13717 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
13718 if (!CTN.getAsVoidPointer())
13719 return TemplateName();
13720 auto NExpX = X.getNumTemplateExpansions();
13721 assert(NExpX == Y.getNumTemplateExpansions());
13722 return TemplateArgument(CTN, NExpX);
13723 }
13724 default:
13725 // FIXME: Handle the other argument kinds.
13726 return X;
13727 }
13728}
13729
13734 if (Xs.size() != Ys.size())
13735 return true;
13736 R.resize(Xs.size());
13737 for (size_t I = 0; I < R.size(); ++I) {
13738 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
13739 if (R[I].isNull())
13740 return true;
13741 }
13742 return false;
13743}
13744
13749 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
13750 assert(!Different);
13751 (void)Different;
13752 return R;
13753}
13754
13755template <class T>
13757 bool IsSame) {
13758 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
13759 if (KX == KY)
13760 return KX;
13762 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
13763 return KX;
13764}
13765
13766/// Returns a NestedNameSpecifier which has only the common sugar
13767/// present in both NNS1 and NNS2.
13770 NestedNameSpecifier NNS2, bool IsSame) {
13771 // If they are identical, all sugar is common.
13772 if (NNS1 == NNS2)
13773 return NNS1;
13774
13775 // IsSame implies both Qualifiers are equivalent.
13776 NestedNameSpecifier Canon = NNS1.getCanonical();
13777 if (Canon != NNS2.getCanonical()) {
13778 assert(!IsSame && "Should be the same NestedNameSpecifier");
13779 // If they are not the same, there is nothing to unify.
13780 return std::nullopt;
13781 }
13782
13783 NestedNameSpecifier R = std::nullopt;
13784 NestedNameSpecifier::Kind Kind = NNS1.getKind();
13785 assert(Kind == NNS2.getKind());
13786 switch (Kind) {
13788 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
13789 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
13790 auto Kind = Namespace1->getKind();
13791 if (Kind != Namespace2->getKind() ||
13792 (Kind == Decl::NamespaceAlias &&
13793 !declaresSameEntity(Namespace1, Namespace2))) {
13795 Ctx,
13796 ::getCommonDeclChecked(Namespace1->getNamespace(),
13797 Namespace2->getNamespace()),
13798 /*Prefix=*/std::nullopt);
13799 break;
13800 }
13801 // The prefixes for namespaces are not significant, its declaration
13802 // identifies it uniquely.
13803 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
13804 /*IsSame=*/false);
13805 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
13806 Prefix);
13807 break;
13808 }
13810 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
13811 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
13812 /*Unqualified=*/true)
13813 .getTypePtr();
13815 break;
13816 }
13818 // FIXME: Can __super even be used with data members?
13819 // If it's only usable in functions, we will never see it here,
13820 // unless we save the qualifiers used in function types.
13821 // In that case, it might be possible NNS2 is a type,
13822 // in which case we should degrade the result to
13823 // a CXXRecordType.
13825 NNS2.getAsMicrosoftSuper()));
13826 break;
13827 }
13830 // These are singletons.
13831 llvm_unreachable("singletons did not compare equal");
13832 }
13833 assert(R.getCanonical() == Canon);
13834 return R;
13835}
13836
13837template <class T>
13839 const T *Y, bool IsSame) {
13840 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
13841}
13842
13843template <class T>
13844static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
13845 const T *Y) {
13846 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
13847}
13848
13849template <class T>
13851 Qualifiers &QX, const T *Y,
13852 Qualifiers &QY) {
13853 QualType EX = X->getElementType(), EY = Y->getElementType();
13854 QualType R = Ctx.getCommonSugaredType(EX, EY,
13855 /*Unqualified=*/true);
13856 // Qualifiers common to both element types.
13857 Qualifiers RQ = R.getQualifiers();
13858 // For each side, move to the top level any qualifiers which are not common to
13859 // both element types. The caller must assume top level qualifiers might
13860 // be different, even if they are the same type, and can be treated as sugar.
13861 QX += EX.getQualifiers() - RQ;
13862 QY += EY.getQualifiers() - RQ;
13863 return R;
13864}
13865
13866template <class T>
13867static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
13868 const T *Y) {
13869 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
13870}
13871
13872template <class T>
13873static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
13874 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
13875 return X->getSizeExpr();
13876}
13877
13878static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
13879 assert(X->getSizeModifier() == Y->getSizeModifier());
13880 return X->getSizeModifier();
13881}
13882
13884 const ArrayType *Y) {
13885 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
13886 return X->getIndexTypeCVRQualifiers();
13887}
13888
13889// Merges two type lists such that the resulting vector will contain
13890// each type (in a canonical sense) only once, in the order they appear
13891// from X to Y. If they occur in both X and Y, the result will contain
13892// the common sugared type between them.
13893static void mergeTypeLists(const ASTContext &Ctx,
13896 llvm::DenseMap<QualType, unsigned> Found;
13897 for (auto Ts : {X, Y}) {
13898 for (QualType T : Ts) {
13899 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
13900 if (!Res.second) {
13901 QualType &U = Out[Res.first->second];
13902 U = Ctx.getCommonSugaredType(U, T);
13903 } else {
13904 Out.emplace_back(T);
13905 }
13906 }
13907 }
13908}
13909
13910FunctionProtoType::ExceptionSpecInfo
13913 SmallVectorImpl<QualType> &ExceptionTypeStorage,
13914 bool AcceptDependent) const {
13915 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
13916
13917 // If either of them can throw anything, that is the result.
13918 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
13919 if (EST1 == I)
13920 return ESI1;
13921 if (EST2 == I)
13922 return ESI2;
13923 }
13924
13925 // If either of them is non-throwing, the result is the other.
13926 for (auto I :
13928 if (EST1 == I)
13929 return ESI2;
13930 if (EST2 == I)
13931 return ESI1;
13932 }
13933
13934 // If we're left with value-dependent computed noexcept expressions, we're
13935 // stuck. Before C++17, we can just drop the exception specification entirely,
13936 // since it's not actually part of the canonical type. And this should never
13937 // happen in C++17, because it would mean we were computing the composite
13938 // pointer type of dependent types, which should never happen.
13939 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
13940 assert(AcceptDependent &&
13941 "computing composite pointer type of dependent types");
13943 }
13944
13945 // Switch over the possibilities so that people adding new values know to
13946 // update this function.
13947 switch (EST1) {
13948 case EST_None:
13949 case EST_DynamicNone:
13950 case EST_MSAny:
13951 case EST_BasicNoexcept:
13953 case EST_NoexceptFalse:
13954 case EST_NoexceptTrue:
13955 case EST_NoThrow:
13956 llvm_unreachable("These ESTs should be handled above");
13957
13958 case EST_Dynamic: {
13959 // This is the fun case: both exception specifications are dynamic. Form
13960 // the union of the two lists.
13961 assert(EST2 == EST_Dynamic && "other cases should already be handled");
13962 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
13963 ESI2.Exceptions);
13965 Result.Exceptions = ExceptionTypeStorage;
13966 return Result;
13967 }
13968
13969 case EST_Unevaluated:
13970 case EST_Uninstantiated:
13971 case EST_Unparsed:
13972 llvm_unreachable("shouldn't see unresolved exception specifications here");
13973 }
13974
13975 llvm_unreachable("invalid ExceptionSpecificationType");
13976}
13977
13979 Qualifiers &QX, const Type *Y,
13980 Qualifiers &QY) {
13981 Type::TypeClass TC = X->getTypeClass();
13982 assert(TC == Y->getTypeClass());
13983 switch (TC) {
13984#define UNEXPECTED_TYPE(Class, Kind) \
13985 case Type::Class: \
13986 llvm_unreachable("Unexpected " Kind ": " #Class);
13987
13988#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
13989#define TYPE(Class, Base)
13990#include "clang/AST/TypeNodes.inc"
13991
13992#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
13994 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
13995 SUGAR_FREE_TYPE(DependentBitInt)
13997 SUGAR_FREE_TYPE(ObjCInterface)
13998 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
13999 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14000 SUGAR_FREE_TYPE(UnresolvedUsing)
14001 SUGAR_FREE_TYPE(HLSLAttributedResource)
14002 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14003#undef SUGAR_FREE_TYPE
14004#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14005 NON_UNIQUE_TYPE(TypeOfExpr)
14006 NON_UNIQUE_TYPE(VariableArray)
14007#undef NON_UNIQUE_TYPE
14008
14009 UNEXPECTED_TYPE(TypeOf, "sugar")
14010
14011#undef UNEXPECTED_TYPE
14012
14013 case Type::Auto: {
14014 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14015 assert(AX->getDeducedType().isNull());
14016 assert(AY->getDeducedType().isNull());
14017 assert(AX->getKeyword() == AY->getKeyword());
14018 assert(AX->isInstantiationDependentType() ==
14019 AY->isInstantiationDependentType());
14020 auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
14021 AY->getTypeConstraintArguments());
14022 return Ctx.getAutoType(QualType(), AX->getKeyword(),
14024 AX->containsUnexpandedParameterPack(),
14025 getCommonDeclChecked(AX->getTypeConstraintConcept(),
14026 AY->getTypeConstraintConcept()),
14027 As);
14028 }
14029 case Type::IncompleteArray: {
14030 const auto *AX = cast<IncompleteArrayType>(X),
14032 return Ctx.getIncompleteArrayType(
14033 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14035 }
14036 case Type::DependentSizedArray: {
14037 const auto *AX = cast<DependentSizedArrayType>(X),
14039 return Ctx.getDependentSizedArrayType(
14040 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14041 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14043 }
14044 case Type::ConstantArray: {
14045 const auto *AX = cast<ConstantArrayType>(X),
14046 *AY = cast<ConstantArrayType>(Y);
14047 assert(AX->getSize() == AY->getSize());
14048 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14049 ? AX->getSizeExpr()
14050 : nullptr;
14051 return Ctx.getConstantArrayType(
14052 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14054 }
14055 case Type::ArrayParameter: {
14056 const auto *AX = cast<ArrayParameterType>(X),
14057 *AY = cast<ArrayParameterType>(Y);
14058 assert(AX->getSize() == AY->getSize());
14059 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14060 ? AX->getSizeExpr()
14061 : nullptr;
14062 auto ArrayTy = Ctx.getConstantArrayType(
14063 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14065 return Ctx.getArrayParameterType(ArrayTy);
14066 }
14067 case Type::Atomic: {
14068 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14069 return Ctx.getAtomicType(
14070 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14071 }
14072 case Type::Complex: {
14073 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14074 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14075 }
14076 case Type::Pointer: {
14077 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14078 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14079 }
14080 case Type::BlockPointer: {
14081 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14082 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14083 }
14084 case Type::ObjCObjectPointer: {
14085 const auto *PX = cast<ObjCObjectPointerType>(X),
14087 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14088 }
14089 case Type::MemberPointer: {
14090 const auto *PX = cast<MemberPointerType>(X),
14091 *PY = cast<MemberPointerType>(Y);
14092 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14093 PY->getMostRecentCXXRecordDecl()));
14094 return Ctx.getMemberPointerType(
14095 getCommonPointeeType(Ctx, PX, PY),
14096 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14097 PX->getMostRecentCXXRecordDecl());
14098 }
14099 case Type::LValueReference: {
14100 const auto *PX = cast<LValueReferenceType>(X),
14102 // FIXME: Preserve PointeeTypeAsWritten.
14103 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14104 PX->isSpelledAsLValue() ||
14105 PY->isSpelledAsLValue());
14106 }
14107 case Type::RValueReference: {
14108 const auto *PX = cast<RValueReferenceType>(X),
14110 // FIXME: Preserve PointeeTypeAsWritten.
14111 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14112 }
14113 case Type::DependentAddressSpace: {
14114 const auto *PX = cast<DependentAddressSpaceType>(X),
14116 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14117 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14118 PX->getAddrSpaceExpr(),
14119 getCommonAttrLoc(PX, PY));
14120 }
14121 case Type::FunctionNoProto: {
14122 const auto *FX = cast<FunctionNoProtoType>(X),
14124 assert(FX->getExtInfo() == FY->getExtInfo());
14125 return Ctx.getFunctionNoProtoType(
14126 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14127 FX->getExtInfo());
14128 }
14129 case Type::FunctionProto: {
14130 const auto *FX = cast<FunctionProtoType>(X),
14131 *FY = cast<FunctionProtoType>(Y);
14132 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14133 EPIY = FY->getExtProtoInfo();
14134 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14135 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14136 assert(!EPIX.ExtParameterInfos ||
14137 llvm::equal(
14138 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14139 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14140 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14141 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14142 assert(EPIX.Variadic == EPIY.Variadic);
14143
14144 // FIXME: Can we handle an empty EllipsisLoc?
14145 // Use emtpy EllipsisLoc if X and Y differ.
14146
14147 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14148
14149 QualType R =
14150 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14151 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14152 /*Unqualified=*/true);
14153
14154 SmallVector<QualType, 8> Exceptions;
14156 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14157 return Ctx.getFunctionType(R, P, EPIX);
14158 }
14159 case Type::ObjCObject: {
14160 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14161 assert(
14162 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14163 OY->getProtocols().begin(), OY->getProtocols().end(),
14164 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14165 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14166 }) &&
14167 "protocol lists must be the same");
14168 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14169 OY->getTypeArgsAsWritten());
14170 return Ctx.getObjCObjectType(
14171 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14172 OX->getProtocols(),
14173 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14174 }
14175 case Type::ConstantMatrix: {
14176 const auto *MX = cast<ConstantMatrixType>(X),
14177 *MY = cast<ConstantMatrixType>(Y);
14178 assert(MX->getNumRows() == MY->getNumRows());
14179 assert(MX->getNumColumns() == MY->getNumColumns());
14180 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14181 MX->getNumRows(), MX->getNumColumns());
14182 }
14183 case Type::DependentSizedMatrix: {
14184 const auto *MX = cast<DependentSizedMatrixType>(X),
14186 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14187 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14188 return Ctx.getDependentSizedMatrixType(
14189 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14190 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14191 }
14192 case Type::Vector: {
14193 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14194 assert(VX->getNumElements() == VY->getNumElements());
14195 assert(VX->getVectorKind() == VY->getVectorKind());
14196 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14197 VX->getNumElements(), VX->getVectorKind());
14198 }
14199 case Type::ExtVector: {
14200 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14201 assert(VX->getNumElements() == VY->getNumElements());
14202 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14203 VX->getNumElements());
14204 }
14205 case Type::DependentSizedExtVector: {
14206 const auto *VX = cast<DependentSizedExtVectorType>(X),
14209 getCommonSizeExpr(Ctx, VX, VY),
14210 getCommonAttrLoc(VX, VY));
14211 }
14212 case Type::DependentVector: {
14213 const auto *VX = cast<DependentVectorType>(X),
14215 assert(VX->getVectorKind() == VY->getVectorKind());
14216 return Ctx.getDependentVectorType(
14217 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14218 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14219 }
14220 case Type::Enum:
14221 case Type::Record:
14222 case Type::InjectedClassName: {
14223 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14224 return Ctx.getTagType(
14225 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14226 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14227 ::getCommonDeclChecked(TX->getOriginalDecl(), TY->getOriginalDecl()),
14228 /*OwnedTag=*/false);
14229 }
14230 case Type::TemplateSpecialization: {
14231 const auto *TX = cast<TemplateSpecializationType>(X),
14233 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14234 TY->template_arguments());
14236 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14237 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14238 TY->getTemplateName(),
14239 /*IgnoreDeduced=*/true),
14240 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14241 }
14242 case Type::Decltype: {
14243 const auto *DX = cast<DecltypeType>(X);
14244 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14245 assert(DX->isDependentType());
14246 assert(DY->isDependentType());
14247 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14248 // As Decltype is not uniqued, building a common type would be wasteful.
14249 return QualType(DX, 0);
14250 }
14251 case Type::PackIndexing: {
14252 const auto *DX = cast<PackIndexingType>(X);
14253 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14254 assert(DX->isDependentType());
14255 assert(DY->isDependentType());
14256 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14257 return QualType(DX, 0);
14258 }
14259 case Type::DependentName: {
14260 const auto *NX = cast<DependentNameType>(X),
14261 *NY = cast<DependentNameType>(Y);
14262 assert(NX->getIdentifier() == NY->getIdentifier());
14263 return Ctx.getDependentNameType(
14264 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14265 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14266 }
14267 case Type::UnaryTransform: {
14268 const auto *TX = cast<UnaryTransformType>(X),
14269 *TY = cast<UnaryTransformType>(Y);
14270 assert(TX->getUTTKind() == TY->getUTTKind());
14271 return Ctx.getUnaryTransformType(
14272 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14273 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14274 TY->getUnderlyingType()),
14275 TX->getUTTKind());
14276 }
14277 case Type::PackExpansion: {
14278 const auto *PX = cast<PackExpansionType>(X),
14279 *PY = cast<PackExpansionType>(Y);
14280 assert(PX->getNumExpansions() == PY->getNumExpansions());
14281 return Ctx.getPackExpansionType(
14282 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14283 PX->getNumExpansions(), false);
14284 }
14285 case Type::Pipe: {
14286 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14287 assert(PX->isReadOnly() == PY->isReadOnly());
14288 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14290 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14291 }
14292 case Type::TemplateTypeParm: {
14293 const auto *TX = cast<TemplateTypeParmType>(X),
14295 assert(TX->getDepth() == TY->getDepth());
14296 assert(TX->getIndex() == TY->getIndex());
14297 assert(TX->isParameterPack() == TY->isParameterPack());
14298 return Ctx.getTemplateTypeParmType(
14299 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14300 getCommonDecl(TX->getDecl(), TY->getDecl()));
14301 }
14302 }
14303 llvm_unreachable("Unknown Type Class");
14304}
14305
14307 const Type *Y,
14308 SplitQualType Underlying) {
14309 Type::TypeClass TC = X->getTypeClass();
14310 if (TC != Y->getTypeClass())
14311 return QualType();
14312 switch (TC) {
14313#define UNEXPECTED_TYPE(Class, Kind) \
14314 case Type::Class: \
14315 llvm_unreachable("Unexpected " Kind ": " #Class);
14316#define TYPE(Class, Base)
14317#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14318#include "clang/AST/TypeNodes.inc"
14319
14320#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14323 CANONICAL_TYPE(BlockPointer)
14326 CANONICAL_TYPE(ConstantArray)
14327 CANONICAL_TYPE(ArrayParameter)
14328 CANONICAL_TYPE(ConstantMatrix)
14330 CANONICAL_TYPE(ExtVector)
14331 CANONICAL_TYPE(FunctionNoProto)
14332 CANONICAL_TYPE(FunctionProto)
14333 CANONICAL_TYPE(IncompleteArray)
14334 CANONICAL_TYPE(HLSLAttributedResource)
14335 CANONICAL_TYPE(HLSLInlineSpirv)
14336 CANONICAL_TYPE(LValueReference)
14337 CANONICAL_TYPE(ObjCInterface)
14338 CANONICAL_TYPE(ObjCObject)
14339 CANONICAL_TYPE(ObjCObjectPointer)
14343 CANONICAL_TYPE(RValueReference)
14344 CANONICAL_TYPE(VariableArray)
14346#undef CANONICAL_TYPE
14347
14348#undef UNEXPECTED_TYPE
14349
14350 case Type::Adjusted: {
14351 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14352 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14353 if (!Ctx.hasSameType(OX, OY))
14354 return QualType();
14355 // FIXME: It's inefficient to have to unify the original types.
14356 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14357 Ctx.getQualifiedType(Underlying));
14358 }
14359 case Type::Decayed: {
14360 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14361 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14362 if (!Ctx.hasSameType(OX, OY))
14363 return QualType();
14364 // FIXME: It's inefficient to have to unify the original types.
14365 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14366 Ctx.getQualifiedType(Underlying));
14367 }
14368 case Type::Attributed: {
14369 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14370 AttributedType::Kind Kind = AX->getAttrKind();
14371 if (Kind != AY->getAttrKind())
14372 return QualType();
14373 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14374 if (!Ctx.hasSameType(MX, MY))
14375 return QualType();
14376 // FIXME: It's inefficient to have to unify the modified types.
14377 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14378 Ctx.getQualifiedType(Underlying),
14379 AX->getAttr());
14380 }
14381 case Type::BTFTagAttributed: {
14382 const auto *BX = cast<BTFTagAttributedType>(X);
14383 const BTFTypeTagAttr *AX = BX->getAttr();
14384 // The attribute is not uniqued, so just compare the tag.
14385 if (AX->getBTFTypeTag() !=
14386 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14387 return QualType();
14388 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14389 }
14390 case Type::Auto: {
14391 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14392
14393 AutoTypeKeyword KW = AX->getKeyword();
14394 if (KW != AY->getKeyword())
14395 return QualType();
14396
14397 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14398 AY->getTypeConstraintConcept());
14400 if (CD &&
14401 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14402 AY->getTypeConstraintArguments())) {
14403 CD = nullptr; // The arguments differ, so make it unconstrained.
14404 As.clear();
14405 }
14406
14407 // Both auto types can't be dependent, otherwise they wouldn't have been
14408 // sugar. This implies they can't contain unexpanded packs either.
14409 return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14410 /*IsDependent=*/false, /*IsPack=*/false, CD, As);
14411 }
14412 case Type::PackIndexing:
14413 case Type::Decltype:
14414 return QualType();
14415 case Type::DeducedTemplateSpecialization:
14416 // FIXME: Try to merge these.
14417 return QualType();
14418 case Type::MacroQualified: {
14419 const auto *MX = cast<MacroQualifiedType>(X),
14420 *MY = cast<MacroQualifiedType>(Y);
14421 const IdentifierInfo *IX = MX->getMacroIdentifier();
14422 if (IX != MY->getMacroIdentifier())
14423 return QualType();
14424 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14425 }
14426 case Type::SubstTemplateTypeParm: {
14427 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14429 Decl *CD =
14430 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14431 if (!CD)
14432 return QualType();
14433 unsigned Index = SX->getIndex();
14434 if (Index != SY->getIndex())
14435 return QualType();
14436 auto PackIndex = SX->getPackIndex();
14437 if (PackIndex != SY->getPackIndex())
14438 return QualType();
14439 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14440 CD, Index, PackIndex,
14441 SX->getFinal() && SY->getFinal());
14442 }
14443 case Type::ObjCTypeParam:
14444 // FIXME: Try to merge these.
14445 return QualType();
14446 case Type::Paren:
14447 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14448
14449 case Type::TemplateSpecialization: {
14450 const auto *TX = cast<TemplateSpecializationType>(X),
14452 TemplateName CTN =
14453 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14454 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14455 if (!CTN.getAsVoidPointer())
14456 return QualType();
14458 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14459 TY->template_arguments()))
14460 return QualType();
14462 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14463 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14464 }
14465 case Type::Typedef: {
14466 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14467 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14468 if (!CD)
14469 return QualType();
14470 return Ctx.getTypedefType(
14471 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14472 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14473 Ctx.getQualifiedType(Underlying));
14474 }
14475 case Type::TypeOf: {
14476 // The common sugar between two typeof expressions, where one is
14477 // potentially a typeof_unqual and the other is not, we unify to the
14478 // qualified type as that retains the most information along with the type.
14479 // We only return a typeof_unqual type when both types are unqual types.
14484 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14485 }
14486 case Type::TypeOfExpr:
14487 return QualType();
14488
14489 case Type::UnaryTransform: {
14490 const auto *UX = cast<UnaryTransformType>(X),
14491 *UY = cast<UnaryTransformType>(Y);
14492 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14493 if (KX != UY->getUTTKind())
14494 return QualType();
14495 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14496 if (!Ctx.hasSameType(BX, BY))
14497 return QualType();
14498 // FIXME: It's inefficient to have to unify the base types.
14499 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14500 Ctx.getQualifiedType(Underlying), KX);
14501 }
14502 case Type::Using: {
14503 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14504 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14505 if (!CD)
14506 return QualType();
14507 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14508 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14509 CD, Ctx.getQualifiedType(Underlying));
14510 }
14511 case Type::MemberPointer: {
14512 const auto *PX = cast<MemberPointerType>(X),
14513 *PY = cast<MemberPointerType>(Y);
14514 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14515 assert(Cls == PY->getMostRecentCXXRecordDecl());
14516 return Ctx.getMemberPointerType(
14517 ::getCommonPointeeType(Ctx, PX, PY),
14518 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14519 }
14520 case Type::CountAttributed: {
14521 const auto *DX = cast<CountAttributedType>(X),
14523 if (DX->isCountInBytes() != DY->isCountInBytes())
14524 return QualType();
14525 if (DX->isOrNull() != DY->isOrNull())
14526 return QualType();
14527 Expr *CEX = DX->getCountExpr();
14528 Expr *CEY = DY->getCountExpr();
14529 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14530 if (Ctx.hasSameExpr(CEX, CEY))
14531 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14532 DX->isCountInBytes(), DX->isOrNull(),
14533 CDX);
14534 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14535 return QualType();
14536 // Two declarations with the same integer constant may still differ in their
14537 // expression pointers, so we need to evaluate them.
14538 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14539 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14540 if (VX != VY)
14541 return QualType();
14542 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14543 DX->isCountInBytes(), DX->isOrNull(),
14544 CDX);
14545 }
14546 case Type::PredefinedSugar:
14547 assert(cast<PredefinedSugarType>(X)->getKind() !=
14549 return QualType();
14550 }
14551 llvm_unreachable("Unhandled Type Class");
14552}
14553
14554static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14556 while (true) {
14557 QTotal.addConsistentQualifiers(T.Quals);
14558 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14559 if (NT == QualType(T.Ty, 0))
14560 break;
14561 R.push_back(T);
14562 T = NT.split();
14563 }
14564 return R;
14565}
14566
14568 bool Unqualified) const {
14569 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14570 if (X == Y)
14571 return X;
14572 if (!Unqualified) {
14573 if (X.isCanonical())
14574 return X;
14575 if (Y.isCanonical())
14576 return Y;
14577 }
14578
14579 SplitQualType SX = X.split(), SY = Y.split();
14580 Qualifiers QX, QY;
14581 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14582 // until we reach their underlying "canonical nodes". Note these are not
14583 // necessarily canonical types, as they may still have sugared properties.
14584 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14585 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14586
14587 // If this is an ArrayType, the element qualifiers are interchangeable with
14588 // the top level qualifiers.
14589 // * In case the canonical nodes are the same, the elements types are already
14590 // the same.
14591 // * Otherwise, the element types will be made the same, and any different
14592 // element qualifiers will be moved up to the top level qualifiers, per
14593 // 'getCommonArrayElementType'.
14594 // In both cases, this means there may be top level qualifiers which differ
14595 // between X and Y. If so, these differing qualifiers are redundant with the
14596 // element qualifiers, and can be removed without changing the canonical type.
14597 // The desired behaviour is the same as for the 'Unqualified' case here:
14598 // treat the redundant qualifiers as sugar, remove the ones which are not
14599 // common to both sides.
14600 bool KeepCommonQualifiers = Unqualified || isa<ArrayType>(SX.Ty);
14601
14602 if (SX.Ty != SY.Ty) {
14603 // The canonical nodes differ. Build a common canonical node out of the two,
14604 // unifying their sugar. This may recurse back here.
14605 SX.Ty =
14606 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14607 } else {
14608 // The canonical nodes were identical: We may have desugared too much.
14609 // Add any common sugar back in.
14610 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14611 QX -= SX.Quals;
14612 QY -= SY.Quals;
14613 SX = Xs.pop_back_val();
14614 SY = Ys.pop_back_val();
14615 }
14616 }
14617 if (KeepCommonQualifiers)
14619 else
14620 assert(QX == QY);
14621
14622 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
14623 // related. Walk up these nodes, unifying them and adding the result.
14624 while (!Xs.empty() && !Ys.empty()) {
14625 auto Underlying = SplitQualType(
14626 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
14627 SX = Xs.pop_back_val();
14628 SY = Ys.pop_back_val();
14629 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
14631 // Stop at the first pair which is unrelated.
14632 if (!SX.Ty) {
14633 SX.Ty = Underlying.Ty;
14634 break;
14635 }
14636 QX -= Underlying.Quals;
14637 };
14638
14639 // Add back the missing accumulated qualifiers, which were stripped off
14640 // with the sugar nodes we could not unify.
14641 QualType R = getQualifiedType(SX.Ty, QX);
14642 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
14643 return R;
14644}
14645
14647 assert(Ty->isFixedPointType());
14648
14650 return Ty;
14651
14652 switch (Ty->castAs<BuiltinType>()->getKind()) {
14653 default:
14654 llvm_unreachable("Not a saturated fixed point type!");
14655 case BuiltinType::SatShortAccum:
14656 return ShortAccumTy;
14657 case BuiltinType::SatAccum:
14658 return AccumTy;
14659 case BuiltinType::SatLongAccum:
14660 return LongAccumTy;
14661 case BuiltinType::SatUShortAccum:
14662 return UnsignedShortAccumTy;
14663 case BuiltinType::SatUAccum:
14664 return UnsignedAccumTy;
14665 case BuiltinType::SatULongAccum:
14666 return UnsignedLongAccumTy;
14667 case BuiltinType::SatShortFract:
14668 return ShortFractTy;
14669 case BuiltinType::SatFract:
14670 return FractTy;
14671 case BuiltinType::SatLongFract:
14672 return LongFractTy;
14673 case BuiltinType::SatUShortFract:
14674 return UnsignedShortFractTy;
14675 case BuiltinType::SatUFract:
14676 return UnsignedFractTy;
14677 case BuiltinType::SatULongFract:
14678 return UnsignedLongFractTy;
14679 }
14680}
14681
14683 assert(Ty->isFixedPointType());
14684
14685 if (Ty->isSaturatedFixedPointType()) return Ty;
14686
14687 switch (Ty->castAs<BuiltinType>()->getKind()) {
14688 default:
14689 llvm_unreachable("Not a fixed point type!");
14690 case BuiltinType::ShortAccum:
14691 return SatShortAccumTy;
14692 case BuiltinType::Accum:
14693 return SatAccumTy;
14694 case BuiltinType::LongAccum:
14695 return SatLongAccumTy;
14696 case BuiltinType::UShortAccum:
14698 case BuiltinType::UAccum:
14699 return SatUnsignedAccumTy;
14700 case BuiltinType::ULongAccum:
14702 case BuiltinType::ShortFract:
14703 return SatShortFractTy;
14704 case BuiltinType::Fract:
14705 return SatFractTy;
14706 case BuiltinType::LongFract:
14707 return SatLongFractTy;
14708 case BuiltinType::UShortFract:
14710 case BuiltinType::UFract:
14711 return SatUnsignedFractTy;
14712 case BuiltinType::ULongFract:
14714 }
14715}
14716
14718 if (LangOpts.OpenCL)
14720
14721 if (LangOpts.CUDA)
14723
14724 return getLangASFromTargetAS(AS);
14725}
14726
14727// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
14728// doesn't include ASTContext.h
14729template
14731 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
14733 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
14734 const clang::ASTContext &Ctx, Decl *Value);
14735
14737 assert(Ty->isFixedPointType());
14738
14739 const TargetInfo &Target = getTargetInfo();
14740 switch (Ty->castAs<BuiltinType>()->getKind()) {
14741 default:
14742 llvm_unreachable("Not a fixed point type!");
14743 case BuiltinType::ShortAccum:
14744 case BuiltinType::SatShortAccum:
14745 return Target.getShortAccumScale();
14746 case BuiltinType::Accum:
14747 case BuiltinType::SatAccum:
14748 return Target.getAccumScale();
14749 case BuiltinType::LongAccum:
14750 case BuiltinType::SatLongAccum:
14751 return Target.getLongAccumScale();
14752 case BuiltinType::UShortAccum:
14753 case BuiltinType::SatUShortAccum:
14754 return Target.getUnsignedShortAccumScale();
14755 case BuiltinType::UAccum:
14756 case BuiltinType::SatUAccum:
14757 return Target.getUnsignedAccumScale();
14758 case BuiltinType::ULongAccum:
14759 case BuiltinType::SatULongAccum:
14760 return Target.getUnsignedLongAccumScale();
14761 case BuiltinType::ShortFract:
14762 case BuiltinType::SatShortFract:
14763 return Target.getShortFractScale();
14764 case BuiltinType::Fract:
14765 case BuiltinType::SatFract:
14766 return Target.getFractScale();
14767 case BuiltinType::LongFract:
14768 case BuiltinType::SatLongFract:
14769 return Target.getLongFractScale();
14770 case BuiltinType::UShortFract:
14771 case BuiltinType::SatUShortFract:
14772 return Target.getUnsignedShortFractScale();
14773 case BuiltinType::UFract:
14774 case BuiltinType::SatUFract:
14775 return Target.getUnsignedFractScale();
14776 case BuiltinType::ULongFract:
14777 case BuiltinType::SatULongFract:
14778 return Target.getUnsignedLongFractScale();
14779 }
14780}
14781
14783 assert(Ty->isFixedPointType());
14784
14785 const TargetInfo &Target = getTargetInfo();
14786 switch (Ty->castAs<BuiltinType>()->getKind()) {
14787 default:
14788 llvm_unreachable("Not a fixed point type!");
14789 case BuiltinType::ShortAccum:
14790 case BuiltinType::SatShortAccum:
14791 return Target.getShortAccumIBits();
14792 case BuiltinType::Accum:
14793 case BuiltinType::SatAccum:
14794 return Target.getAccumIBits();
14795 case BuiltinType::LongAccum:
14796 case BuiltinType::SatLongAccum:
14797 return Target.getLongAccumIBits();
14798 case BuiltinType::UShortAccum:
14799 case BuiltinType::SatUShortAccum:
14800 return Target.getUnsignedShortAccumIBits();
14801 case BuiltinType::UAccum:
14802 case BuiltinType::SatUAccum:
14803 return Target.getUnsignedAccumIBits();
14804 case BuiltinType::ULongAccum:
14805 case BuiltinType::SatULongAccum:
14806 return Target.getUnsignedLongAccumIBits();
14807 case BuiltinType::ShortFract:
14808 case BuiltinType::SatShortFract:
14809 case BuiltinType::Fract:
14810 case BuiltinType::SatFract:
14811 case BuiltinType::LongFract:
14812 case BuiltinType::SatLongFract:
14813 case BuiltinType::UShortFract:
14814 case BuiltinType::SatUShortFract:
14815 case BuiltinType::UFract:
14816 case BuiltinType::SatUFract:
14817 case BuiltinType::ULongFract:
14818 case BuiltinType::SatULongFract:
14819 return 0;
14820 }
14821}
14822
14823llvm::FixedPointSemantics
14825 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
14826 "Can only get the fixed point semantics for a "
14827 "fixed point or integer type.");
14828 if (Ty->isIntegerType())
14829 return llvm::FixedPointSemantics::GetIntegerSemantics(
14830 getIntWidth(Ty), Ty->isSignedIntegerType());
14831
14832 bool isSigned = Ty->isSignedFixedPointType();
14833 return llvm::FixedPointSemantics(
14834 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
14836 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
14837}
14838
14839llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
14840 assert(Ty->isFixedPointType());
14841 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
14842}
14843
14844llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
14845 assert(Ty->isFixedPointType());
14846 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
14847}
14848
14850 assert(Ty->isUnsignedFixedPointType() &&
14851 "Expected unsigned fixed point type");
14852
14853 switch (Ty->castAs<BuiltinType>()->getKind()) {
14854 case BuiltinType::UShortAccum:
14855 return ShortAccumTy;
14856 case BuiltinType::UAccum:
14857 return AccumTy;
14858 case BuiltinType::ULongAccum:
14859 return LongAccumTy;
14860 case BuiltinType::SatUShortAccum:
14861 return SatShortAccumTy;
14862 case BuiltinType::SatUAccum:
14863 return SatAccumTy;
14864 case BuiltinType::SatULongAccum:
14865 return SatLongAccumTy;
14866 case BuiltinType::UShortFract:
14867 return ShortFractTy;
14868 case BuiltinType::UFract:
14869 return FractTy;
14870 case BuiltinType::ULongFract:
14871 return LongFractTy;
14872 case BuiltinType::SatUShortFract:
14873 return SatShortFractTy;
14874 case BuiltinType::SatUFract:
14875 return SatFractTy;
14876 case BuiltinType::SatULongFract:
14877 return SatLongFractTy;
14878 default:
14879 llvm_unreachable("Unexpected unsigned fixed point type");
14880 }
14881}
14882
14883// Given a list of FMV features, return a concatenated list of the
14884// corresponding backend features (which may contain duplicates).
14885static std::vector<std::string> getFMVBackendFeaturesFor(
14886 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
14887 std::vector<std::string> BackendFeats;
14888 llvm::AArch64::ExtensionSet FeatureBits;
14889 for (StringRef F : FMVFeatStrings)
14890 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
14891 if (FMVExt->ID)
14892 FeatureBits.enable(*FMVExt->ID);
14893 FeatureBits.toLLVMFeatureList(BackendFeats);
14894 return BackendFeats;
14895}
14896
14897ParsedTargetAttr
14898ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
14899 assert(TD != nullptr);
14900 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
14901
14902 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
14903 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
14904 });
14905 return ParsedAttr;
14906}
14907
14908void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14909 const FunctionDecl *FD) const {
14910 if (FD)
14911 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
14912 else
14913 Target->initFeatureMap(FeatureMap, getDiagnostics(),
14914 Target->getTargetOpts().CPU,
14915 Target->getTargetOpts().Features);
14916}
14917
14918// Fills in the supplied string map with the set of target features for the
14919// passed in function.
14920void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
14921 GlobalDecl GD) const {
14922 StringRef TargetCPU = Target->getTargetOpts().CPU;
14923 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
14924 if (const auto *TD = FD->getAttr<TargetAttr>()) {
14926
14927 // Make a copy of the features as passed on the command line into the
14928 // beginning of the additional features from the function to override.
14929 // AArch64 handles command line option features in parseTargetAttr().
14930 if (!Target->getTriple().isAArch64())
14931 ParsedAttr.Features.insert(
14932 ParsedAttr.Features.begin(),
14933 Target->getTargetOpts().FeaturesAsWritten.begin(),
14934 Target->getTargetOpts().FeaturesAsWritten.end());
14935
14936 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
14937 TargetCPU = ParsedAttr.CPU;
14938
14939 // Now populate the feature map, first with the TargetCPU which is either
14940 // the default or a new one from the target attribute string. Then we'll use
14941 // the passed in features (FeaturesAsWritten) along with the new ones from
14942 // the attribute.
14943 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
14944 ParsedAttr.Features);
14945 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
14947 Target->getCPUSpecificCPUDispatchFeatures(
14948 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
14949 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
14950 Features.insert(Features.begin(),
14951 Target->getTargetOpts().FeaturesAsWritten.begin(),
14952 Target->getTargetOpts().FeaturesAsWritten.end());
14953 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14954 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
14955 if (Target->getTriple().isAArch64()) {
14957 TC->getFeatures(Feats, GD.getMultiVersionIndex());
14958 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
14959 Features.insert(Features.begin(),
14960 Target->getTargetOpts().FeaturesAsWritten.begin(),
14961 Target->getTargetOpts().FeaturesAsWritten.end());
14962 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14963 } else if (Target->getTriple().isRISCV()) {
14964 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14965 std::vector<std::string> Features;
14966 if (VersionStr != "default") {
14967 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
14968 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14969 ParsedAttr.Features.end());
14970 }
14971 Features.insert(Features.begin(),
14972 Target->getTargetOpts().FeaturesAsWritten.begin(),
14973 Target->getTargetOpts().FeaturesAsWritten.end());
14974 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14975 } else {
14976 std::vector<std::string> Features;
14977 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
14978 if (VersionStr.starts_with("arch="))
14979 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
14980 else if (VersionStr != "default")
14981 Features.push_back((StringRef{"+"} + VersionStr).str());
14982 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
14983 }
14984 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
14985 std::vector<std::string> Features;
14986 if (Target->getTriple().isRISCV()) {
14987 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
14988 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
14989 ParsedAttr.Features.end());
14990 } else {
14991 assert(Target->getTriple().isAArch64());
14993 TV->getFeatures(Feats);
14994 Features = getFMVBackendFeaturesFor(Feats);
14995 }
14996 Features.insert(Features.begin(),
14997 Target->getTargetOpts().FeaturesAsWritten.begin(),
14998 Target->getTargetOpts().FeaturesAsWritten.end());
14999 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15000 } else {
15001 FeatureMap = Target->getTargetOpts().FeatureMap;
15002 }
15003}
15004
15006 CanQualType KernelNameType,
15007 const FunctionDecl *FD) {
15008 // Host and device compilation may use different ABIs and different ABIs
15009 // may allocate name mangling discriminators differently. A discriminator
15010 // override is used to ensure consistent discriminator allocation across
15011 // host and device compilation.
15012 auto DeviceDiscriminatorOverrider =
15013 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15014 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15015 if (RD->isLambda())
15016 return RD->getDeviceLambdaManglingNumber();
15017 return std::nullopt;
15018 };
15019 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15020 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15021
15022 // Construct a mangled name for the SYCL kernel caller offload entry point.
15023 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15024 // name the SYCL kernel caller offload entry point function. This mangling
15025 // does not suffice to clearly identify symbols that correspond to SYCL
15026 // kernel caller functions, nor is this mangling natural for targets that
15027 // use a non-Itanium ABI.
15028 std::string Buffer;
15029 Buffer.reserve(128);
15030 llvm::raw_string_ostream Out(Buffer);
15031 MC->mangleCanonicalTypeName(KernelNameType, Out);
15032 std::string KernelName = Out.str();
15033
15034 return {KernelNameType, FD, KernelName};
15035}
15036
15038 // If the function declaration to register is invalid or dependent, the
15039 // registration attempt is ignored.
15040 if (FD->isInvalidDecl() || FD->isTemplated())
15041 return;
15042
15043 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15044 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15045
15046 // Be tolerant of multiple registration attempts so long as each attempt
15047 // is for the same entity. Callers are obligated to detect and diagnose
15048 // conflicting kernel names prior to calling this function.
15049 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15050 auto IT = SYCLKernels.find(KernelNameType);
15051 assert((IT == SYCLKernels.end() ||
15052 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15053 "SYCL kernel name conflict");
15054 (void)IT;
15055 SYCLKernels.insert(std::make_pair(
15056 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15057}
15058
15060 CanQualType KernelNameType = getCanonicalType(T);
15061 return SYCLKernels.at(KernelNameType);
15062}
15063
15065 CanQualType KernelNameType = getCanonicalType(T);
15066 auto IT = SYCLKernels.find(KernelNameType);
15067 if (IT != SYCLKernels.end())
15068 return &IT->second;
15069 return nullptr;
15070}
15071
15073 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15074 return *OMPTraitInfoVector.back();
15075}
15076
15079 const ASTContext::SectionInfo &Section) {
15080 if (Section.Decl)
15081 return DB << Section.Decl;
15082 return DB << "a prior #pragma section";
15083}
15084
15085bool ASTContext::mayExternalize(const Decl *D) const {
15086 bool IsInternalVar =
15087 isa<VarDecl>(D) &&
15089 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15090 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15091 (D->hasAttr<CUDAConstantAttr>() &&
15092 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15093 // CUDA/HIP: managed variables need to be externalized since it is
15094 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15095 // anonymous name space needs to be externalized to avoid duplicate symbols.
15096 return (IsInternalVar &&
15097 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15098 (D->hasAttr<CUDAGlobalAttr>() &&
15100 GVA_Internal);
15101}
15102
15104 return mayExternalize(D) &&
15105 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15107}
15108
15109StringRef ASTContext::getCUIDHash() const {
15110 if (!CUIDHash.empty())
15111 return CUIDHash;
15112 if (LangOpts.CUID.empty())
15113 return StringRef();
15114 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15115 return CUIDHash;
15116}
15117
15118const CXXRecordDecl *
15120 assert(ThisClass);
15121 assert(ThisClass->isPolymorphic());
15122 const CXXRecordDecl *PrimaryBase = ThisClass;
15123 while (1) {
15124 assert(PrimaryBase);
15125 assert(PrimaryBase->isPolymorphic());
15126 auto &Layout = getASTRecordLayout(PrimaryBase);
15127 auto Base = Layout.getPrimaryBase();
15128 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15129 break;
15130 PrimaryBase = Base;
15131 }
15132 return PrimaryBase;
15133}
15134
15136 StringRef MangledName) {
15137 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15138 assert(Method->isVirtual());
15139 bool DefaultIncludesPointerAuth =
15140 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15141
15142 if (!DefaultIncludesPointerAuth)
15143 return true;
15144
15145 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15146 if (Existing != ThunksToBeAbbreviated.end())
15147 return Existing->second.contains(MangledName.str());
15148
15149 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15150 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15151 auto VtableContext = getVTableContext();
15152 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15153 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15154 for (const auto &Thunk : *ThunkInfos) {
15155 SmallString<256> ElidedName;
15156 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15157 if (Destructor)
15158 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15159 Thunk, /* elideOverrideInfo */ true,
15160 ElidedNameStream);
15161 else
15162 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15163 ElidedNameStream);
15164 SmallString<256> MangledName;
15165 llvm::raw_svector_ostream mangledNameStream(MangledName);
15166 if (Destructor)
15167 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15168 Thunk, /* elideOverrideInfo */ false,
15169 mangledNameStream);
15170 else
15171 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15172 mangledNameStream);
15173
15174 Thunks[ElidedName].push_back(std::string(MangledName));
15175 }
15176 }
15177 llvm::StringSet<> SimplifiedThunkNames;
15178 for (auto &ThunkList : Thunks) {
15179 llvm::sort(ThunkList.second);
15180 SimplifiedThunkNames.insert(ThunkList.second[0]);
15181 }
15182 bool Result = SimplifiedThunkNames.contains(MangledName);
15183 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15184 return Result;
15185}
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:3510
Represents a loop initializing the elements of an array.
Definition Expr.h:5902
llvm::APInt getArraySize() const
Definition Expr.h:5924
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5922
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3740
QualType getElementType() const
Definition TypeBase.h:3734
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3744
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6814
Expr * getPtr() const
Definition Expr.h:6845
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8091
Attr - This represents one attribute.
Definition Attr.h:44
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8139
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8156
unsigned getNumBits() const
Definition TypeBase.h:8151
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:3542
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3559
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
Kind getKind() const
Definition TypeBase.h:3212
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3363
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:228
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2225
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1186
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
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:3760
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3856
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3875
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4394
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4411
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4391
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4402
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3436
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3472
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3525
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2102
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
const DeclContext * getParentFunctionOrMethod(bool LexicalParent=false) const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition DeclBase.cpp:319
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:859
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:984
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:360
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h: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:4061
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4083
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8184
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4011
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4040
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4126
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4432
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4452
Represents a dependent template name that cannot be resolved prior to template instantiation.
void Profile(llvm::FoldingSetNodeID &ID) const
IdentifierOrOverloadedOperator getName() const
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
bool hasTemplateKeyword() const
Was this template name was preceeded by the template keyword?
Internal representation of canonical, dependent typeof(expr) types.
Definition TypeBase.h:6211
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6216
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4252
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:905
Represents an enum.
Definition Decl.h: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:4267
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:5234
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5641
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5679
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5066
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5100
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4844
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4860
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5770
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5573
unsigned getNumParams() const
Definition TypeBase.h:5544
QualType getParamType(unsigned i) const
Definition TypeBase.h:5546
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:3956
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5579
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5670
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5739
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5735
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4573
CallingConv getCC() const
Definition TypeBase.h:4632
unsigned getRegParm() const
Definition TypeBase.h:4625
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4621
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4644
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4488
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4528
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4462
ExtInfo getExtInfo() const
Definition TypeBase.h:4818
QualType getReturnType() const
Definition TypeBase.h:4802
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5032
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3926
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
@ Relative
Components in the vtable are relative offsets between the vtable and the other structs/functions.
@ Pointer
Components in the vtable are pointers to other structs/functions.
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
A global _GUID constant.
Definition DeclCXX.h:4398
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4435
MSGuidDeclParts Parts
Definition DeclCXX.h:4400
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6145
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:52
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4351
static bool isValidElementType(QualType T)
Valid elements types are the following:
Definition TypeBase.h:4358
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3696
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:144
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:224
This represents a decl that may have a name.
Definition Decl.h: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:7849
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:7905
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:7986
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:7980
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8062
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7942
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:7963
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7917
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:7957
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:8024
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:7969
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:8122
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:8198
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:8371
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:8418
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8376
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:8287
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8413
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8327
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
QualType getCanonicalType() const
Definition TypeBase.h:8339
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8381
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8308
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8360
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:8344
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8291
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:8319
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:8227
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8234
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:384
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:638
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:689
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:624
bool hasUnaligned() const
Definition TypeBase.h:511
bool hasAddressSpace() const
Definition TypeBase.h:570
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
unsigned getFastQualifiers() const
Definition TypeBase.h:619
void removeAddressSpace()
Definition TypeBase.h:596
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:455
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
bool empty() const
Definition TypeBase.h:647
void addObjCGCAttr(GC type)
Definition TypeBase.h:524
LangAS getAddressSpace() const
Definition TypeBase.h:571
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition Decl.h: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:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3599
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1799
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1184
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h: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:6177
A container of type source information.
Definition TypeBase.h:8258
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:8544
bool isVoidType() const
Definition TypeBase.h:8880
bool isObjCBuiltinType() const
Definition TypeBase.h:8744
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:8631
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:8627
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:8623
bool isCharType() const
Definition Type.cpp:2132
bool isPointerType() const
Definition TypeBase.h:8524
bool isArrayParameterType() const
Definition TypeBase.h:8639
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8924
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9167
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:8964
bool isEnumeralType() const
Definition TypeBase.h:8655
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8714
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:8998
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:8789
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8647
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:8936
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8952
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:8726
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8960
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9153
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:8520
bool isObjCObjectPointerType() const
Definition TypeBase.h:8693
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:8978
bool isVectorType() const
Definition TypeBase.h:8663
bool isObjCClassType() const
Definition TypeBase.h:8732
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:8532
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:9100
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:8917
bool isRecordType() const
Definition TypeBase.h:8651
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:6121
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4483
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5982
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6019
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4037
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4102
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3792
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3374
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6059
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h: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:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4199
VectorKind getVectorKind() const
Definition TypeBase.h:4195
QualType getElementType() const
Definition TypeBase.h:4189
A full comment attached to a declaration, contains block content.
Definition Comment.h:1104
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1142
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1136
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1132
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:41
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1792
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8422
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:3719
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5895
@ Struct
The "struct" keyword.
Definition TypeBase.h:5892
@ Class
The "class" keyword.
Definition TypeBase.h:5901
constexpr uint16_t SelPointerConstantDiscriminator
Constant discriminator to be used with objective-c sel pointers.
bool isDiscardableGVALinkage(GVALinkage L)
Definition Linkage.h:80
BuiltinTemplateKind
Kinds of BuiltinTemplateDecl.
Definition Builtins.h:462
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h: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:4145
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4154
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4142
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4160
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4163
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4157
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:176
@ None
The alignment was not explicit in code.
Definition ASTContext.h:178
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:187
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:181
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:184
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5865
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5870
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5876
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5873
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5883
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h: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:5323
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5325
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5328
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5331
Extra information about a function prototype.
Definition TypeBase.h:5351
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5397
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5356
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5401
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5390
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:207
bool isAlignRequired()
Definition ASTContext.h:199
AlignRequirementKind AlignRequirement
Definition ASTContext.h:193
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:983
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1009
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:986