clang 24.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"
18#include "clang/AST/ASTLambda.h"
22#include "clang/AST/Attr.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Comment.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclBase.h"
28#include "clang/AST/DeclCXX.h"
30#include "clang/AST/DeclObjC.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
38#include "clang/AST/Mangle.h"
44#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
57#include "clang/Basic/LLVM.h"
59#include "clang/Basic/Linkage.h"
60#include "clang/Basic/Module.h"
70#include "clang/Lex/MacroInfo.h"
71#include "llvm/ADT/APFixedPoint.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/APSInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/SmallPtrSet.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/ADT/StringRef.h"
84#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
85#include "llvm/Support/Capacity.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/MD5.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/SipHash.h"
92#include "llvm/Support/raw_ostream.h"
93#include "llvm/TargetParser/AArch64TargetParser.h"
94#include "llvm/TargetParser/RISCVTargetParser.h"
95#include "llvm/TargetParser/Triple.h"
96#include <algorithm>
97#include <cassert>
98#include <cstddef>
99#include <cstdint>
100#include <cstdlib>
101#include <map>
102#include <memory>
103#include <optional>
104#include <string>
105#include <tuple>
106#include <utility>
107
108using namespace clang;
109
120
121/// \returns The locations that are relevant when searching for Doc comments
122/// related to \p Key.
125 SourceManager &SourceMgr) {
126 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
127 SourceLocation DefLoc = MI->getDefinitionLoc();
128 if (DefLoc.isInvalid() || !DefLoc.isFileID())
129 return {};
130
131 // The macro's definition location points at its name (e.g. FOO in
132 // `#define FOO 1`). The text between a preceding documentation comment
133 // and the name contains the `#define` directive itself, which would be
134 // rejected by the preprocessor-directive guard in
135 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
136 // the guard only fires when something *else* sits between the comment
137 // and our directive.
138 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
139 bool Invalid = false;
140 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
141 if (Invalid)
142 return {};
143 unsigned Offset = Decomposed.second;
144 if (size_t Found = Buffer.find_last_of("#\n", Offset);
145 Found != StringRef::npos)
146 Offset = Found;
147 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
148 .getLocWithOffset(Offset)};
149 }
150
151 const auto *D = cast<const Decl *>(Key);
152 assert(D);
153
154 // User can not attach documentation to implicit declarations.
155 if (D->isImplicit())
156 return {};
157
158 // User can not attach documentation to implicit instantiations.
159 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
160 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
161 return {};
162 }
163
164 if (const auto *VD = dyn_cast<VarDecl>(D)) {
165 if (VD->isStaticDataMember() &&
166 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
167 return {};
168 }
169
170 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
171 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
172 return {};
173 }
174
175 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
176 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
177 if (TSK == TSK_ImplicitInstantiation ||
178 TSK == TSK_Undeclared)
179 return {};
180 }
181
182 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
183 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
184 return {};
185 }
186 if (const auto *TD = dyn_cast<TagDecl>(D)) {
187 // When tag declaration (but not definition!) is part of the
188 // decl-specifier-seq of some other declaration, it doesn't get comment
189 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
190 return {};
191 }
192 // TODO: handle comments for function parameters properly.
193 if (isa<ParmVarDecl>(D))
194 return {};
195
196 // TODO: we could look up template parameter documentation in the template
197 // documentation.
201 return {};
202
204 // Find declaration location.
205 // For Objective-C declarations we generally don't expect to have multiple
206 // declarators, thus use declaration starting location as the "declaration
207 // location".
208 // For all other declarations multiple declarators are used quite frequently,
209 // so we use the location of the identifier as the "declaration location".
210 SourceLocation BaseLocation;
214 // Allow association with Y across {} in `typedef struct X {} Y`.
216 BaseLocation = D->getBeginLoc();
217 else
218 BaseLocation = D->getLocation();
219
220 if (!D->getLocation().isMacroID()) {
221 Locations.emplace_back(BaseLocation);
222 } else {
223 const auto *DeclCtx = D->getDeclContext();
224
225 // When encountering definitions generated from a macro (that are not
226 // contained by another declaration in the macro) we need to try and find
227 // the comment at the location of the expansion but if there is no comment
228 // there we should retry to see if there is a comment inside the macro as
229 // well. To this end we return first BaseLocation to first look at the
230 // expansion site, the second value is the spelling location of the
231 // beginning of the declaration defined inside the macro.
232 if (!(DeclCtx &&
233 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
234 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
235 }
236
237 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
238 // we don't refer to the macro argument location at the expansion site (this
239 // can happen if the name's spelling is provided via macro argument), and
240 // always to the declaration itself.
241 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
242 }
243
244 return Locations;
245}
246
248 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
249 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
250 // If the declaration doesn't map directly to a location in a file, we
251 // can't find the comment.
252 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
253 return nullptr;
254
255 // If there are no comments anywhere, we won't find anything.
256 if (CommentsInTheFile.empty())
257 return nullptr;
258
259 const auto *D = dyn_cast<const Decl *>(Key);
260 const bool IsMacro = isa<const MacroInfo *>(Key);
261
262 // Decompose the location for the declaration and find the beginning of the
263 // file buffer.
264 const FileIDAndOffset LocDecomp =
265 SourceMgr.getDecomposedLoc(RepresentativeLoc);
266
267 // Slow path.
268 auto OffsetCommentBehindDecl =
269 CommentsInTheFile.lower_bound(LocDecomp.second);
270
271 // First check whether we have a trailing comment.
272 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
273 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
274 if ((CommentBehindDecl->isDocumentation() ||
275 LangOpts.CommentOpts.ParseAllComments) &&
276 CommentBehindDecl->isTrailingComment() &&
277 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
279 isa<ObjCPropertyDecl>(D))))) {
280
281 // Check that Doxygen trailing comment comes after the declaration, starts
282 // on the same line and in the same file as the declaration.
283 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
284 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
285 OffsetCommentBehindDecl->first)) {
286 return CommentBehindDecl;
287 }
288 }
289 }
290
291 // The comment just after the declaration was not a trailing comment.
292 // Let's look at the previous comment.
293 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
294 return nullptr;
295
296 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
297 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
298
299 // Check that we actually have a non-member Doxygen comment.
300 if (!(CommentBeforeDecl->isDocumentation() ||
301 LangOpts.CommentOpts.ParseAllComments) ||
302 CommentBeforeDecl->isTrailingComment())
303 return nullptr;
304
305 // Decompose the end of the comment.
306 const unsigned CommentEndOffset =
307 Comments.getCommentEndOffset(CommentBeforeDecl);
308
309 // Get the corresponding buffer.
310 bool Invalid = false;
311 const char *Buffer =
312 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
313 if (Invalid)
314 return nullptr;
315
316 // Extract text between the comment and declaration.
317 StringRef Text(Buffer + CommentEndOffset,
318 LocDecomp.second - CommentEndOffset);
319
320 // There should be no other declarations or preprocessor directives between
321 // comment and declaration.
322 if (Text.find_last_of(";{}#@") != StringRef::npos)
323 return nullptr;
324
325 return CommentBeforeDecl;
326}
327
329 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
330
331 for (const auto Loc : Locs) {
332 // If the declaration or macro doesn't map directly to a location in a file,
333 // we can't find the comment.
334 if (Loc.isInvalid() || !Loc.isFileID())
335 continue;
336
338 ExternalSource->ReadComments();
339 CommentsLoaded = true;
340 }
341
342 if (Comments.empty())
343 continue;
344
345 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
346 if (!File.isValid())
347 continue;
348
349 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
350 if (!CommentsInThisFile || CommentsInThisFile->empty())
351 continue;
352
353 if (RawComment *Comment =
354 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
355 return Comment;
356 }
357
358 return nullptr;
359}
360
362 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
363 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
364 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
365}
366
367const RawComment *
369 const Decl **OriginalDecl) const {
370 if (Key.isNull()) {
371 if (OriginalDecl)
372 *OriginalDecl = nullptr;
373 return nullptr;
374 }
375
376 // Macros have no redeclaration chain: look up directly, populate the cache,
377 // and return.
378 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
379 if (OriginalDecl)
380 *OriginalDecl = nullptr;
381 auto Existing = RawComments.find(Key);
382 if (Existing != RawComments.end())
383 return Existing->second;
384 if (const RawComment *RC = getRawCommentNoCache(Key)) {
385 cacheRawComment(MI, *RC);
386 return RC;
387 }
388 return nullptr;
389 }
390
391 const Decl *D = cast<const Decl *>(Key);
392 D = &adjustDeclToTemplate(*D);
393
394 // Any comment directly attached to D?
395 {
396 auto DeclComment = RawComments.find(D);
397 if (DeclComment != RawComments.end()) {
398 if (OriginalDecl)
399 *OriginalDecl = D;
400 return DeclComment->second;
401 }
402 }
403
404 // Any comment attached to any redeclaration of D?
405 const Decl *CanonicalD = D->getCanonicalDecl();
406 if (!CanonicalD)
407 return nullptr;
408
409 {
410 auto RedeclComment = RedeclChainComments.find(CanonicalD);
411 if (RedeclComment != RedeclChainComments.end()) {
412 if (OriginalDecl)
413 *OriginalDecl = RedeclComment->second;
414 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
415 assert(CommentAtRedecl != RawComments.end() &&
416 "This decl is supposed to have comment attached.");
417 return CommentAtRedecl->second;
418 }
419 }
420
421 // Any redeclarations of D that we haven't checked for comments yet?
422 const Decl *LastCheckedRedecl = [&]() {
423 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
424 bool CanUseCommentlessCache = false;
425 if (LastChecked) {
426 for (auto *Redecl : CanonicalD->redecls()) {
427 if (Redecl == D) {
428 CanUseCommentlessCache = true;
429 break;
430 }
431 if (Redecl == LastChecked)
432 break;
433 }
434 }
435 // FIXME: This could be improved so that even if CanUseCommentlessCache
436 // is false, once we've traversed past CanonicalD we still skip ahead
437 // LastChecked.
438 return CanUseCommentlessCache ? LastChecked : nullptr;
439 }();
440
441 for (const Decl *Redecl : D->redecls()) {
442 assert(Redecl);
443 // Skip all redeclarations that have been checked previously.
444 if (LastCheckedRedecl) {
445 if (LastCheckedRedecl == Redecl) {
446 LastCheckedRedecl = nullptr;
447 }
448 continue;
449 }
450 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
451 if (RedeclComment) {
452 cacheRawComment(Redecl, *RedeclComment);
453 if (OriginalDecl)
454 *OriginalDecl = Redecl;
455 return RedeclComment;
456 }
457 CommentlessRedeclChains[CanonicalD] = Redecl;
458 }
459
460 if (OriginalDecl)
461 *OriginalDecl = nullptr;
462 return nullptr;
463}
464
466 const RawComment &Comment) const {
467 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
468 RawComments.try_emplace(Original, &Comment);
469 if (const auto *D = dyn_cast<const Decl *>(Original)) {
470 const Decl *const CanonicalDecl = D->getCanonicalDecl();
471 RedeclChainComments.try_emplace(CanonicalDecl, D);
472 CommentlessRedeclChains.erase(CanonicalDecl);
473 }
474}
475
476static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
478 const DeclContext *DC = ObjCMethod->getDeclContext();
479 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
480 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
481 if (!ID)
482 return;
483 // Add redeclared method here.
484 for (const auto *Ext : ID->known_extensions()) {
485 if (ObjCMethodDecl *RedeclaredMethod =
486 Ext->getMethod(ObjCMethod->getSelector(),
487 ObjCMethod->isInstanceMethod()))
488 Redeclared.push_back(RedeclaredMethod);
489 }
490 }
491}
492
494 const Preprocessor *PP) {
495 if (Comments.empty() || Decls.empty())
496 return;
497
498 FileID File;
499 for (const Decl *D : Decls) {
500 if (D->isInvalidDecl())
501 continue;
502
503 D = &adjustDeclToTemplate(*D);
504 SourceLocation Loc = D->getLocation();
505 if (Loc.isValid()) {
506 // See if there are any new comments that are not attached to a decl.
507 // The location doesn't have to be precise - we care only about the file.
508 File = SourceMgr.getDecomposedLoc(Loc).first;
509 break;
510 }
511 }
512
513 if (File.isInvalid())
514 return;
515
516 auto CommentsInThisFile = Comments.getCommentsInFile(File);
517 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
518 CommentsInThisFile->rbegin()->second->isAttached())
519 return;
520
521 // There is at least one comment not attached to a decl.
522 // Maybe it should be attached to one of Decls?
523 //
524 // Note that this way we pick up not only comments that precede the
525 // declaration, but also comments that *follow* the declaration -- thanks to
526 // the lookahead in the lexer: we've consumed the semicolon and looked
527 // ahead through comments.
528 for (const Decl *D : Decls) {
529 assert(D);
530 if (D->isInvalidDecl())
531 continue;
532
533 D = &adjustDeclToTemplate(*D);
534
535 if (RawComments.count(D) > 0)
536 continue;
537
538 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
539
540 for (const auto DeclLoc : DeclLocs) {
541 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
542 continue;
543
544 if (RawComment *const DocComment =
545 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
546 cacheRawComment(D, *DocComment);
547 comments::FullComment *FC = DocComment->parse(*this, PP, D);
548 ParsedComments[D->getCanonicalDecl()] = FC;
549 break;
550 }
551 }
552 }
553}
554
556 const Decl *D) const {
557 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
558 ThisDeclInfo->CommentDecl = D;
559 ThisDeclInfo->IsFilled = false;
560 ThisDeclInfo->fill();
561 ThisDeclInfo->CommentDecl = FC->getDecl();
562 if (!ThisDeclInfo->TemplateParameters)
563 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
565 new (*this) comments::FullComment(FC->getBlocks(),
566 ThisDeclInfo);
567 return CFC;
568}
569
571 const RawComment *RC = getRawCommentNoCache(D);
572 return RC ? RC->parse(*this, nullptr, D) : nullptr;
573}
574
576 const Decl *D,
577 const Preprocessor *PP) const {
578 if (!D || D->isInvalidDecl())
579 return nullptr;
580 D = &adjustDeclToTemplate(*D);
581
582 const Decl *Canonical = D->getCanonicalDecl();
583 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
584 ParsedComments.find(Canonical);
585
586 if (Pos != ParsedComments.end()) {
587 if (Canonical != D) {
588 comments::FullComment *FC = Pos->second;
590 return CFC;
591 }
592 return Pos->second;
593 }
594
595 const Decl *OriginalDecl = nullptr;
596
597 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
598 if (!RC) {
601 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
602 if (OMD && OMD->isPropertyAccessor())
603 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
604 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
605 return cloneFullComment(FC, D);
606 if (OMD)
607 addRedeclaredMethods(OMD, Overridden);
608 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
609 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
610 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
611 return cloneFullComment(FC, D);
612 }
613 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
614 // Attach any tag type's documentation to its typedef if latter
615 // does not have one of its own.
616 QualType QT = TD->getUnderlyingType();
617 if (const auto *TT = QT->getAs<TagType>())
618 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
619 return cloneFullComment(FC, D);
620 }
621 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
622 while (IC->getSuperClass()) {
623 IC = IC->getSuperClass();
625 return cloneFullComment(FC, D);
626 }
627 }
628 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
629 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
631 return cloneFullComment(FC, D);
632 }
633 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
634 if (!(RD = RD->getDefinition()))
635 return nullptr;
636 // Check non-virtual bases.
637 for (const auto &I : RD->bases()) {
638 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
639 continue;
640 QualType Ty = I.getType();
641 if (Ty.isNull())
642 continue;
644 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
645 continue;
646
648 return cloneFullComment(FC, D);
649 }
650 }
651 // Check virtual bases.
652 for (const auto &I : RD->vbases()) {
653 if (I.getAccessSpecifier() != AS_public)
654 continue;
655 QualType Ty = I.getType();
656 if (Ty.isNull())
657 continue;
658 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
659 if (!(VirtualBase= VirtualBase->getDefinition()))
660 continue;
662 return cloneFullComment(FC, D);
663 }
664 }
665 }
666 return nullptr;
667 }
668
669 // If the RawComment was attached to other redeclaration of this Decl, we
670 // should parse the comment in context of that other Decl. This is important
671 // because comments can contain references to parameter names which can be
672 // different across redeclarations.
673 if (D != OriginalDecl && OriginalDecl)
674 return getCommentForDecl(OriginalDecl, PP);
675
676 comments::FullComment *FC = RC->parse(*this, PP, D);
677 ParsedComments[Canonical] = FC;
678 return FC;
679}
680
681void ASTContext::CanonicalTemplateTemplateParm::Profile(
682 llvm::FoldingSetNodeID &ID, const ASTContext &C,
684 ID.AddInteger(Parm->getDepth());
685 ID.AddInteger(Parm->getPosition());
686 ID.AddBoolean(Parm->isParameterPack());
687 ID.AddInteger(Parm->templateParameterKind());
688
690 ID.AddInteger(Params->size());
692 PEnd = Params->end();
693 P != PEnd; ++P) {
694 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
695 ID.AddInteger(0);
696 ID.AddBoolean(TTP->isParameterPack());
697 ID.AddInteger(
698 TTP->getNumExpansionParameters().toInternalRepresentation());
699 continue;
700 }
701
702 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
703 ID.AddInteger(1);
704 ID.AddBoolean(NTTP->isParameterPack());
705 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
706 .getAsOpaquePtr());
707 if (NTTP->isExpandedParameterPack()) {
708 ID.AddBoolean(true);
709 ID.AddInteger(NTTP->getNumExpansionTypes());
710 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
711 QualType T = NTTP->getExpansionType(I);
712 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
713 }
714 } else
715 ID.AddBoolean(false);
716 continue;
717 }
718
719 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
720 ID.AddInteger(2);
721 Profile(ID, C, TTP);
722 }
723}
724
725TemplateTemplateParmDecl *
727 TemplateTemplateParmDecl *TTP) const {
728 // Check if we already have a canonical template template parameter.
729 llvm::FoldingSetNodeID ID;
730 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
731 llvm::FoldingSetInsertToken Token;
732 CanonicalTemplateTemplateParm *Canonical =
733 CanonTemplateTemplateParms.lookup(ID, Token);
734 if (Canonical)
735 return Canonical->getParam();
736
737 // Build a canonical template parameter list.
739 SmallVector<NamedDecl *, 4> CanonParams;
740 CanonParams.reserve(Params->size());
742 PEnd = Params->end();
743 P != PEnd; ++P) {
744 // Note that, per C++20 [temp.over.link]/6, when determining whether
745 // template-parameters are equivalent, constraints are ignored.
746 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
749 TTP->getDepth(), TTP->getIndex(), nullptr, false,
750 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
751 TTP->getNumExpansionParameters());
752 CanonParams.push_back(NewTTP);
753 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
757 if (NTTP->isExpandedParameterPack()) {
758 SmallVector<QualType, 2> ExpandedTypes;
760 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
761 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
762 ExpandedTInfos.push_back(
763 getTrivialTypeSourceInfo(ExpandedTypes.back()));
764 }
765
769 NTTP->getDepth(),
770 NTTP->getPosition(), nullptr,
771 T,
772 TInfo,
773 ExpandedTypes,
774 ExpandedTInfos);
775 } else {
779 NTTP->getDepth(),
780 NTTP->getPosition(), nullptr,
781 T,
782 NTTP->isParameterPack(),
783 TInfo);
784 }
785 CanonParams.push_back(Param);
786 } else
787 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
789 }
790
793 TTP->getPosition(), TTP->isParameterPack(), nullptr,
795 /*Typename=*/false,
797 CanonParams, SourceLocation(),
798 /*RequiresClause=*/nullptr));
799
800 // Get the new insert position for the node we care about.
801 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
802 assert(!Canonical && "Shouldn't be in the map!");
803 (void)Canonical;
804
805 // Create the canonical template template parameter entry.
806 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
807 CanonTemplateTemplateParms.insert(Canonical, Token);
808 return CanonTTP;
809}
810
813 TemplateTemplateParmDecl *TTP) const {
814 llvm::FoldingSetNodeID ID;
815 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
816 llvm::FoldingSetInsertToken Token;
817 CanonicalTemplateTemplateParm *Canonical =
818 CanonTemplateTemplateParms.lookup(ID, Token);
819 return Canonical ? Canonical->getParam() : nullptr;
820}
821
824 TemplateTemplateParmDecl *CanonTTP) const {
825 llvm::FoldingSetNodeID ID;
826 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
827 llvm::FoldingSetInsertToken Token;
828 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
829 return Existing->getParam();
830 CanonTemplateTemplateParms.insert(
831 new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
832 return CanonTTP;
833}
834
835/// For the purposes of overflow pattern exclusion, does this match the
836/// while(i--) pattern?
837static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
838 if (UO->getOpcode() != UO_PostDec)
839 return false;
840
841 if (!UO->getType()->isUnsignedIntegerType())
842 return false;
843
844 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
847 return false;
848
849 // all Parents (usually just one) must be a WhileStmt
850 return llvm::all_of(
852 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
853}
854
856 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
857 // ... like -1UL;
858 if (UO->getOpcode() == UO_Minus &&
859 getLangOpts().isOverflowPatternExcluded(
861 UO->isIntegerConstantExpr(*this)) {
862 return true;
863 }
864
865 if (matchesPostDecrInWhile(UO, *this))
866 return true;
867
868 return false;
869}
870
871/// Check if a type can have its sanitizer instrumentation elided based on its
872/// presence within an ignorelist.
874 const QualType &Ty) const {
875 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
876 return NoSanitizeL->containsType(Mask, TyName);
877}
878
880 auto Kind = getTargetInfo().getCXXABI().getKind();
881 return getLangOpts().CXXABI.value_or(Kind);
882}
883
884CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
885 if (!LangOpts.CPlusPlus) return nullptr;
886
887 switch (getCXXABIKind()) {
888 case TargetCXXABI::AppleARM64:
889 case TargetCXXABI::Fuchsia:
890 case TargetCXXABI::GenericARM: // Same as Itanium at this level
891 case TargetCXXABI::iOS:
892 case TargetCXXABI::WatchOS:
893 case TargetCXXABI::GenericAArch64:
894 case TargetCXXABI::GenericMIPS:
895 case TargetCXXABI::GenericItanium:
896 case TargetCXXABI::WebAssembly:
897 case TargetCXXABI::XL:
898 return CreateItaniumCXXABI(*this);
899 case TargetCXXABI::Microsoft:
900 return CreateMicrosoftCXXABI(*this);
901 }
902 llvm_unreachable("Invalid CXXABI type!");
903}
904
906 if (!InterpContext) {
907 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
908 }
909 return *InterpContext;
910}
911
913 const LangOptions &LangOpts) {
914 switch (LangOpts.getAddressSpaceMapMangling()) {
916 return TI.useAddressSpaceMapMangling();
918 return true;
920 return false;
921 }
922 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
923}
924
926 IdentifierTable &idents, SelectorTable &sels,
928 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
929 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
930 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
931 DependentSizedMatrixTypes(this_()),
932 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
933 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
934 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
935 AttributedTypes(this_()), DependentBitIntTypes(this_()),
936 HLSLAttributedResourceTypes(this_()),
937 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
938 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
939 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
940 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
941 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
942 LangOpts.XRayNeverInstrumentFiles,
943 LangOpts.XRayAttrListFiles, SM)),
944 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
945 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
946 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
947 DeclarationNames(*this), Comments(SM),
948 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
949 CompCategories(this_()), LastSDM(nullptr, 0) {
951}
952
954 // Release the DenseMaps associated with DeclContext objects.
955 // FIXME: Is this the ideal solution?
956 ReleaseDeclContextMaps();
957
958 // Call all of the deallocation functions on all of their targets.
959 for (auto &Pair : Deallocations)
960 (Pair.first)(Pair.second);
961 Deallocations.clear();
962
963 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
964 // because they can contain DenseMaps.
965 for (llvm::DenseMap<const ObjCInterfaceDecl *,
967 I = ObjCLayouts.begin(),
968 E = ObjCLayouts.end();
969 I != E;)
970 // Increment in loop to prevent using deallocated memory.
971 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
972 R->Destroy(*this);
973 ObjCLayouts.clear();
974
975 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
976 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
977 // Increment in loop to prevent using deallocated memory.
978 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
979 R->Destroy(*this);
980 }
981 ASTRecordLayouts.clear();
982
983 CtorClosureDefaultArgs.clear();
984
985 for (const auto &Value : ModuleInitializers)
986 Value.second->~PerModuleInitializers();
987 ModuleInitializers.clear();
988
989 TUDecl = nullptr;
990 XRayFilter.reset();
991 NoSanitizeL.reset();
992}
993
995
996void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
997 TraversalScope = TopLevelDecls;
999}
1000
1001void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1002 Deallocations.push_back({Callback, Data});
1003}
1004
1005void
1009
1011 llvm::errs() << "\n*** AST Context Stats:\n";
1012 llvm::errs() << " " << Types.size() << " types total.\n";
1013
1014 unsigned counts[] = {
1015#define TYPE(Name, Parent) 0,
1016#define ABSTRACT_TYPE(Name, Parent)
1017#include "clang/AST/TypeNodes.inc"
1018 0 // Extra
1019 };
1020
1021 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1022 Type *T = Types[i];
1023 counts[(unsigned)T->getTypeClass()]++;
1024 }
1025
1026 unsigned Idx = 0;
1027 unsigned TotalBytes = 0;
1028#define TYPE(Name, Parent) \
1029 if (counts[Idx]) \
1030 llvm::errs() << " " << counts[Idx] << " " << #Name \
1031 << " types, " << sizeof(Name##Type) << " each " \
1032 << "(" << counts[Idx] * sizeof(Name##Type) \
1033 << " bytes)\n"; \
1034 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1035 ++Idx;
1036#define ABSTRACT_TYPE(Name, Parent)
1037#include "clang/AST/TypeNodes.inc"
1038
1039 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1040
1041 // Implicit special member functions.
1042 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1044 << " implicit default constructors created\n";
1045 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1047 << " implicit copy constructors created\n";
1048 if (getLangOpts().CPlusPlus)
1049 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1051 << " implicit move constructors created\n";
1052 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1054 << " implicit copy assignment operators created\n";
1055 if (getLangOpts().CPlusPlus)
1056 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1058 << " implicit move assignment operators created\n";
1059 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1061 << " implicit destructors created\n";
1062
1063 if (ExternalSource) {
1064 llvm::errs() << "\n";
1065 ExternalSource->PrintStats();
1066 }
1067
1068 BumpAlloc.PrintStats();
1069}
1070
1072 bool NotifyListeners) {
1073 if (NotifyListeners)
1074 if (auto *Listener = getASTMutationListener();
1076 Listener->RedefinedHiddenDefinition(ND, M);
1077
1078 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1079}
1080
1082 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1083 if (It == MergedDefModules.end())
1084 return;
1085
1086 auto &Merged = It->second;
1087 llvm::DenseSet<Module*> Found;
1088 for (Module *&M : Merged)
1089 if (!Found.insert(M).second)
1090 M = nullptr;
1091 llvm::erase(Merged, nullptr);
1092}
1093
1096 auto MergedIt =
1097 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1098 if (MergedIt == MergedDefModules.end())
1099 return {};
1100 return MergedIt->second;
1101}
1102
1103void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1104 if (LazyInitializers.empty())
1105 return;
1106
1107 auto *Source = Ctx.getExternalSource();
1108 assert(Source && "lazy initializers but no external source");
1109
1110 auto LazyInits = std::move(LazyInitializers);
1111 LazyInitializers.clear();
1112
1113 for (auto ID : LazyInits)
1114 Initializers.push_back(Source->GetExternalDecl(ID));
1115
1116 assert(LazyInitializers.empty() &&
1117 "GetExternalDecl for lazy module initializer added more inits");
1118}
1119
1121 // One special case: if we add a module initializer that imports another
1122 // module, and that module's only initializer is an ImportDecl, simplify.
1123 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1124 auto It = ModuleInitializers.find(ID->getImportedModule());
1125
1126 // Maybe the ImportDecl does nothing at all. (Common case.)
1127 if (It == ModuleInitializers.end())
1128 return;
1129
1130 // Maybe the ImportDecl only imports another ImportDecl.
1131 auto &Imported = *It->second;
1132 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1133 Imported.resolve(*this);
1134 auto *OnlyDecl = Imported.Initializers.front();
1135 if (isa<ImportDecl>(OnlyDecl))
1136 D = OnlyDecl;
1137 }
1138 }
1139
1140 auto *&Inits = ModuleInitializers[M];
1141 if (!Inits)
1142 Inits = new (*this) PerModuleInitializers;
1143 Inits->Initializers.push_back(D);
1144}
1145
1148 auto *&Inits = ModuleInitializers[M];
1149 if (!Inits)
1150 Inits = new (*this) PerModuleInitializers;
1151 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1152 IDs.begin(), IDs.end());
1153}
1154
1156 auto It = ModuleInitializers.find(M);
1157 if (It == ModuleInitializers.end())
1158 return {};
1159
1160 auto *Inits = It->second;
1161 Inits->resolve(*this);
1162 return Inits->Initializers;
1163}
1164
1166 assert(M->isNamedModule());
1167 assert(!CurrentCXXNamedModule &&
1168 "We should set named module for ASTContext for only once");
1169 CurrentCXXNamedModule = M;
1170}
1171
1172bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1173 if (!M1 != !M2)
1174 return false;
1175
1176 /// Get the representative module for M. The representative module is the
1177 /// first module unit for a specific primary module name. So that the module
1178 /// units have the same representative module belongs to the same module.
1179 ///
1180 /// The process is helpful to reduce the expensive string operations.
1181 auto GetRepresentativeModule = [this](const Module *M) {
1182 auto Iter = SameModuleLookupSet.find(M);
1183 if (Iter != SameModuleLookupSet.end())
1184 return Iter->second;
1185
1186 const Module *RepresentativeModule =
1187 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1188 .first->second;
1189 SameModuleLookupSet[M] = RepresentativeModule;
1190 return RepresentativeModule;
1191 };
1192
1193 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1194 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1195}
1196
1198 if (!ExternCContext)
1199 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1200
1201 return ExternCContext;
1202}
1203
1214
1215#define BuiltinTemplate(BTName) \
1216 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1217 if (!Decl##BTName) \
1218 Decl##BTName = \
1219 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1220 return Decl##BTName; \
1221 }
1222#include "clang/Basic/BuiltinTemplates.inc"
1223
1225 RecordDecl::TagKind TK) const {
1226 SourceLocation Loc;
1227 RecordDecl *NewDecl;
1228 if (getLangOpts().CPlusPlus)
1229 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1230 Loc, &Idents.get(Name));
1231 else
1232 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1233 &Idents.get(Name));
1234 NewDecl->setImplicit();
1235 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1236 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1237 return NewDecl;
1238}
1239
1241 StringRef Name) const {
1244 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1245 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1246 NewDecl->setImplicit();
1247 return NewDecl;
1248}
1249
1251 if (!Int128Decl)
1252 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1253 return Int128Decl;
1254}
1255
1257 if (!UInt128Decl)
1258 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1259 return UInt128Decl;
1260}
1261
1262void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1263 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1265 Types.push_back(Ty);
1266}
1267
1269 const TargetInfo *AuxTarget) {
1270 assert((!this->Target || this->Target == &Target) &&
1271 "Incorrect target reinitialization");
1272 assert(VoidTy.isNull() && "Context reinitialized?");
1273
1274 this->Target = &Target;
1275 this->AuxTarget = AuxTarget;
1276
1277 ABI.reset(createCXXABI(Target));
1278 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1279
1280 // C99 6.2.5p19.
1281 InitBuiltinType(VoidTy, BuiltinType::Void);
1282
1283 // C99 6.2.5p2.
1284 InitBuiltinType(BoolTy, BuiltinType::Bool);
1285 // C99 6.2.5p3.
1286 if (LangOpts.CharIsSigned)
1287 InitBuiltinType(CharTy, BuiltinType::Char_S);
1288 else
1289 InitBuiltinType(CharTy, BuiltinType::Char_U);
1290 // C99 6.2.5p4.
1291 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1292 InitBuiltinType(ShortTy, BuiltinType::Short);
1293 InitBuiltinType(IntTy, BuiltinType::Int);
1294 InitBuiltinType(LongTy, BuiltinType::Long);
1295 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1296
1297 // C99 6.2.5p6.
1298 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1299 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1300 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1301 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1302 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1303
1304 // C99 6.2.5p10.
1305 InitBuiltinType(FloatTy, BuiltinType::Float);
1306 InitBuiltinType(DoubleTy, BuiltinType::Double);
1307 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1308
1309 // GNU extension, __float128 for IEEE quadruple precision
1310 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1311
1312 // __ibm128 for IBM extended precision
1313 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1314
1315 // C11 extension ISO/IEC TS 18661-3
1316 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1317
1318 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1319 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1320 InitBuiltinType(AccumTy, BuiltinType::Accum);
1321 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1322 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1323 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1324 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1325 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1326 InitBuiltinType(FractTy, BuiltinType::Fract);
1327 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1328 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1329 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1330 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1331 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1332 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1333 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1334 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1335 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1336 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1337 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1338 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1339 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1340 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1341 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1342 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1343
1344 // GNU extension, 128-bit integers.
1345 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1346 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1347
1348 // C++ 3.9.1p5
1349 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1350 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1351 else // -fshort-wchar makes wchar_t be unsigned.
1352 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1353 if (LangOpts.CPlusPlus && LangOpts.WChar)
1355 else {
1356 // C99 (or C++ using -fno-wchar).
1357 WideCharTy = getFromTargetType(Target.getWCharType());
1358 }
1359
1360 WIntTy = getFromTargetType(Target.getWIntType());
1361
1362 // C++20 (proposed)
1363 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1364
1365 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1366 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1367 else // C99
1368 Char16Ty = getFromTargetType(Target.getChar16Type());
1369
1370 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1371 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1372 else // C99
1373 Char32Ty = getFromTargetType(Target.getChar32Type());
1374
1375 // Placeholder type for type-dependent expressions whose type is
1376 // completely unknown. No code should ever check a type against
1377 // DependentTy and users should never see it; however, it is here to
1378 // help diagnose failures to properly check for type-dependent
1379 // expressions.
1380 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1381
1382 // Placeholder type for functions.
1383 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1384
1385 // Placeholder type for bound members.
1386 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1387
1388 // Placeholder type for unresolved templates.
1389 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1390
1391 // Placeholder type for pseudo-objects.
1392 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1393
1394 // "any" type; useful for debugger-like clients.
1395 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1396
1397 // Placeholder type for unbridged ARC casts.
1398 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1399
1400 // Placeholder type for builtin functions.
1401 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1402
1403 // Placeholder type for OMP array sections.
1404 if (LangOpts.OpenMP) {
1405 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1406 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1407 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1408 }
1409 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1410 // don't bother, as we're just using the same type as OMP.
1411 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1412 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1413 }
1414 if (LangOpts.MatrixTypes)
1415 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1416
1417 // Builtin types for 'id', 'Class', and 'SEL'.
1418 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1419 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1420 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1421
1422 if (LangOpts.OpenCL) {
1423#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1424 InitBuiltinType(SingletonId, BuiltinType::Id);
1425#include "clang/Basic/OpenCLImageTypes.def"
1426
1427 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1428 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1429 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1430 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1431 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1432
1433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1434 InitBuiltinType(Id##Ty, BuiltinType::Id);
1435#include "clang/Basic/OpenCLExtensionTypes.def"
1436 }
1437
1438 if (LangOpts.HLSL) {
1439#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1440 InitBuiltinType(SingletonId, BuiltinType::Id);
1441#include "clang/Basic/HLSLIntangibleTypes.def"
1442
1443#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1444 InitBuiltinType(SingletonId, BuiltinType::Id);
1445#include "clang/Basic/HLSLPackedTypes.def"
1446 }
1447
1448 if (Target.hasAArch64ACLETypes() ||
1449 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1450#define SVE_TYPE(Name, Id, SingletonId) \
1451 InitBuiltinType(SingletonId, BuiltinType::Id);
1452#include "clang/Basic/AArch64ACLETypes.def"
1453 }
1454
1455 if (Target.getTriple().isPPC64()) {
1456#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1457 InitBuiltinType(Id##Ty, BuiltinType::Id);
1458#include "clang/Basic/PPCTypes.def"
1459#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1460 InitBuiltinType(Id##Ty, BuiltinType::Id);
1461#include "clang/Basic/PPCTypes.def"
1462 }
1463
1464 if (Target.hasRISCVVTypes()) {
1465#define RVV_TYPE(Name, Id, SingletonId) \
1466 InitBuiltinType(SingletonId, BuiltinType::Id);
1467#include "clang/Basic/RISCVVTypes.def"
1468 }
1469
1470 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1471#define WASM_TYPE(Name, Id, SingletonId) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/WebAssemblyReferenceTypes.def"
1474 }
1475
1476 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1477#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/AMDGPUTypes.def"
1480 }
1481
1482 if (Target.getTriple().isSPIRV() ||
1483 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1484#define SPIRV_TYPE(Name, Id, SingletonId) \
1485 InitBuiltinType(SingletonId, BuiltinType::Id);
1486#include "clang/Basic/SPIRVTypes.def"
1487 }
1488
1489 // Builtin type for __objc_yes and __objc_no
1490 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1492
1493 ObjCConstantStringType = QualType();
1494
1495 ObjCSuperType = QualType();
1496
1497 // void * type
1498 if (LangOpts.OpenCLGenericAddressSpace) {
1499 auto Q = VoidTy.getQualifiers();
1500 Q.setAddressSpace(LangAS::opencl_generic);
1502 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1503 } else {
1505 }
1506
1507 // nullptr type (C++0x 2.14.7)
1508 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1509
1510 // std::meta::info type (C++26 21.4.1)
1511 InitBuiltinType(MetaInfoTy, BuiltinType::MetaInfo);
1512
1513 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1514 InitBuiltinType(HalfTy, BuiltinType::Half);
1515
1516 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1517
1518 // Builtin type used to help define __builtin_va_list.
1519 VaListTagDecl = nullptr;
1520
1521 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1522 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1525 }
1526}
1527
1529 return SourceMgr.getDiagnostics();
1530}
1531
1533 return new (DeclAttrAllocator.Allocate()) AttrVec;
1534}
1535
1538 return CtorClosureDefaultArgs.lookup(CD);
1539}
1540
1543 assert(!CtorClosureDefaultArgs.contains(CD));
1544 CtorClosureDefaultArgs[CD] = Args;
1545}
1546
1549 auto It =
1550 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1551 if (It != ExplicitInstantiations.end())
1552 return It->second;
1553 return {};
1554}
1555
1558 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1559 EID);
1560}
1561
1564 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1565 TemplateOrInstantiation.find(Var);
1566 if (Pos == TemplateOrInstantiation.end())
1567 return {};
1568
1569 return Pos->second;
1570}
1571
1572void
1575 SourceLocation PointOfInstantiation) {
1576 assert(Inst->isStaticDataMember() && "Not a static data member");
1577 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1579 Tmpl, TSK, PointOfInstantiation));
1580}
1581
1582void
1585 assert(!TemplateOrInstantiation[Inst] &&
1586 "Already noted what the variable was instantiated from");
1587 TemplateOrInstantiation[Inst] = TSI;
1588}
1589
1590NamedDecl *
1592 return InstantiatedFromUsingDecl.lookup(UUD);
1593}
1594
1595void
1597 assert((isa<UsingDecl>(Pattern) ||
1600 "pattern decl is not a using decl");
1601 assert((isa<UsingDecl>(Inst) ||
1604 "instantiation did not produce a using decl");
1605 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1606 InstantiatedFromUsingDecl[Inst] = Pattern;
1607}
1608
1611 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1612}
1613
1615 UsingEnumDecl *Pattern) {
1616 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1617 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1618}
1619
1622 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1623}
1624
1625void
1627 UsingShadowDecl *Pattern) {
1628 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1629 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1630}
1631
1632FieldDecl *
1634 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1635}
1636
1638 FieldDecl *Tmpl) {
1639 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1640 "Instantiated field decl is not unnamed");
1641 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1642 "Template field decl is not unnamed");
1643 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1644 "Already noted what unnamed field was instantiated from");
1645
1646 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1647}
1648
1653
1658
1659unsigned
1661 auto Range = overridden_methods(Method);
1662 return Range.end() - Range.begin();
1663}
1664
1667 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1668 OverriddenMethods.find(Method->getCanonicalDecl());
1669 if (Pos == OverriddenMethods.end())
1670 return overridden_method_range(nullptr, nullptr);
1671 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1672}
1673
1675 const CXXMethodDecl *Overridden) {
1676 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1677 OverriddenMethods[Method].push_back(Overridden);
1678}
1679
1681 const NamedDecl *D,
1682 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1683 assert(D);
1684
1685 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1686 Overridden.append(overridden_methods_begin(CXXMethod),
1687 overridden_methods_end(CXXMethod));
1688 return;
1689 }
1690
1691 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1692 if (!Method)
1693 return;
1694
1696 Method->getOverriddenMethods(OverDecls);
1697 Overridden.append(OverDecls.begin(), OverDecls.end());
1698}
1699
1700std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1702 assert(RD);
1703 CXXRecordDecl *D = RD->getDefinition();
1704 auto it = RelocatableClasses.find(D);
1705 if (it != RelocatableClasses.end())
1706 return it->getSecond();
1707 return std::nullopt;
1708}
1709
1712 assert(RD);
1713 CXXRecordDecl *D = RD->getDefinition();
1714 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1715 RelocatableClasses.insert({D, Info});
1716}
1717
1719 const ASTContext &Context, const CXXRecordDecl *Class) {
1720 if (!Class->isPolymorphic())
1721 return false;
1722 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1723 using AuthAttr = VTablePointerAuthenticationAttr;
1724 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1725 if (!ExplicitAuth)
1726 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1727 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1728 ExplicitAuth->getAddressDiscrimination();
1729 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1730 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1731 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1732}
1733
1734ASTContext::PointerAuthContent
1735ASTContext::findPointerAuthContent(QualType T) const {
1736 assert(isPointerAuthenticationAvailable());
1737
1738 T = T.getCanonicalType();
1739 if (T->isDependentType())
1740 return PointerAuthContent::None;
1741
1742 if (T.hasAddressDiscriminatedPointerAuth())
1743 return PointerAuthContent::AddressDiscriminatedData;
1744 const RecordDecl *RD = T->getAsRecordDecl();
1745 if (!RD)
1746 return PointerAuthContent::None;
1747
1748 if (RD->isInvalidDecl())
1749 return PointerAuthContent::None;
1750
1751 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1752 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1753 return Existing->second;
1754
1755 PointerAuthContent Result = PointerAuthContent::None;
1756
1757 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1758 auto [ResultIter, DidAdd] =
1759 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1760 (void)ResultIter;
1761 (void)DidAdd;
1762 assert(DidAdd);
1763 return Result;
1764 };
1765 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1766 static_assert(PointerAuthContent::None <
1767 PointerAuthContent::AddressDiscriminatedVTable);
1768 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1769 PointerAuthContent::AddressDiscriminatedData);
1770 if (NewResult > Result)
1771 Result = NewResult;
1772 return Result != PointerAuthContent::AddressDiscriminatedData;
1773 };
1774 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1776 !ShouldContinueAfterUpdate(
1777 PointerAuthContent::AddressDiscriminatedVTable))
1778 return SaveResultAndReturn();
1779 for (auto Base : CXXRD->bases()) {
1780 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1781 return SaveResultAndReturn();
1782 }
1783 }
1784 for (auto *FieldDecl : RD->fields()) {
1785 if (!ShouldContinueAfterUpdate(
1786 findPointerAuthContent(FieldDecl->getType())))
1787 return SaveResultAndReturn();
1788 }
1789 return SaveResultAndReturn();
1790}
1791
1793 assert(!Import->getNextLocalImport() &&
1794 "Import declaration already in the chain");
1795 assert(!Import->isFromASTFile() && "Non-local import declaration");
1796 if (!FirstLocalImport) {
1797 FirstLocalImport = Import;
1798 LastLocalImport = Import;
1799 return;
1800 }
1801
1802 LastLocalImport->setNextLocalImport(Import);
1803 LastLocalImport = Import;
1804}
1805
1806//===----------------------------------------------------------------------===//
1807// Type Sizing and Analysis
1808//===----------------------------------------------------------------------===//
1809
1810/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1811/// scalar floating point type.
1812const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1813 switch (T->castAs<BuiltinType>()->getKind()) {
1814 default:
1815 llvm_unreachable("Not a floating point type!");
1816 case BuiltinType::BFloat16:
1817 return Target->getBFloat16Format();
1818 case BuiltinType::Float16:
1819 return Target->getHalfFormat();
1820 case BuiltinType::Half:
1821 return Target->getHalfFormat();
1822 case BuiltinType::Float: return Target->getFloatFormat();
1823 case BuiltinType::Double: return Target->getDoubleFormat();
1824 case BuiltinType::Ibm128:
1825 return Target->getIbm128Format();
1826 case BuiltinType::LongDouble:
1827 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1828 return AuxTarget->getLongDoubleFormat();
1829 return Target->getLongDoubleFormat();
1830 case BuiltinType::Float128:
1831 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1832 return AuxTarget->getFloat128Format();
1833 return Target->getFloat128Format();
1834 }
1835}
1836
1837CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1838 unsigned Align = Target->getCharWidth();
1839
1840 const unsigned AlignFromAttr = D->getMaxAlignment();
1841 if (AlignFromAttr)
1842 Align = AlignFromAttr;
1843
1844 // __attribute__((aligned)) can increase or decrease alignment
1845 // *except* on a struct or struct member, where it only increases
1846 // alignment unless 'packed' is also specified.
1847 //
1848 // It is an error for alignas to decrease alignment, so we can
1849 // ignore that possibility; Sema should diagnose it.
1850 bool UseAlignAttrOnly;
1851 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1852 UseAlignAttrOnly =
1853 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1854 else
1855 UseAlignAttrOnly = AlignFromAttr != 0;
1856 // If we're using the align attribute only, just ignore everything
1857 // else about the declaration and its type.
1858 if (UseAlignAttrOnly) {
1859 // do nothing
1860 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1861 QualType T = VD->getType();
1862 if (const auto *RT = T->getAs<ReferenceType>()) {
1863 if (ForAlignof)
1864 T = RT->getPointeeType();
1865 else
1866 T = getPointerType(RT->getPointeeType());
1867 }
1868 QualType BaseT = getBaseElementType(T);
1869 if (T->isFunctionType())
1870 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1871 else if (!BaseT->isIncompleteType()) {
1872 // Adjust alignments of declarations with array type by the
1873 // large-array alignment on the target.
1874 if (const ArrayType *arrayType = getAsArrayType(T)) {
1875 unsigned MinWidth = Target->getLargeArrayMinWidth();
1876 if (!ForAlignof && MinWidth) {
1878 Align = std::max(Align, Target->getLargeArrayAlign());
1881 Align = std::max(Align, Target->getLargeArrayAlign());
1882 }
1883 }
1884 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1885 if (BaseT.getQualifiers().hasUnaligned())
1886 Align = Target->getCharWidth();
1887 }
1888
1889 // Ensure minimum alignment for global variables.
1890 if (const auto *VD = dyn_cast<VarDecl>(D))
1891 if (VD->hasGlobalStorage() && !ForAlignof) {
1892 uint64_t TypeSize =
1893 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1894 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1895 }
1896
1897 // Fields can be subject to extra alignment constraints, like if
1898 // the field is packed, the struct is packed, or the struct has a
1899 // a max-field-alignment constraint (#pragma pack). So calculate
1900 // the actual alignment of the field within the struct, and then
1901 // (as we're expected to) constrain that by the alignment of the type.
1902 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1903 const RecordDecl *Parent = Field->getParent();
1904 // We can only produce a sensible answer if the record is valid.
1905 if (!Parent->isInvalidDecl()) {
1906 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1907
1908 // Start with the record's overall alignment.
1909 unsigned FieldAlign = toBits(Layout.getAlignment());
1910
1911 // Use the GCD of that and the offset within the record.
1912 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1913 if (Offset > 0) {
1914 // Alignment is always a power of 2, so the GCD will be a power of 2,
1915 // which means we get to do this crazy thing instead of Euclid's.
1916 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1917 if (LowBitOfOffset < FieldAlign)
1918 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1919 }
1920
1921 Align = std::min(Align, FieldAlign);
1922 }
1923 }
1924 }
1925
1926 // Some targets have hard limitation on the maximum requestable alignment in
1927 // aligned attribute for static variables.
1928 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1929 const auto *VD = dyn_cast<VarDecl>(D);
1930 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1931 Align = std::min(Align, MaxAlignedAttr);
1932
1933 return toCharUnitsFromBits(Align);
1934}
1935
1937 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1938}
1939
1940// getTypeInfoDataSizeInChars - Return the size of a type, in
1941// chars. If the type is a record, its data size is returned. This is
1942// the size of the memcpy that's performed when assigning this type
1943// using a trivial copy/move assignment operator.
1946
1947 // In C++, objects can sometimes be allocated into the tail padding
1948 // of a base-class subobject. We decide whether that's possible
1949 // during class layout, so here we can just trust the layout results.
1950 if (getLangOpts().CPlusPlus) {
1951 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1952 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1953 Info.Width = layout.getDataSize();
1954 }
1955 }
1956
1957 return Info;
1958}
1959
1960/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1961/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1964 const ConstantArrayType *CAT) {
1965 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1966 uint64_t Size = CAT->getZExtSize();
1967 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1968 (uint64_t)(-1)/Size) &&
1969 "Overflow in array type char size evaluation");
1970 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1971 unsigned Align = EltInfo.Align.getQuantity();
1972 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1973 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1974 Width = llvm::alignTo(Width, Align);
1977 EltInfo.AlignRequirement);
1978}
1979
1981 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1982 return getConstantArrayInfoInChars(*this, CAT);
1983 TypeInfo Info = getTypeInfo(T);
1986}
1987
1991
1993 // HLSL doesn't promote all small integer types to int, it
1994 // just uses the rank-based promotion rules for all types.
1995 if (getLangOpts().HLSL)
1996 return false;
1997
1998 if (const auto *BT = T->getAs<BuiltinType>())
1999 switch (BT->getKind()) {
2000 case BuiltinType::Bool:
2001 case BuiltinType::Char_S:
2002 case BuiltinType::Char_U:
2003 case BuiltinType::SChar:
2004 case BuiltinType::UChar:
2005 case BuiltinType::Short:
2006 case BuiltinType::UShort:
2007 case BuiltinType::WChar_S:
2008 case BuiltinType::WChar_U:
2009 case BuiltinType::Char8:
2010 case BuiltinType::Char16:
2011 case BuiltinType::Char32:
2012 return true;
2013 default:
2014 return false;
2015 }
2016
2017 // Enumerated types are promotable to their compatible integer types
2018 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2019 if (const auto *ED = T->getAsEnumDecl()) {
2020 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2021 ED->isScoped())
2022 return false;
2023
2024 return true;
2025 }
2026
2027 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2028 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2029 return isPromotableIntegerType(OBT->getUnderlyingType());
2030 }
2031
2032 return false;
2033}
2034
2036 return getTypeInfo(T).isAlignRequired();
2037}
2038
2040 return isAlignmentRequired(T.getTypePtr());
2041}
2042
2044 bool NeedsPreferredAlignment) const {
2045 // An alignment on a typedef overrides anything else.
2046 if (const auto *TT = T->getAs<TypedefType>())
2047 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2048 return Align;
2049
2050 // If we have an (array of) complete type, we're done.
2052 if (!T->isIncompleteType())
2053 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2054
2055 // If we had an array type, its element type might be a typedef
2056 // type with an alignment attribute.
2057 if (const auto *TT = T->getAs<TypedefType>())
2058 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2059 return Align;
2060
2061 // Otherwise, see if the declaration of the type had an attribute.
2062 if (const auto *TD = T->getAsTagDecl())
2063 return TD->getMaxAlignment();
2064
2065 return 0;
2066}
2067
2069 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2070 if (I != MemoizedTypeInfo.end())
2071 return I->second;
2072
2073 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2074 TypeInfo TI = getTypeInfoImpl(T);
2075 MemoizedTypeInfo[T] = TI;
2076 return TI;
2077}
2078
2079/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2080/// method does not work on incomplete types.
2081///
2082/// FIXME: Pointers into different addr spaces could have different sizes and
2083/// alignment requirements: getPointerInfo should take an AddrSpace, this
2084/// should take a QualType, &c.
2085TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2086 uint64_t Width = 0;
2087 unsigned Align = 8;
2090 switch (T->getTypeClass()) {
2091#define TYPE(Class, Base)
2092#define ABSTRACT_TYPE(Class, Base)
2093#define NON_CANONICAL_TYPE(Class, Base)
2094#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2095#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2096 case Type::Class: \
2097 assert(!T->isDependentType() && "should not see dependent types here"); \
2098 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2099#include "clang/AST/TypeNodes.inc"
2100 llvm_unreachable("Should not see dependent types");
2101
2102 case Type::FunctionNoProto:
2103 case Type::FunctionProto:
2104 // GCC extension: alignof(function) = 32 bits
2105 Width = 0;
2106 Align = 32;
2107 break;
2108
2109 case Type::IncompleteArray:
2110 case Type::VariableArray:
2111 case Type::ConstantArray:
2112 case Type::ArrayParameter: {
2113 // Model non-constant sized arrays as size zero, but track the alignment.
2114 uint64_t Size = 0;
2115 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2116 Size = CAT->getZExtSize();
2117
2118 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2119 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2120 "Overflow in array type bit size evaluation");
2121 Width = EltInfo.Width * Size;
2122 Align = EltInfo.Align;
2123 AlignRequirement = EltInfo.AlignRequirement;
2124 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2125 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2126 Width = llvm::alignTo(Width, Align);
2127 break;
2128 }
2129
2130 case Type::ExtVector:
2131 case Type::Vector: {
2132 const auto *VT = cast<VectorType>(T);
2133 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2134 Width = VT->isPackedVectorBoolType(*this)
2135 ? VT->getNumElements()
2136 : EltInfo.Width * VT->getNumElements();
2137 // Enforce at least byte size and alignment.
2138 Width = std::max<unsigned>(8, Width);
2139 Align = std::max<unsigned>(
2140 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2141
2142 // If the alignment is not a power of 2, round up to the next power of 2.
2143 // This happens for non-power-of-2 length vectors.
2144 if (Align & (Align-1)) {
2145 Align = llvm::bit_ceil(Align);
2146 Width = llvm::alignTo(Width, Align);
2147 }
2148 // Adjust the alignment based on the target max.
2149 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2150 if (TargetVectorAlign && TargetVectorAlign < Align)
2151 Align = TargetVectorAlign;
2152 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2153 // Adjust the alignment for fixed-length SVE vectors. This is important
2154 // for non-power-of-2 vector lengths.
2155 Align = 128;
2156 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2157 // Adjust the alignment for fixed-length SVE predicates.
2158 Align = 16;
2159 else if (isRVVFixedLengthVectorKind(VT->getVectorKind()))
2160 // Adjust the alignment for fixed-length RVV vectors.
2161 Align = std::min<unsigned>(64, Width);
2162 // Vector types have their natural alignment resist reduction by
2163 // #pragma pack in MSVC record layout.
2164 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2165 break;
2166 }
2167
2168 case Type::ConstantMatrix: {
2169 const auto *MT = cast<ConstantMatrixType>(T);
2170 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2171 // The internal layout of a matrix value is implementation defined.
2172 // Initially be ABI compatible with arrays with respect to alignment and
2173 // size.
2174 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2175 Align = ElementInfo.Align;
2176 break;
2177 }
2178
2179 case Type::Builtin:
2180 switch (cast<BuiltinType>(T)->getKind()) {
2181 default: llvm_unreachable("Unknown builtin type!");
2182 case BuiltinType::Void:
2183 // GCC extension: alignof(void) = 8 bits.
2184 Width = 0;
2185 Align = 8;
2186 break;
2187 case BuiltinType::Bool:
2188 Width = Target->getBoolWidth();
2189 Align = Target->getBoolAlign();
2190 break;
2191 case BuiltinType::Char_S:
2192 case BuiltinType::Char_U:
2193 case BuiltinType::UChar:
2194 case BuiltinType::SChar:
2195 case BuiltinType::Char8:
2196 Width = Target->getCharWidth();
2197 Align = Target->getCharAlign();
2198 break;
2199 case BuiltinType::WChar_S:
2200 case BuiltinType::WChar_U:
2201 Width = Target->getWCharWidth();
2202 Align = Target->getWCharAlign();
2203 break;
2204 case BuiltinType::Char16:
2205 Width = Target->getChar16Width();
2206 Align = Target->getChar16Align();
2207 break;
2208 case BuiltinType::Char32:
2209 Width = Target->getChar32Width();
2210 Align = Target->getChar32Align();
2211 break;
2212 case BuiltinType::UShort:
2213 case BuiltinType::Short:
2214 Width = Target->getShortWidth();
2215 Align = Target->getShortAlign();
2216 break;
2217 case BuiltinType::UInt:
2218 case BuiltinType::Int:
2219 Width = Target->getIntWidth();
2220 Align = Target->getIntAlign();
2221 break;
2222 case BuiltinType::ULong:
2223 case BuiltinType::Long:
2224 Width = Target->getLongWidth();
2225 Align = Target->getLongAlign();
2226 break;
2227 case BuiltinType::ULongLong:
2228 case BuiltinType::LongLong:
2229 Width = Target->getLongLongWidth();
2230 Align = Target->getLongLongAlign();
2231 break;
2232 case BuiltinType::Int128:
2233 case BuiltinType::UInt128:
2234 Width = 128;
2235 Align = Target->getInt128Align();
2236 break;
2237 case BuiltinType::ShortAccum:
2238 case BuiltinType::UShortAccum:
2239 case BuiltinType::SatShortAccum:
2240 case BuiltinType::SatUShortAccum:
2241 Width = Target->getShortAccumWidth();
2242 Align = Target->getShortAccumAlign();
2243 break;
2244 case BuiltinType::Accum:
2245 case BuiltinType::UAccum:
2246 case BuiltinType::SatAccum:
2247 case BuiltinType::SatUAccum:
2248 Width = Target->getAccumWidth();
2249 Align = Target->getAccumAlign();
2250 break;
2251 case BuiltinType::LongAccum:
2252 case BuiltinType::ULongAccum:
2253 case BuiltinType::SatLongAccum:
2254 case BuiltinType::SatULongAccum:
2255 Width = Target->getLongAccumWidth();
2256 Align = Target->getLongAccumAlign();
2257 break;
2258 case BuiltinType::ShortFract:
2259 case BuiltinType::UShortFract:
2260 case BuiltinType::SatShortFract:
2261 case BuiltinType::SatUShortFract:
2262 Width = Target->getShortFractWidth();
2263 Align = Target->getShortFractAlign();
2264 break;
2265 case BuiltinType::Fract:
2266 case BuiltinType::UFract:
2267 case BuiltinType::SatFract:
2268 case BuiltinType::SatUFract:
2269 Width = Target->getFractWidth();
2270 Align = Target->getFractAlign();
2271 break;
2272 case BuiltinType::LongFract:
2273 case BuiltinType::ULongFract:
2274 case BuiltinType::SatLongFract:
2275 case BuiltinType::SatULongFract:
2276 Width = Target->getLongFractWidth();
2277 Align = Target->getLongFractAlign();
2278 break;
2279 case BuiltinType::BFloat16:
2280 if (Target->hasBFloat16Type()) {
2281 Width = Target->getBFloat16Width();
2282 Align = Target->getBFloat16Align();
2283 } else if ((getLangOpts().SYCLIsDevice ||
2284 (getLangOpts().OpenMP &&
2285 getLangOpts().OpenMPIsTargetDevice)) &&
2286 AuxTarget->hasBFloat16Type()) {
2287 Width = AuxTarget->getBFloat16Width();
2288 Align = AuxTarget->getBFloat16Align();
2289 }
2290 break;
2291 case BuiltinType::Float16:
2292 case BuiltinType::Half:
2293 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2294 !getLangOpts().OpenMPIsTargetDevice) {
2295 Width = Target->getHalfWidth();
2296 Align = Target->getHalfAlign();
2297 } else {
2298 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2299 "Expected OpenMP device compilation.");
2300 Width = AuxTarget->getHalfWidth();
2301 Align = AuxTarget->getHalfAlign();
2302 }
2303 break;
2304 case BuiltinType::Float:
2305 Width = Target->getFloatWidth();
2306 Align = Target->getFloatAlign();
2307 break;
2308 case BuiltinType::Double:
2309 Width = Target->getDoubleWidth();
2310 Align = Target->getDoubleAlign();
2311 break;
2312 case BuiltinType::Ibm128:
2313 Width = Target->getIbm128Width();
2314 Align = Target->getIbm128Align();
2315 break;
2316 case BuiltinType::LongDouble:
2317 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2318 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2319 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2320 Width = AuxTarget->getLongDoubleWidth();
2321 Align = AuxTarget->getLongDoubleAlign();
2322 } else {
2323 Width = Target->getLongDoubleWidth();
2324 Align = Target->getLongDoubleAlign();
2325 }
2326 // x87 extended precision (fp80) has its natural alignment resist
2327 // reduction by #pragma pack in MSVC record layout.
2328 if (&Target->getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
2329 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2330 break;
2331 case BuiltinType::Float128:
2332 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2333 !getLangOpts().OpenMPIsTargetDevice) {
2334 Width = Target->getFloat128Width();
2335 Align = Target->getFloat128Align();
2336 } else {
2337 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2338 "Expected OpenMP device compilation.");
2339 Width = AuxTarget->getFloat128Width();
2340 Align = AuxTarget->getFloat128Align();
2341 }
2342 break;
2343 case BuiltinType::NullPtr:
2344 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2345 Width = Target->getPointerWidth(LangAS::Default);
2346 Align = Target->getPointerAlign(LangAS::Default);
2347 break;
2348 case BuiltinType::MetaInfo:
2349 // sizeof(std::meta::info) == sizeof(void*)
2350 Width = Target->getPointerWidth(LangAS::Default);
2351 // alignof(std::meta::info) == alignof(void*)
2352 Align = Target->getPointerAlign(LangAS::Default);
2353 break;
2354 case BuiltinType::ObjCId:
2355 case BuiltinType::ObjCClass:
2356 case BuiltinType::ObjCSel:
2357 Width = Target->getPointerWidth(LangAS::Default);
2358 Align = Target->getPointerAlign(LangAS::Default);
2359 break;
2360 case BuiltinType::OCLSampler:
2361 case BuiltinType::OCLEvent:
2362 case BuiltinType::OCLClkEvent:
2363 case BuiltinType::OCLQueue:
2364 case BuiltinType::OCLReserveID:
2365#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2366 case BuiltinType::Id:
2367#include "clang/Basic/OpenCLImageTypes.def"
2368#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2369 case BuiltinType::Id:
2370#include "clang/Basic/OpenCLExtensionTypes.def"
2371 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2372 Width = Target->getPointerWidth(AS);
2373 Align = Target->getPointerAlign(AS);
2374 break;
2375 // The SVE types are effectively target-specific. The length of an
2376 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2377 // of 128 bits. There is one predicate bit for each vector byte, so the
2378 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2379 //
2380 // Because the length is only known at runtime, we use a dummy value
2381 // of 0 for the static length. The alignment values are those defined
2382 // by the Procedure Call Standard for the Arm Architecture.
2383#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2384 case BuiltinType::Id: \
2385 Width = 0; \
2386 Align = 128; \
2387 break;
2388#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2389 case BuiltinType::Id: \
2390 Width = 0; \
2391 Align = 16; \
2392 break;
2393#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2394 case BuiltinType::Id: \
2395 Width = 0; \
2396 Align = 16; \
2397 break;
2398#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2399 case BuiltinType::Id: \
2400 Width = Bits; \
2401 Align = Bits; \
2402 break;
2403#include "clang/Basic/AArch64ACLETypes.def"
2404#define PPC_VECTOR_TYPE(Name, Id, Size) \
2405 case BuiltinType::Id: \
2406 Width = Size; \
2407 Align = Size; \
2408 break;
2409#include "clang/Basic/PPCTypes.def"
2410#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2411 IsFP, IsBF) \
2412 case BuiltinType::Id: \
2413 Width = 0; \
2414 Align = ElBits; \
2415 break;
2416#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2417 case BuiltinType::Id: \
2418 Width = 0; \
2419 Align = 8; \
2420 break;
2421#include "clang/Basic/RISCVVTypes.def"
2422#define WASM_TYPE(Name, Id, SingletonId) \
2423 case BuiltinType::Id: \
2424 Width = 0; \
2425 Align = 8; \
2426 break;
2427#include "clang/Basic/WebAssemblyReferenceTypes.def"
2428#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2429 case BuiltinType::ID: \
2430 Width = WIDTH; \
2431 Align = ALIGN; \
2432 break;
2433#include "clang/Basic/AMDGPUTypes.def"
2434#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2435#include "clang/Basic/HLSLIntangibleTypes.def"
2436 Width = Target->getPointerWidth(LangAS::Default);
2437 Align = Target->getPointerAlign(LangAS::Default);
2438 break;
2439#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2440#include "clang/Basic/HLSLPackedTypes.def"
2441 Width = 32;
2442 Align = 32;
2443 break;
2444#define SPIRV_TYPE(Name, Id, SingletonId) \
2445 case BuiltinType::Id: \
2446 Width = Target->getPointerWidth(LangAS::Default); \
2447 Align = Target->getPointerAlign(LangAS::Default); \
2448 break;
2449#include "clang/Basic/SPIRVTypes.def"
2450 }
2451 break;
2452 case Type::ObjCObjectPointer:
2453 Width = Target->getPointerWidth(LangAS::Default);
2454 Align = Target->getPointerAlign(LangAS::Default);
2455 break;
2456 case Type::BlockPointer:
2457 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2458 Width = Target->getPointerWidth(AS);
2459 Align = Target->getPointerAlign(AS);
2460 break;
2461 case Type::LValueReference:
2462 case Type::RValueReference:
2463 // alignof and sizeof should never enter this code path here, so we go
2464 // the pointer route.
2465 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2466 Width = Target->getPointerWidth(AS);
2467 Align = Target->getPointerAlign(AS);
2468 break;
2469 case Type::Pointer:
2470 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2471 Width = Target->getPointerWidth(AS);
2472 Align = Target->getPointerAlign(AS);
2473 break;
2474 case Type::MemberPointer: {
2475 const auto *MPT = cast<MemberPointerType>(T);
2476 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2477 Width = MPI.Width;
2478 Align = MPI.Align;
2479 break;
2480 }
2481 case Type::Complex: {
2482 // Complex types have the same alignment as their elements, but twice the
2483 // size.
2484 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2485 Width = EltInfo.Width * 2;
2486 Align = EltInfo.Align;
2487 break;
2488 }
2489 case Type::ObjCObject:
2490 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2491 case Type::Adjusted:
2492 case Type::Decayed:
2493 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2494 case Type::ObjCInterface: {
2495 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2496 if (ObjCI->getDecl()->isInvalidDecl()) {
2497 Width = 8;
2498 Align = 8;
2499 break;
2500 }
2501 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2502 Width = toBits(Layout.getSize());
2503 Align = toBits(Layout.getAlignment());
2504 break;
2505 }
2506 case Type::BitInt: {
2507 const auto *EIT = cast<BitIntType>(T);
2508 Align = Target->getBitIntAlign(EIT->getNumBits());
2509 Width = Target->getBitIntWidth(EIT->getNumBits());
2510 break;
2511 }
2512 case Type::Record:
2513 case Type::Enum: {
2514 const auto *TT = cast<TagType>(T);
2515 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2516
2517 if (TD->isInvalidDecl()) {
2518 Width = 8;
2519 Align = 8;
2520 break;
2521 }
2522
2523 if (isa<EnumType>(TT)) {
2524 const EnumDecl *ED = cast<EnumDecl>(TD);
2525 TypeInfo Info =
2527 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2528 Info.Align = AttrAlign;
2530 }
2531 return Info;
2532 }
2533
2534 const auto *RD = cast<RecordDecl>(TD);
2535 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2536 Width = toBits(Layout.getSize());
2537 Align = toBits(Layout.getAlignment());
2538 AlignRequirement = RD->hasAttr<AlignedAttr>()
2540 : AlignRequirementKind::None;
2541 break;
2542 }
2543
2544 case Type::SubstTemplateTypeParm:
2546 getReplacementType().getTypePtr());
2547
2548 case Type::Auto:
2549 case Type::DeducedTemplateSpecialization: {
2550 const auto *A = cast<DeducedType>(T);
2551 assert(!A->getDeducedType().isNull() &&
2552 "cannot request the size of an undeduced or dependent auto type");
2553 return getTypeInfo(A->getDeducedType().getTypePtr());
2554 }
2555
2556 case Type::Paren:
2557 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2558
2559 case Type::MacroQualified:
2560 return getTypeInfo(
2562
2563 case Type::ObjCTypeParam:
2564 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2565
2566 case Type::Using:
2567 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2568
2569 case Type::Typedef: {
2570 const auto *TT = cast<TypedefType>(T);
2571 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2572 // If the typedef has an aligned attribute on it, it overrides any computed
2573 // alignment we have. This violates the GCC documentation (which says that
2574 // attribute(aligned) can only round up) but matches its implementation.
2575 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2576 Align = AttrAlign;
2577 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2578 } else {
2579 Align = Info.Align;
2580 AlignRequirement = Info.AlignRequirement;
2581 }
2582 Width = Info.Width;
2583 break;
2584 }
2585
2586 case Type::Attributed:
2587 return getTypeInfo(
2588 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2589
2590 case Type::CountAttributed:
2591 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2592
2593 case Type::LateParsedAttr:
2594 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2595
2596 case Type::BTFTagAttributed:
2597 return getTypeInfo(
2598 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2599
2600 case Type::OverflowBehavior:
2601 return getTypeInfo(
2603
2604 case Type::HLSLAttributedResource:
2605 return getTypeInfo(
2606 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2607
2608 case Type::HLSLInlineSpirv: {
2609 const auto *ST = cast<HLSLInlineSpirvType>(T);
2610 // Size is specified in bytes, convert to bits
2611 Width = ST->getSize() * 8;
2612 Align = ST->getAlignment();
2613 if (Width == 0 && Align == 0) {
2614 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2615 Width = 32;
2616 Align = 32;
2617 }
2618 break;
2619 }
2620
2621 case Type::Atomic: {
2622 // Start with the base type information.
2623 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2624 Width = Info.Width;
2625 Align = Info.Align;
2626
2627 if (!Width) {
2628 // An otherwise zero-sized type should still generate an
2629 // atomic operation.
2630 Width = Target->getCharWidth();
2631 assert(Align);
2632 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2633 // If the size of the type doesn't exceed the platform's max
2634 // atomic promotion width, make the size and alignment more
2635 // favorable to atomic operations:
2636
2637 // Round the size up to a power of 2.
2638 Width = llvm::bit_ceil(Width);
2639
2640 // Set the alignment equal to the size.
2641 Align = static_cast<unsigned>(Width);
2642 }
2643 }
2644 break;
2645
2646 case Type::PredefinedSugar:
2647 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2648
2649 case Type::Pipe:
2650 Width = Target->getPointerWidth(LangAS::opencl_global);
2651 Align = Target->getPointerAlign(LangAS::opencl_global);
2652 break;
2653 }
2654
2655 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2656 return TypeInfo(Width, Align, AlignRequirement);
2657}
2658
2660 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2661 if (I != MemoizedUnadjustedAlign.end())
2662 return I->second;
2663
2664 unsigned UnadjustedAlign;
2665 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2666 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2667 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2668 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2669 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2670 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2671 } else {
2672 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2673 }
2674
2675 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2676 return UnadjustedAlign;
2677}
2678
2680 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2681 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2682 return SimdAlign;
2683}
2684
2685/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2687 return CharUnits::fromQuantity(BitSize / getCharWidth());
2688}
2689
2690/// toBits - Convert a size in characters to a size in characters.
2691int64_t ASTContext::toBits(CharUnits CharSize) const {
2692 return CharSize.getQuantity() * getCharWidth();
2693}
2694
2695/// getTypeSizeInChars - Return the size of the specified type, in characters.
2696/// This method does not work on incomplete types.
2703
2704/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2705/// characters. This method does not work on incomplete types.
2712
2713/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2714/// type, in characters, before alignment adjustments. This method does
2715/// not work on incomplete types.
2722
2723/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2724/// type for the current target in bits. This can be different than the ABI
2725/// alignment in cases where it is beneficial for performance or backwards
2726/// compatibility preserving to overalign a data type. (Note: despite the name,
2727/// the preferred alignment is ABI-impacting, and not an optimization.)
2729 TypeInfo TI = getTypeInfo(T);
2730 unsigned ABIAlign = TI.Align;
2731
2732 T = T->getBaseElementTypeUnsafe();
2733
2734 // The preferred alignment of member pointers is that of a pointer.
2735 if (T->isMemberPointerType())
2736 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2737
2738 if (!Target->allowsLargerPreferedTypeAlignment())
2739 return ABIAlign;
2740
2741 if (const auto *RD = T->getAsRecordDecl()) {
2742 // When used as part of a typedef, or together with a 'packed' attribute,
2743 // the 'aligned' attribute can be used to decrease alignment. Note that the
2744 // 'packed' case is already taken into consideration when computing the
2745 // alignment, we only need to handle the typedef case here.
2747 RD->isInvalidDecl())
2748 return ABIAlign;
2749
2750 unsigned PreferredAlign = static_cast<unsigned>(
2751 toBits(getASTRecordLayout(RD).PreferredAlignment));
2752 assert(PreferredAlign >= ABIAlign &&
2753 "PreferredAlign should be at least as large as ABIAlign.");
2754 return PreferredAlign;
2755 }
2756
2757 // Double (and, for targets supporting AIX `power` alignment, long double) and
2758 // long long should be naturally aligned (despite requiring less alignment) if
2759 // possible.
2760 if (const auto *CT = T->getAs<ComplexType>())
2761 T = CT->getElementType().getTypePtr();
2762 if (const auto *ED = T->getAsEnumDecl())
2763 T = ED->getIntegerType().getTypePtr();
2764 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2765 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2766 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2767 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2768 Target->defaultsToAIXPowerAlignment()))
2769 // Don't increase the alignment if an alignment attribute was specified on a
2770 // typedef declaration.
2771 if (!TI.isAlignRequired())
2772 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2773
2774 return ABIAlign;
2775}
2776
2777/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2778/// for __attribute__((aligned)) on this target, to be used if no alignment
2779/// value is specified.
2783
2784/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2785/// to a global variable of the specified type.
2787 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2788 return std::max(getPreferredTypeAlign(T),
2789 getMinGlobalAlignOfVar(TypeSize, VD));
2790}
2791
2792/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2793/// should be given to a global variable of the specified type.
2798
2800 const VarDecl *VD) const {
2801 // Make the default handling as that of a non-weak definition in the
2802 // current translation unit.
2803 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2804 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2805}
2806
2808 CharUnits Offset = CharUnits::Zero();
2809 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2810 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2811 Offset += Layout->getBaseClassOffset(Base);
2812 Layout = &getASTRecordLayout(Base);
2813 }
2814 return Offset;
2815}
2816
2818 const ValueDecl *MPD = MP.getMemberPointerDecl();
2821 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2823 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2824 const CXXRecordDecl *Base = RD;
2825 const CXXRecordDecl *Derived = Path[I];
2826 if (DerivedMember)
2827 std::swap(Base, Derived);
2829 RD = Path[I];
2830 }
2831 if (DerivedMember)
2833 return ThisAdjustment;
2834}
2835
2836/// DeepCollectObjCIvars -
2837/// This routine first collects all declared, but not synthesized, ivars in
2838/// super class and then collects all ivars, including those synthesized for
2839/// current class. This routine is used for implementation of current class
2840/// when all ivars, declared and synthesized are known.
2842 bool leafClass,
2844 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2845 DeepCollectObjCIvars(SuperClass, false, Ivars);
2846 if (!leafClass) {
2847 llvm::append_range(Ivars, OI->ivars());
2848 } else {
2849 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2850 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2851 Iv= Iv->getNextIvar())
2852 Ivars.push_back(Iv);
2853 }
2854}
2855
2856/// CollectInheritedProtocols - Collect all protocols in current class and
2857/// those inherited by it.
2860 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2861 // We can use protocol_iterator here instead of
2862 // all_referenced_protocol_iterator since we are walking all categories.
2863 for (auto *Proto : OI->all_referenced_protocols()) {
2864 CollectInheritedProtocols(Proto, Protocols);
2865 }
2866
2867 // Categories of this Interface.
2868 for (const auto *Cat : OI->visible_categories())
2869 CollectInheritedProtocols(Cat, Protocols);
2870
2871 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2872 while (SD) {
2873 CollectInheritedProtocols(SD, Protocols);
2874 SD = SD->getSuperClass();
2875 }
2876 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2877 for (auto *Proto : OC->protocols()) {
2878 CollectInheritedProtocols(Proto, Protocols);
2879 }
2880 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2881 // Insert the protocol.
2882 if (!Protocols.insert(
2883 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2884 return;
2885
2886 for (auto *Proto : OP->protocols())
2887 CollectInheritedProtocols(Proto, Protocols);
2888 }
2889}
2890
2892 const RecordDecl *RD,
2893 bool CheckIfTriviallyCopyable) {
2894 assert(RD->isUnion() && "Must be union type");
2895 CharUnits UnionSize =
2896 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2897
2898 for (const auto *Field : RD->fields()) {
2899 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2900 CheckIfTriviallyCopyable))
2901 return false;
2902 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2903 if (FieldSize != UnionSize)
2904 return false;
2905 }
2906 return !RD->field_empty();
2907}
2908
2910 const ASTContext &Context,
2911 const clang::ASTRecordLayout & /*Layout*/) {
2912 return Context.getFieldOffset(Field);
2913}
2914
2916 const ASTContext &Context,
2917 const clang::ASTRecordLayout &Layout) {
2918 return Context.toBits(Layout.getBaseClassOffset(RD));
2919}
2920
2921static std::optional<int64_t>
2923 const RecordDecl *RD,
2924 bool CheckIfTriviallyCopyable);
2925
2926static std::optional<int64_t>
2927getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2928 bool CheckIfTriviallyCopyable) {
2929 if (const auto *RD = Field->getType()->getAsRecordDecl();
2930 RD && !RD->isUnion())
2931 return structHasUniqueObjectRepresentations(Context, RD,
2932 CheckIfTriviallyCopyable);
2933
2934 // A _BitInt type may not be unique if it has padding bits
2935 // but if it is a bitfield the padding bits are not used.
2936 bool IsBitIntType = Field->getType()->isBitIntType();
2937 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2938 !Context.hasUniqueObjectRepresentations(Field->getType(),
2939 CheckIfTriviallyCopyable))
2940 return std::nullopt;
2941
2942 int64_t FieldSizeInBits =
2943 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2944 if (Field->isBitField()) {
2945 // If we have explicit padding bits, they don't contribute bits
2946 // to the actual object representation, so return 0.
2947 if (Field->isUnnamedBitField())
2948 return 0;
2949
2950 int64_t BitfieldSize = Field->getBitWidthValue();
2951 if (IsBitIntType) {
2952 if ((unsigned)BitfieldSize >
2953 cast<BitIntType>(Field->getType())->getNumBits())
2954 return std::nullopt;
2955 } else if (BitfieldSize > FieldSizeInBits) {
2956 return std::nullopt;
2957 }
2958 FieldSizeInBits = BitfieldSize;
2959 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2960 Field->getType(), CheckIfTriviallyCopyable)) {
2961 return std::nullopt;
2962 }
2963 return FieldSizeInBits;
2964}
2965
2966static std::optional<int64_t>
2968 bool CheckIfTriviallyCopyable) {
2969 return structHasUniqueObjectRepresentations(Context, RD,
2970 CheckIfTriviallyCopyable);
2971}
2972
2973template <typename RangeT>
2975 const RangeT &Subobjects, int64_t CurOffsetInBits,
2976 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2977 bool CheckIfTriviallyCopyable) {
2978 for (const auto *Subobject : Subobjects) {
2979 std::optional<int64_t> SizeInBits =
2980 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2981 if (!SizeInBits)
2982 return std::nullopt;
2983 if (*SizeInBits != 0) {
2984 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2985 if (Offset != CurOffsetInBits)
2986 return std::nullopt;
2987 CurOffsetInBits += *SizeInBits;
2988 }
2989 }
2990 return CurOffsetInBits;
2991}
2992
2993static std::optional<int64_t>
2995 const RecordDecl *RD,
2996 bool CheckIfTriviallyCopyable) {
2997 assert(!RD->isUnion() && "Must be struct/class type");
2998 const auto &Layout = Context.getASTRecordLayout(RD);
2999
3000 int64_t CurOffsetInBits = 0;
3001 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3002 if (ClassDecl->isDynamicClass())
3003 return std::nullopt;
3004
3006 for (const auto &Base : ClassDecl->bases()) {
3007 // Empty types can be inherited from, and non-empty types can potentially
3008 // have tail padding, so just make sure there isn't an error.
3009 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3010 }
3011
3012 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3013 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3014 });
3015
3016 std::optional<int64_t> OffsetAfterBases =
3018 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3019 if (!OffsetAfterBases)
3020 return std::nullopt;
3021 CurOffsetInBits = *OffsetAfterBases;
3022 }
3023
3024 std::optional<int64_t> OffsetAfterFields =
3026 RD->fields(), CurOffsetInBits, Context, Layout,
3027 CheckIfTriviallyCopyable);
3028 if (!OffsetAfterFields)
3029 return std::nullopt;
3030 CurOffsetInBits = *OffsetAfterFields;
3031
3032 return CurOffsetInBits;
3033}
3034
3036 QualType Ty, bool CheckIfTriviallyCopyable) const {
3037 // C++17 [meta.unary.prop]:
3038 // The predicate condition for a template specialization
3039 // has_unique_object_representations<T> shall be satisfied if and only if:
3040 // (9.1) - T is trivially copyable, and
3041 // (9.2) - any two objects of type T with the same value have the same
3042 // object representation, where:
3043 // - two objects of array or non-union class type are considered to have
3044 // the same value if their respective sequences of direct subobjects
3045 // have the same values, and
3046 // - two objects of union type are considered to have the same value if
3047 // they have the same active member and the corresponding members have
3048 // the same value.
3049 // The set of scalar types for which this condition holds is
3050 // implementation-defined. [ Note: If a type has padding bits, the condition
3051 // does not hold; otherwise, the condition holds true for unsigned integral
3052 // types. -- end note ]
3053 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3054
3055 // Arrays are unique only if their element type is unique.
3056 if (Ty->isArrayType())
3058 CheckIfTriviallyCopyable);
3059
3060 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3061 "hasUniqueObjectRepresentations should not be called with an "
3062 "incomplete type");
3063
3064 // _Atomic(T) shares T's object representation unless its size was rounded
3065 // up to a power of two, in which case the extra bytes are padding. Atomic
3066 // types are never trivially copyable, so (9.1) is judged on the value type.
3067 if (const auto *AT = Ty->getAs<AtomicType>())
3068 return getTypeSize(AT) == getTypeSize(AT->getValueType()) &&
3069 hasUniqueObjectRepresentations(AT->getValueType(),
3070 CheckIfTriviallyCopyable);
3071
3072 // (9.1) - T is trivially copyable...
3073 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3074 return false;
3075
3076 // All integrals and enums are unique.
3077 if (Ty->isIntegralOrEnumerationType()) {
3078 // Address discriminated integer types are not unique.
3080 return false;
3081 // Except _BitInt types that have padding bits.
3082 if (const auto *BIT = Ty->getAs<BitIntType>())
3083 return getTypeSize(BIT) == BIT->getNumBits();
3084
3085 return true;
3086 }
3087
3088 // All other pointers are unique.
3089 if (Ty->isPointerType())
3091
3092 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3093 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3094
3095 if (const auto *Record = Ty->getAsRecordDecl()) {
3096 if (Record->isInvalidDecl())
3097 return false;
3098
3099 if (Record->isUnion())
3101 CheckIfTriviallyCopyable);
3102
3103 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3104 *this, Record, CheckIfTriviallyCopyable);
3105
3106 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3107 }
3108
3109 // FIXME: More cases to handle here (list by rsmith):
3110 // vectors (careful about, eg, vector of 3 foo)
3111 // _Complex int and friends
3112 // Obj-C block pointers
3113 // Obj-C object pointers
3114 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3115 // clk_event_t, queue_t, reserve_id_t)
3116 // There're also Obj-C class types and the Obj-C selector type, but I think it
3117 // makes sense for those to return false here.
3118
3119 return false;
3120}
3121
3123 unsigned count = 0;
3124 // Count ivars declared in class extension.
3125 for (const auto *Ext : OI->known_extensions())
3126 count += Ext->ivar_size();
3127
3128 // Count ivar defined in this class's implementation. This
3129 // includes synthesized ivars.
3130 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3131 count += ImplDecl->ivar_size();
3132
3133 return count;
3134}
3135
3137 if (!E)
3138 return false;
3139
3140 // nullptr_t is always treated as null.
3141 if (E->getType()->isNullPtrType()) return true;
3142
3143 if (E->getType()->isAnyPointerType() &&
3146 return true;
3147
3148 // Unfortunately, __null has type 'int'.
3149 if (isa<GNUNullExpr>(E)) return true;
3150
3151 return false;
3152}
3153
3154/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3155/// exists.
3157 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3158 I = ObjCImpls.find(D);
3159 if (I != ObjCImpls.end())
3160 return cast<ObjCImplementationDecl>(I->second);
3161 return nullptr;
3162}
3163
3164/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3165/// exists.
3167 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3168 I = ObjCImpls.find(D);
3169 if (I != ObjCImpls.end())
3170 return cast<ObjCCategoryImplDecl>(I->second);
3171 return nullptr;
3172}
3173
3174/// Set the implementation of ObjCInterfaceDecl.
3176 ObjCImplementationDecl *ImplD) {
3177 assert(IFaceD && ImplD && "Passed null params");
3178 ObjCImpls[IFaceD] = ImplD;
3179}
3180
3181/// Set the implementation of ObjCCategoryDecl.
3183 ObjCCategoryImplDecl *ImplD) {
3184 assert(CatD && ImplD && "Passed null params");
3185 ObjCImpls[CatD] = ImplD;
3186}
3187
3188const ObjCMethodDecl *
3190 return ObjCMethodRedecls.lookup(MD);
3191}
3192
3194 const ObjCMethodDecl *Redecl) {
3195 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3196 ObjCMethodRedecls[MD] = Redecl;
3197}
3198
3200 const NamedDecl *ND) const {
3201 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3202 return ID;
3203 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3204 return CD->getClassInterface();
3205 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3206 return IMD->getClassInterface();
3207
3208 return nullptr;
3209}
3210
3211/// Get the copy initialization expression of VarDecl, or nullptr if
3212/// none exists.
3214 assert(VD && "Passed null params");
3215 assert(VD->hasAttr<BlocksAttr>() &&
3216 "getBlockVarCopyInits - not __block var");
3217 auto I = BlockVarCopyInits.find(VD);
3218 if (I != BlockVarCopyInits.end())
3219 return I->second;
3220 return {nullptr, false};
3221}
3222
3223/// Set the copy initialization expression of a block var decl.
3225 bool CanThrow) {
3226 assert(VD && CopyExpr && "Passed null params");
3227 assert(VD->hasAttr<BlocksAttr>() &&
3228 "setBlockVarCopyInits - not __block var");
3229 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3230}
3231
3233 unsigned DataSize) const {
3234 if (!DataSize)
3236 else
3237 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3238 "incorrect data size provided to CreateTypeSourceInfo!");
3239
3240 auto *TInfo =
3241 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3242 new (TInfo) TypeSourceInfo(T, DataSize);
3243 return TInfo;
3244}
3245
3247 SourceLocation L) const {
3249 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3250 return TSI;
3251}
3252
3253const ASTRecordLayout &
3255 return getObjCLayout(D);
3256}
3257
3260 bool &AnyNonCanonArgs) {
3261 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3262 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3263 return CanonArgs;
3264}
3265
3268 bool AnyNonCanonArgs = false;
3269 for (auto &Arg : Args) {
3270 TemplateArgument OrigArg = Arg;
3272 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3273 }
3274 return AnyNonCanonArgs;
3275}
3276
3277//===----------------------------------------------------------------------===//
3278// Type creation/memoization methods
3279//===----------------------------------------------------------------------===//
3280
3282ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3283 unsigned fastQuals = quals.getFastQualifiers();
3284 quals.removeFastQualifiers();
3285
3286 // Check if we've already instantiated this type.
3287 llvm::FoldingSetNodeID ID;
3288 ExtQuals::Profile(ID, baseType, quals);
3289 llvm::FoldingSetInsertToken Token;
3290 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3291 assert(eq->getQualifiers() == quals);
3292 return QualType(eq, fastQuals);
3293 }
3294
3295 // If the base type is not canonical, make the appropriate canonical type.
3296 QualType canon;
3297 if (!baseType->isCanonicalUnqualified()) {
3298 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3299 canonSplit.Quals.addConsistentQualifiers(quals);
3300 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3301
3302 // Re-find the insert position.
3303 (void)ExtQualNodes.lookup(ID, Token);
3304 }
3305
3306 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3307 ExtQualNodes.insert(eq, Token);
3308 return QualType(eq, fastQuals);
3309}
3310
3312 LangAS AddressSpace) const {
3313 QualType CanT = getCanonicalType(T);
3314 if (CanT.getAddressSpace() == AddressSpace)
3315 return T;
3316
3317 // If we are composing extended qualifiers together, merge together
3318 // into one ExtQuals node.
3319 QualifierCollector Quals;
3320 const Type *TypeNode = Quals.strip(T);
3321
3322 // If this type already has an address space specified, it cannot get
3323 // another one.
3324 assert(!Quals.hasAddressSpace() &&
3325 "Type cannot be in multiple addr spaces!");
3326 Quals.addAddressSpace(AddressSpace);
3327
3328 return getExtQualType(TypeNode, Quals);
3329}
3330
3332 // If the type is not qualified with an address space, just return it
3333 // immediately.
3334 if (!T.hasAddressSpace())
3335 return T;
3336
3337 QualifierCollector Quals;
3338 const Type *TypeNode;
3339 // For arrays, strip the qualifier off the element type, then reconstruct the
3340 // array type
3341 if (T.getTypePtr()->isArrayType()) {
3342 T = getUnqualifiedArrayType(T, Quals);
3343 TypeNode = T.getTypePtr();
3344 } else {
3345 // If we are composing extended qualifiers together, merge together
3346 // into one ExtQuals node.
3347 while (T.hasAddressSpace()) {
3348 TypeNode = Quals.strip(T);
3349
3350 // If the type no longer has an address space after stripping qualifiers,
3351 // jump out.
3352 if (!QualType(TypeNode, 0).hasAddressSpace())
3353 break;
3354
3355 // There might be sugar in the way. Strip it and try again.
3356 T = T.getSingleStepDesugaredType(*this);
3357 }
3358 }
3359
3360 Quals.removeAddressSpace();
3361
3362 // Removal of the address space can mean there are no longer any
3363 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3364 // or required.
3365 if (Quals.hasNonFastQualifiers())
3366 return getExtQualType(TypeNode, Quals);
3367 else
3368 return QualType(TypeNode, Quals.getFastQualifiers());
3369}
3370
3371uint16_t
3373 bool IsVTTEntry) {
3374 assert(RD->isPolymorphic() &&
3375 "Attempted to get vtable pointer discriminator on a monomorphic type");
3376
3377 std::unique_ptr<MangleContext> MC(createMangleContext());
3378 SmallString<256> Str;
3379 llvm::raw_svector_ostream Out(Str);
3380 MC->mangleCXXVTable(RD, Out);
3381 if (IsVTTEntry)
3383 return llvm::getPointerAuthStableSipHash(Str);
3384}
3385
3386/// Encode a function type for use in the discriminator of a function pointer
3387/// type. We can't use the itanium scheme for this since C has quite permissive
3388/// rules for type compatibility that we need to be compatible with.
3389///
3390/// Formally, this function associates every function pointer type T with an
3391/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3392/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3393/// compatibility requires equivalent treatment under the ABI, so
3394/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3395/// a subset of ~. Crucially, however, it must be a proper subset because
3396/// CCompatible is not an equivalence relation: for example, int[] is compatible
3397/// with both int[1] and int[2], but the latter are not compatible with each
3398/// other. Therefore this encoding function must be careful to only distinguish
3399/// types if there is no third type with which they are both required to be
3400/// compatible.
3402 raw_ostream &OS, QualType QT) {
3403 // FIXME: Consider address space qualifiers.
3404 const Type *T = QT.getCanonicalType().getTypePtr();
3405
3406 // FIXME: Consider using the C++ type mangling when we encounter a construct
3407 // that is incompatible with C.
3408
3409 switch (T->getTypeClass()) {
3410 case Type::Atomic:
3412 Ctx, OS, cast<AtomicType>(T)->getValueType());
3413
3414 case Type::LValueReference:
3415 OS << "R";
3418 return;
3419 case Type::RValueReference:
3420 OS << "O";
3423 return;
3424
3425 case Type::Pointer:
3426 // C11 6.7.6.1p2:
3427 // For two pointer types to be compatible, both shall be identically
3428 // qualified and both shall be pointers to compatible types.
3429 // FIXME: we should also consider pointee types.
3430 OS << "P";
3431 return;
3432
3433 case Type::ObjCObjectPointer:
3434 case Type::BlockPointer:
3435 OS << "P";
3436 return;
3437
3438 case Type::Complex:
3439 OS << "C";
3441 Ctx, OS, cast<ComplexType>(T)->getElementType());
3442
3443 case Type::VariableArray:
3444 case Type::ConstantArray:
3445 case Type::IncompleteArray:
3446 case Type::ArrayParameter:
3447 // C11 6.7.6.2p6:
3448 // For two array types to be compatible, both shall have compatible
3449 // element types, and if both size specifiers are present, and are integer
3450 // constant expressions, then both size specifiers shall have the same
3451 // constant value [...]
3452 //
3453 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3454 // width of the array.
3455 OS << "A";
3457 Ctx, OS, cast<ArrayType>(T)->getElementType());
3458
3459 case Type::ObjCInterface:
3460 case Type::ObjCObject:
3461 OS << "<objc_object>";
3462 return;
3463
3464 case Type::Enum: {
3465 // C11 6.7.2.2p4:
3466 // Each enumerated type shall be compatible with char, a signed integer
3467 // type, or an unsigned integer type.
3468 //
3469 // So we have to treat enum types as integers.
3470 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3472 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3473 }
3474
3475 case Type::FunctionNoProto:
3476 case Type::FunctionProto: {
3477 // C11 6.7.6.3p15:
3478 // For two function types to be compatible, both shall specify compatible
3479 // return types. Moreover, the parameter type lists, if both are present,
3480 // shall agree in the number of parameters and in the use of the ellipsis
3481 // terminator; corresponding parameters shall have compatible types.
3482 //
3483 // That paragraph goes on to describe how unprototyped functions are to be
3484 // handled, which we ignore here. Unprototyped function pointers are hashed
3485 // as though they were prototyped nullary functions since thats probably
3486 // what the user meant. This behavior is non-conforming.
3487 // FIXME: If we add a "custom discriminator" function type attribute we
3488 // should encode functions as their discriminators.
3489 OS << "F";
3490 const auto *FuncType = cast<FunctionType>(T);
3491 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3492 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3493 for (QualType Param : FPT->param_types()) {
3494 Param = Ctx.getSignatureParameterType(Param);
3495 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3496 }
3497 if (FPT->isVariadic())
3498 OS << "z";
3499 }
3500 OS << "E";
3501 return;
3502 }
3503
3504 case Type::MemberPointer: {
3505 OS << "M";
3506 const auto *MPT = T->castAs<MemberPointerType>();
3508 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3509 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3510 return;
3511 }
3512 case Type::ExtVector:
3513 case Type::Vector:
3514 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3515 break;
3516
3517 // Don't bother discriminating based on these types.
3518 case Type::Pipe:
3519 case Type::BitInt:
3520 case Type::ConstantMatrix:
3521 OS << "?";
3522 return;
3523
3524 case Type::Builtin: {
3525 const auto *BTy = T->castAs<BuiltinType>();
3526 switch (BTy->getKind()) {
3527#define SIGNED_TYPE(Id, SingletonId) \
3528 case BuiltinType::Id: \
3529 OS << "i"; \
3530 return;
3531#define UNSIGNED_TYPE(Id, SingletonId) \
3532 case BuiltinType::Id: \
3533 OS << "i"; \
3534 return;
3535#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3536#define BUILTIN_TYPE(Id, SingletonId)
3537#include "clang/AST/BuiltinTypes.def"
3538 llvm_unreachable("placeholder types should not appear here.");
3539
3540 case BuiltinType::Half:
3541 OS << "Dh";
3542 return;
3543 case BuiltinType::Float:
3544 OS << "f";
3545 return;
3546 case BuiltinType::Double:
3547 OS << "d";
3548 return;
3549 case BuiltinType::LongDouble:
3550 OS << "e";
3551 return;
3552 case BuiltinType::Float16:
3553 OS << "DF16_";
3554 return;
3555 case BuiltinType::Float128:
3556 OS << "g";
3557 return;
3558
3559 case BuiltinType::Void:
3560 OS << "v";
3561 return;
3562
3563 case BuiltinType::ObjCId:
3564 case BuiltinType::ObjCClass:
3565 case BuiltinType::ObjCSel:
3566 case BuiltinType::NullPtr:
3567 OS << "P";
3568 return;
3569
3570 // Don't bother discriminating based on OpenCL types.
3571 case BuiltinType::OCLSampler:
3572 case BuiltinType::OCLEvent:
3573 case BuiltinType::OCLClkEvent:
3574 case BuiltinType::OCLQueue:
3575 case BuiltinType::OCLReserveID:
3576 case BuiltinType::BFloat16:
3577 case BuiltinType::VectorQuad:
3578 case BuiltinType::VectorPair:
3579 case BuiltinType::DMR1024:
3580 case BuiltinType::DMR2048:
3581 case BuiltinType::MetaInfo:
3582 OS << "?";
3583 return;
3584
3585 // Don't bother discriminating based on these seldom-used types.
3586 case BuiltinType::Ibm128:
3587 return;
3588#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3589 case BuiltinType::Id: \
3590 return;
3591#include "clang/Basic/OpenCLImageTypes.def"
3592#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3593 case BuiltinType::Id: \
3594 return;
3595#include "clang/Basic/OpenCLExtensionTypes.def"
3596#define SVE_TYPE(Name, Id, SingletonId) \
3597 case BuiltinType::Id: \
3598 return;
3599#include "clang/Basic/AArch64ACLETypes.def"
3600#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3601 case BuiltinType::Id: \
3602 return;
3603#include "clang/Basic/HLSLIntangibleTypes.def"
3604#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3605 case BuiltinType::Id: \
3606 return;
3607#include "clang/Basic/HLSLPackedTypes.def"
3608 case BuiltinType::Dependent:
3609 llvm_unreachable("should never get here");
3610#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3611#include "clang/Basic/AMDGPUTypes.def"
3612 case BuiltinType::WasmExternRef:
3613#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3614#include "clang/Basic/RISCVVTypes.def"
3615#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3616#include "clang/Basic/SPIRVTypes.def"
3617 llvm_unreachable("not yet implemented");
3618 }
3619 llvm_unreachable("should never get here");
3620 }
3621 case Type::Record: {
3622 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3623 const IdentifierInfo *II = RD->getIdentifier();
3624
3625 // In C++, an immediate typedef of an anonymous struct or union
3626 // is considered to name it for ODR purposes, but C's specification
3627 // of type compatibility does not have a similar rule. Using the typedef
3628 // name in function type discriminators anyway, as we do here,
3629 // therefore technically violates the C standard: two function pointer
3630 // types defined in terms of two typedef'd anonymous structs with
3631 // different names are formally still compatible, but we are assigning
3632 // them different discriminators and therefore incompatible ABIs.
3633 //
3634 // This is a relatively minor violation that significantly improves
3635 // discrimination in some cases and has not caused problems in
3636 // practice. Regardless, it is now part of the ABI in places where
3637 // function type discrimination is used, and it can no longer be
3638 // changed except on new platforms.
3639
3640 if (!II)
3641 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3642 II = Typedef->getDeclName().getAsIdentifierInfo();
3643
3644 if (!II) {
3645 OS << "<anonymous_record>";
3646 return;
3647 }
3648 OS << II->getLength() << II->getName();
3649 return;
3650 }
3651 case Type::HLSLAttributedResource:
3652 case Type::HLSLInlineSpirv:
3653 llvm_unreachable("should never get here");
3654 break;
3655 case Type::OverflowBehavior:
3656 llvm_unreachable("should never get here");
3657 break;
3658 case Type::DeducedTemplateSpecialization:
3659 case Type::Auto:
3660#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3661#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3663#define ABSTRACT_TYPE(Class, Base)
3664#define TYPE(Class, Base)
3665#include "clang/AST/TypeNodes.inc"
3666 llvm_unreachable("unexpected non-canonical or dependent type!");
3667 return;
3668 }
3669}
3670
3672 assert(!T->isDependentType() &&
3673 "cannot compute type discriminator of a dependent type");
3674 SmallString<256> Str;
3675 llvm::raw_svector_ostream Out(Str);
3676
3677 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3678 T = T->getPointeeType();
3679
3680 if (T->isFunctionType()) {
3682 } else {
3683 T = T.getUnqualifiedType();
3684 // Calls to member function pointers don't need to worry about
3685 // language interop or the laxness of the C type compatibility rules.
3686 // We just mangle the member pointer type directly, which is
3687 // implicitly much stricter about type matching. However, we do
3688 // strip any top-level exception specification before this mangling.
3689 // C++23 requires calls to work when the function type is convertible
3690 // to the pointer type by a function pointer conversion, which can
3691 // change the exception specification. This does not technically
3692 // require the exception specification to not affect representation,
3693 // because the function pointer conversion is still always a direct
3694 // value conversion and therefore an opportunity to resign the
3695 // pointer. (This is in contrast to e.g. qualification conversions,
3696 // which can be applied in nested pointer positions, effectively
3697 // requiring qualified and unqualified representations to match.)
3698 // However, it is pragmatic to ignore exception specifications
3699 // because it allows a certain amount of `noexcept` mismatching
3700 // to not become a visible ODR problem. This also leaves some
3701 // room for the committee to add laxness to function pointer
3702 // conversions in future standards.
3703 if (auto *MPT = T->getAs<MemberPointerType>())
3704 if (MPT->isMemberFunctionPointer()) {
3705 QualType PointeeType = MPT->getPointeeType();
3706 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3707 EST_None) {
3709 T = getMemberPointerType(FT, MPT->getQualifier(),
3710 MPT->getMostRecentCXXRecordDecl());
3711 }
3712 }
3713 std::unique_ptr<MangleContext> MC(createMangleContext());
3714 MC->mangleCanonicalTypeName(T, Out);
3715 }
3716
3717 return llvm::getPointerAuthStableSipHash(Str);
3718}
3719
3721 Qualifiers::GC GCAttr) const {
3722 QualType CanT = getCanonicalType(T);
3723 if (CanT.getObjCGCAttr() == GCAttr)
3724 return T;
3725
3726 if (const auto *ptr = T->getAs<PointerType>()) {
3727 QualType Pointee = ptr->getPointeeType();
3728 if (Pointee->isAnyPointerType()) {
3729 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3730 return getPointerType(ResultType);
3731 }
3732 }
3733
3734 // If we are composing extended qualifiers together, merge together
3735 // into one ExtQuals node.
3736 QualifierCollector Quals;
3737 const Type *TypeNode = Quals.strip(T);
3738
3739 // If this type already has an ObjCGC specified, it cannot get
3740 // another one.
3741 assert(!Quals.hasObjCGCAttr() &&
3742 "Type cannot have multiple ObjCGCs!");
3743 Quals.addObjCGCAttr(GCAttr);
3744
3745 return getExtQualType(TypeNode, Quals);
3746}
3747
3749 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3750 QualType Pointee = Ptr->getPointeeType();
3751 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3752 return getPointerType(removeAddrSpaceQualType(Pointee));
3753 }
3754 }
3755 return T;
3756}
3757
3759 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3760 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3761 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3762 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3763
3764 // Complete (non-late-parsed) path: the count expression is known up front.
3765 // This deliberately preserves the pre-existing uniquing behavior -- the
3766 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3767 // getIncompleteCountAttributedType (count filled in later) opts out of
3768 // uniquing.
3769 llvm::FoldingSetNodeID ID;
3770 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3771
3772 llvm::FoldingSetInsertToken Token;
3773 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3774 if (CATy)
3775 return QualType(CATy, 0);
3776
3777 QualType CanonTy = getCanonicalType(WrappedTy);
3778 CATy = CountAttributedType::Create(*this, WrappedTy, CanonTy, CountExpr,
3779 CountInBytes, OrNull, DependentDecls);
3780 Types.push_back(CATy);
3781 CountAttributedTypes.insert(CATy, Token);
3782
3783 return QualType(CATy, 0);
3784}
3785
3787 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3788 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3789
3790 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3791 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3792 // null here, so every incomplete node would profile identically as
3793 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3794 // collide. The node stays un-uniqued even after completion; see
3795 // `completeCountAttributedType`.
3796 //
3797 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3798 // without ever being completed (a nested counted_by, or an argument that
3799 // fails to parse), and a null-count node must not be reachable by anything
3800 // that scans `Types`. `completeCountAttributedType` registers it once the
3801 // count is in place.
3802 return CountAttributedType::Create(
3803 *this, WrappedTy, getCanonicalType(WrappedTy),
3804 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3805 /*CoupledDecls=*/{});
3806}
3807
3809 CountAttributedType *CATy, Expr *CountExpr,
3810 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3811 CATy->complete(*this, CountExpr, DependentDecls);
3812 // Safe for `Types` scanners now that the count is in place; see
3813 // `getIncompleteCountAttributedType` for why it was held back.
3814 //
3815 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3816 // an eagerly built node: this pointer is already embedded in the enclosing
3817 // types and handed out, so an equal node that happens to exist cannot be
3818 // merged into. The only cost is that a completed node is never
3819 // pointer-shared with an equal eager one, which does not affect semantic
3820 // type equality -- `hasSameType` compares canonical types, and this sugar's
3821 // canonical type is the wrapped type's.
3822 Types.push_back(CATy);
3823}
3824
3826 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3827 QualType CanonTy = getCanonicalType(WrappedTy);
3828
3829 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3830 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3831
3832 Types.push_back(LPATy);
3833 return QualType(LPATy, 0);
3834}
3835
3838 llvm::function_ref<QualType(QualType)> Adjust) const {
3839 switch (Orig->getTypeClass()) {
3840 case Type::Attributed: {
3841 const auto *AT = cast<AttributedType>(Orig);
3842 return getAttributedType(AT->getAttrKind(),
3843 adjustType(AT->getModifiedType(), Adjust),
3844 adjustType(AT->getEquivalentType(), Adjust),
3845 AT->getAttr());
3846 }
3847
3848 case Type::BTFTagAttributed: {
3849 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3850 return getBTFTagAttributedType(BTFT->getAttr(),
3851 adjustType(BTFT->getWrappedType(), Adjust));
3852 }
3853
3854 case Type::OverflowBehavior: {
3855 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3856 return getOverflowBehaviorType(OB->getBehaviorKind(),
3857 adjustType(OB->getUnderlyingType(), Adjust));
3858 }
3859
3860 case Type::Paren:
3861 return getParenType(
3862 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3863
3864 case Type::Adjusted: {
3865 const auto *AT = cast<AdjustedType>(Orig);
3866 return getAdjustedType(AT->getOriginalType(),
3867 adjustType(AT->getAdjustedType(), Adjust));
3868 }
3869
3870 case Type::MacroQualified: {
3871 const auto *MQT = cast<MacroQualifiedType>(Orig);
3872 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3873 MQT->getMacroIdentifier());
3874 }
3875
3876 default:
3877 return Adjust(Orig);
3878 }
3879}
3880
3882 FunctionType::ExtInfo Info) {
3883 if (T->getExtInfo() == Info)
3884 return T;
3885
3887 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3888 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3889 } else {
3890 const auto *FPT = cast<FunctionProtoType>(T);
3891 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3892 EPI.ExtInfo = Info;
3893 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3894 }
3895
3896 return cast<FunctionType>(Result.getTypePtr());
3897}
3898
3900 QualType ResultType) {
3901 return adjustType(FunctionType, [&](QualType Orig) {
3902 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3903 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3904
3905 const auto *FPT = Orig->castAs<FunctionProtoType>();
3906 return getFunctionType(ResultType, FPT->getParamTypes(),
3907 FPT->getExtProtoInfo());
3908 });
3909}
3910
3912 QualType ResultType) {
3913 FD = FD->getMostRecentDecl();
3914 while (true) {
3915 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3916 if (FunctionDecl *Next = FD->getPreviousDecl())
3917 FD = Next;
3918 else
3919 break;
3920 }
3922 L->DeducedReturnType(FD, ResultType);
3923}
3924
3925/// Get a function type and produce the equivalent function type with the
3926/// specified exception specification. Type sugar that can be present on a
3927/// declaration of a function with an exception specification is permitted
3928/// and preserved. Other type sugar (for instance, typedefs) is not.
3930 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3931 return adjustType(Orig, [&](QualType Ty) {
3932 const auto *Proto = Ty->castAs<FunctionProtoType>();
3933 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3934 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3935 });
3936}
3937
3945
3947 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3948 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3949 SmallVector<QualType, 16> Args(Proto->param_types().size());
3950 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3951 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3952 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3953 }
3954
3955 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3956 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3957 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3958 }
3959
3960 return T;
3961}
3962
3968
3970 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3971 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3972 EPI.ExtParameterInfos = nullptr;
3973 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3974 }
3975 return T;
3976}
3977
3983
3986 bool AsWritten) {
3987 // Update the type.
3988 QualType Updated =
3990 FD->setType(Updated);
3991
3992 if (!AsWritten)
3993 return;
3994
3995 // Update the type in the type source information too.
3996 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3997 // If the type and the type-as-written differ, we may need to update
3998 // the type-as-written too.
3999 if (TSInfo->getType() != FD->getType())
4000 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
4001
4002 // FIXME: When we get proper type location information for exceptions,
4003 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4004 // up the TypeSourceInfo;
4005 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4006 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4007 "TypeLoc size mismatch from updating exception specification");
4008 TSInfo->overrideType(Updated);
4009 }
4010}
4011
4012/// getComplexType - Return the uniqued reference to the type for a complex
4013/// number with the specified element type.
4015 // Unique pointers, to guarantee there is only one pointer of a particular
4016 // structure.
4017 llvm::FoldingSetInsertToken Token;
4018 if (ComplexType *CT = ComplexTypes.lookup(T, Token))
4019 return QualType(CT, 0);
4020
4021 // If the pointee type isn't canonical, this won't be a canonical type either,
4022 // so fill in the canonical type field.
4023 QualType Canonical;
4024 if (!T.isCanonical()) {
4025 Canonical = getComplexType(getCanonicalType(T));
4026
4027 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4028 }
4029 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4030 Types.push_back(New);
4031 ComplexTypes.insert(New, Token);
4032 return QualType(New, 0);
4033}
4034
4035/// getPointerType - Return the uniqued reference to the type for a pointer to
4036/// the specified type.
4038 // Unique pointers, to guarantee there is only one pointer of a particular
4039 // structure.
4040 llvm::FoldingSetInsertToken Token;
4041 if (PointerType *PT = PointerTypes.lookup(T, Token))
4042 return QualType(PT, 0);
4043
4044 // If the pointee type isn't canonical, this won't be a canonical type either,
4045 // so fill in the canonical type field.
4046 QualType Canonical;
4047 if (!T.isCanonical()) {
4048 Canonical = getPointerType(getCanonicalType(T));
4049
4050 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4051 }
4052 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4053 Types.push_back(New);
4054 PointerTypes.insert(New, Token);
4055 return QualType(New, 0);
4056}
4057
4059 llvm::FoldingSetInsertToken Token;
4060 AdjustedType *AT = AdjustedTypes.lookup({Orig, New}, Token);
4061 if (AT)
4062 return QualType(AT, 0);
4063
4064 QualType Canonical = getCanonicalType(New);
4065
4066 AT = new (*this, alignof(AdjustedType))
4067 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4068 Types.push_back(AT);
4069 AdjustedTypes.insert(AT, Token);
4070 return QualType(AT, 0);
4071}
4072
4074 llvm::FoldingSetInsertToken Token;
4075 AdjustedType *AT = AdjustedTypes.lookup({Orig, Decayed}, Token);
4076 if (AT)
4077 return QualType(AT, 0);
4078
4079 QualType Canonical = getCanonicalType(Decayed);
4080
4081 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4082 Types.push_back(AT);
4083 AdjustedTypes.insert(AT, Token);
4084 return QualType(AT, 0);
4085}
4086
4088 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4089
4090 QualType Decayed;
4091
4092 // C99 6.7.5.3p7:
4093 // A declaration of a parameter as "array of type" shall be
4094 // adjusted to "qualified pointer to type", where the type
4095 // qualifiers (if any) are those specified within the [ and ] of
4096 // the array type derivation.
4097 if (T->isArrayType())
4098 Decayed = getArrayDecayedType(T);
4099
4100 // C99 6.7.5.3p8:
4101 // A declaration of a parameter as "function returning type"
4102 // shall be adjusted to "pointer to function returning type", as
4103 // in 6.3.2.1.
4104 if (T->isFunctionType())
4105 Decayed = getPointerType(T);
4106
4107 return getDecayedType(T, Decayed);
4108}
4109
4111 if (Ty->isArrayParameterType())
4112 return Ty;
4113 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4114 QualType DTy = Ty.getDesugaredType(*this);
4115 const auto *ATy = cast<ConstantArrayType>(DTy);
4116 llvm::FoldingSetNodeID ID;
4117 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4118 ATy->getSizeExpr(), ATy->getSizeModifier(),
4119 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4120 llvm::FoldingSetInsertToken Token;
4121 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4122 if (AT)
4123 return QualType(AT, 0);
4124
4125 QualType Canonical;
4126 if (!DTy.isCanonical()) {
4127 Canonical = getArrayParameterType(getCanonicalType(Ty));
4128
4129 // Get the new insert position for the node we care about.
4130 AT = ArrayParameterTypes.lookup(ID, Token);
4131 assert(!AT && "Shouldn't be in the map!");
4132 }
4133
4134 AT = new (*this, alignof(ArrayParameterType))
4135 ArrayParameterType(ATy, Canonical);
4136 Types.push_back(AT);
4137 ArrayParameterTypes.insert(AT, Token);
4138 return QualType(AT, 0);
4139}
4140
4141/// getBlockPointerType - Return the uniqued reference to the type for
4142/// a pointer to the specified block.
4144 assert(T->isFunctionType() && "block of function types only");
4145 // Unique pointers, to guarantee there is only one block of a particular
4146 // structure.
4147 llvm::FoldingSetInsertToken Token;
4148 if (BlockPointerType *PT = BlockPointerTypes.lookup(T, Token))
4149 return QualType(PT, 0);
4150
4151 // If the block pointee type isn't canonical, this won't be a canonical
4152 // type either so fill in the canonical type field.
4153 QualType Canonical;
4154 if (!T.isCanonical()) {
4156
4157 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4158 }
4159 auto *New =
4160 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4161 Types.push_back(New);
4162 BlockPointerTypes.insert(New, Token);
4163 return QualType(New, 0);
4164}
4165
4166/// getLValueReferenceType - Return the uniqued reference to the type for an
4167/// lvalue reference to the specified type.
4169ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4170 assert((!T->isPlaceholderType() ||
4171 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4172 "Unresolved placeholder type");
4173
4174 // Unique pointers, to guarantee there is only one pointer of a particular
4175 // structure.
4176 llvm::FoldingSetInsertToken Token;
4177 if (LValueReferenceType *RT =
4178 LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token))
4179 return QualType(RT, 0);
4180
4181 const auto *InnerRef = T->getAs<ReferenceType>();
4182
4183 // If the referencee type isn't canonical, this won't be a canonical type
4184 // either, so fill in the canonical type field.
4185 QualType Canonical;
4186 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4187 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4188 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4189
4190 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4191 "Shouldn't be in the map!");
4192 }
4193
4194 auto *New = new (*this, alignof(LValueReferenceType))
4195 LValueReferenceType(T, Canonical, SpelledAsLValue);
4196 Types.push_back(New);
4197 LValueReferenceTypes.insert(New, Token);
4198
4199 return QualType(New, 0);
4200}
4201
4202/// getRValueReferenceType - Return the uniqued reference to the type for an
4203/// rvalue reference to the specified type.
4205 assert((!T->isPlaceholderType() ||
4206 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4207 "Unresolved placeholder type");
4208
4209 // Unique pointers, to guarantee there is only one pointer of a particular
4210 // structure.
4211 llvm::FoldingSetInsertToken Token;
4212 if (RValueReferenceType *RT = RValueReferenceTypes.lookup({T, false}, Token))
4213 return QualType(RT, 0);
4214
4215 const auto *InnerRef = T->getAs<ReferenceType>();
4216
4217 // If the referencee type isn't canonical, this won't be a canonical type
4218 // either, so fill in the canonical type field.
4219 QualType Canonical;
4220 if (InnerRef || !T.isCanonical()) {
4221 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4222 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4223
4224 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4225 "Shouldn't be in the map!");
4226 }
4227
4228 auto *New = new (*this, alignof(RValueReferenceType))
4229 RValueReferenceType(T, Canonical);
4230 Types.push_back(New);
4231 RValueReferenceTypes.insert(New, Token);
4232 return QualType(New, 0);
4233}
4234
4236 NestedNameSpecifier Qualifier,
4237 const CXXRecordDecl *Cls) const {
4238 if (!Qualifier) {
4239 assert(Cls && "At least one of Qualifier or Cls must be provided");
4240 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4241 } else if (!Cls) {
4242 Cls = Qualifier.getAsRecordDecl();
4243 }
4244 // Unique pointers, to guarantee there is only one pointer of a particular
4245 // structure.
4246 llvm::FoldingSetNodeID ID;
4247 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4248
4249 llvm::FoldingSetInsertToken Token;
4250 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4251 return QualType(PT, 0);
4252
4253 NestedNameSpecifier CanonicalQualifier = [&] {
4254 if (!Cls)
4255 return Qualifier.getCanonical();
4256 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4257 assert(R.isCanonical());
4258 return R;
4259 }();
4260 // If the pointee or class type isn't canonical, this won't be a canonical
4261 // type either, so fill in the canonical type field.
4262 QualType Canonical;
4263 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4264 Canonical =
4265 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4266 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4267 // Get the new insert position for the node we care about.
4268 [[maybe_unused]] MemberPointerType *NewIP =
4269 MemberPointerTypes.lookup(ID, Token);
4270 assert(!NewIP && "Shouldn't be in the map!");
4271 }
4272 auto *New = new (*this, alignof(MemberPointerType))
4273 MemberPointerType(T, Qualifier, Canonical);
4274 Types.push_back(New);
4275 MemberPointerTypes.insert(New, Token);
4276 return QualType(New, 0);
4277}
4278
4279/// getConstantArrayType - Return the unique reference to the type for an
4280/// array of the specified element type.
4282 const llvm::APInt &ArySizeIn,
4283 const Expr *SizeExpr,
4285 unsigned IndexTypeQuals) const {
4286 assert((EltTy->isDependentType() ||
4287 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4288 "Constant array of VLAs is illegal!");
4289
4290 // We only need the size as part of the type if it's instantiation-dependent.
4291 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4292 SizeExpr = nullptr;
4293
4294 // Convert the array size into a canonical width matching the pointer size for
4295 // the target.
4296 llvm::APInt ArySize(ArySizeIn);
4297 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4298
4299 llvm::FoldingSetNodeID ID;
4300 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4301 ASM, IndexTypeQuals);
4302
4303 llvm::FoldingSetInsertToken Token;
4304 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4305 return QualType(ATP, 0);
4306
4307 // If the element type isn't canonical or has qualifiers, or the array bound
4308 // is instantiation-dependent, this won't be a canonical type either, so fill
4309 // in the canonical type field.
4310 QualType Canon;
4311 // FIXME: Check below should look for qualifiers behind sugar.
4312 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4313 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4314 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4315 ASM, IndexTypeQuals);
4316 Canon = getQualifiedType(Canon, canonSplit.Quals);
4317
4318 // Get the new insert position for the node we care about.
4319 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4320 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4321 }
4322
4323 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4324 ASM, IndexTypeQuals);
4325 ConstantArrayTypes.insert(New, Token);
4326 Types.push_back(New);
4327 return QualType(New, 0);
4328}
4329
4330/// getVariableArrayDecayedType - Turns the given type, which may be
4331/// variably-modified, into the corresponding type with all the known
4332/// sizes replaced with [*].
4334 // Vastly most common case.
4335 if (!type->isVariablyModifiedType()) return type;
4336
4337 QualType result;
4338
4339 SplitQualType split = type.getSplitDesugaredType();
4340 const Type *ty = split.Ty;
4341 switch (ty->getTypeClass()) {
4342#define TYPE(Class, Base)
4343#define ABSTRACT_TYPE(Class, Base)
4344#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4345#include "clang/AST/TypeNodes.inc"
4346 llvm_unreachable("didn't desugar past all non-canonical types?");
4347
4348 // These types should never be variably-modified.
4349 case Type::Builtin:
4350 case Type::Complex:
4351 case Type::Vector:
4352 case Type::DependentVector:
4353 case Type::ExtVector:
4354 case Type::DependentSizedExtVector:
4355 case Type::ConstantMatrix:
4356 case Type::DependentSizedMatrix:
4357 case Type::DependentAddressSpace:
4358 case Type::ObjCObject:
4359 case Type::ObjCInterface:
4360 case Type::ObjCObjectPointer:
4361 case Type::Record:
4362 case Type::Enum:
4363 case Type::UnresolvedUsing:
4364 case Type::TypeOfExpr:
4365 case Type::TypeOf:
4366 case Type::Decltype:
4367 case Type::UnaryTransform:
4368 case Type::DependentName:
4369 case Type::InjectedClassName:
4370 case Type::TemplateSpecialization:
4371 case Type::TemplateTypeParm:
4372 case Type::SubstTemplateTypeParmPack:
4373 case Type::SubstBuiltinTemplatePack:
4374 case Type::Auto:
4375 case Type::DeducedTemplateSpecialization:
4376 case Type::PackExpansion:
4377 case Type::PackIndexing:
4378 case Type::BitInt:
4379 case Type::DependentBitInt:
4380 case Type::ArrayParameter:
4381 case Type::HLSLAttributedResource:
4382 case Type::HLSLInlineSpirv:
4383 case Type::OverflowBehavior:
4384 llvm_unreachable("type should never be variably-modified");
4385
4386 // These types can be variably-modified but should never need to
4387 // further decay.
4388 case Type::FunctionNoProto:
4389 case Type::FunctionProto:
4390 case Type::BlockPointer:
4391 case Type::MemberPointer:
4392 case Type::Pipe:
4393 return type;
4394
4395 // These types can be variably-modified. All these modifications
4396 // preserve structure except as noted by comments.
4397 // TODO: if we ever care about optimizing VLAs, there are no-op
4398 // optimizations available here.
4399 case Type::Pointer:
4402 break;
4403
4404 case Type::LValueReference: {
4405 const auto *lv = cast<LValueReferenceType>(ty);
4406 result = getLValueReferenceType(
4407 getVariableArrayDecayedType(lv->getPointeeType()),
4408 lv->isSpelledAsLValue());
4409 break;
4410 }
4411
4412 case Type::RValueReference: {
4413 const auto *lv = cast<RValueReferenceType>(ty);
4414 result = getRValueReferenceType(
4415 getVariableArrayDecayedType(lv->getPointeeType()));
4416 break;
4417 }
4418
4419 case Type::Atomic: {
4420 const auto *at = cast<AtomicType>(ty);
4421 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4422 break;
4423 }
4424
4425 case Type::ConstantArray: {
4426 const auto *cat = cast<ConstantArrayType>(ty);
4427 result = getConstantArrayType(
4428 getVariableArrayDecayedType(cat->getElementType()),
4429 cat->getSize(),
4430 cat->getSizeExpr(),
4431 cat->getSizeModifier(),
4432 cat->getIndexTypeCVRQualifiers());
4433 break;
4434 }
4435
4436 case Type::DependentSizedArray: {
4437 const auto *dat = cast<DependentSizedArrayType>(ty);
4439 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4440 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4441 break;
4442 }
4443
4444 // Turn incomplete types into [*] types.
4445 case Type::IncompleteArray: {
4446 const auto *iat = cast<IncompleteArrayType>(ty);
4447 result =
4449 /*size*/ nullptr, ArraySizeModifier::Normal,
4450 iat->getIndexTypeCVRQualifiers());
4451 break;
4452 }
4453
4454 // Turn VLA types into [*] types.
4455 case Type::VariableArray: {
4456 const auto *vat = cast<VariableArrayType>(ty);
4457 result =
4459 /*size*/ nullptr, ArraySizeModifier::Star,
4460 vat->getIndexTypeCVRQualifiers());
4461 break;
4462 }
4463 }
4464
4465 // Apply the top-level qualifiers from the original.
4466 return getQualifiedType(result, split.Quals);
4467}
4468
4469/// getVariableArrayType - Returns a non-unique reference to the type for a
4470/// variable array of the specified element type.
4473 unsigned IndexTypeQuals) const {
4474 // Since we don't unique expressions, it isn't possible to unique VLA's
4475 // that have an expression provided for their size.
4476 QualType Canon;
4477
4478 // Be sure to pull qualifiers off the element type.
4479 // FIXME: Check below should look for qualifiers behind sugar.
4480 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4481 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4482 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4483 IndexTypeQuals);
4484 Canon = getQualifiedType(Canon, canonSplit.Quals);
4485 }
4486
4487 auto *New = new (*this, alignof(VariableArrayType))
4488 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4489
4490 VariableArrayTypes.push_back(New);
4491 Types.push_back(New);
4492 return QualType(New, 0);
4493}
4494
4495/// getDependentSizedArrayType - Returns a non-unique reference to
4496/// the type for a dependently-sized array of the specified element
4497/// type.
4501 unsigned elementTypeQuals) const {
4502 assert((!numElements || numElements->isTypeDependent() ||
4503 numElements->isValueDependent()) &&
4504 "Size must be type- or value-dependent!");
4505
4506 SplitQualType canonElementType = getCanonicalType(elementType).split();
4507
4508 llvm::FoldingSetInsertToken Token;
4509 llvm::FoldingSetNodeID ID;
4511 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4512 ASM, elementTypeQuals, numElements);
4513
4514 // Look for an existing type with these properties.
4515 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4516
4517 // Dependently-sized array types that do not have a specified number
4518 // of elements will have their sizes deduced from a dependent
4519 // initializer.
4520 if (!numElements) {
4521 if (canonTy)
4522 return QualType(canonTy, 0);
4523
4524 auto *newType = new (*this, alignof(DependentSizedArrayType))
4525 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4526 elementTypeQuals);
4527 DependentSizedArrayTypes.insert(newType, Token);
4528 Types.push_back(newType);
4529 return QualType(newType, 0);
4530 }
4531
4532 // If we don't have one, build one.
4533 if (!canonTy) {
4534 canonTy = new (*this, alignof(DependentSizedArrayType))
4535 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4536 numElements, ASM, elementTypeQuals);
4537 DependentSizedArrayTypes.insert(canonTy, Token);
4538 Types.push_back(canonTy);
4539 }
4540
4541 // Apply qualifiers from the element type to the array.
4542 QualType canon = getQualifiedType(QualType(canonTy,0),
4543 canonElementType.Quals);
4544
4545 // If we didn't need extra canonicalization for the element type or the size
4546 // expression, then just use that as our result.
4547 if (QualType(canonElementType.Ty, 0) == elementType &&
4548 canonTy->getSizeExpr() == numElements)
4549 return canon;
4550
4551 // Otherwise, we need to build a type which follows the spelling
4552 // of the element type.
4553 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4554 DependentSizedArrayType(elementType, canon, numElements, ASM,
4555 elementTypeQuals);
4556 Types.push_back(sugaredType);
4557 return QualType(sugaredType, 0);
4558}
4559
4562 unsigned elementTypeQuals) const {
4563 llvm::FoldingSetNodeID ID;
4564 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4565
4566 llvm::FoldingSetInsertToken Token;
4567 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4568 return QualType(iat, 0);
4569
4570 // If the element type isn't canonical, this won't be a canonical type
4571 // either, so fill in the canonical type field. We also have to pull
4572 // qualifiers off the element type.
4573 QualType canon;
4574
4575 // FIXME: Check below should look for qualifiers behind sugar.
4576 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4577 SplitQualType canonSplit = getCanonicalType(elementType).split();
4578 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4579 ASM, elementTypeQuals);
4580 canon = getQualifiedType(canon, canonSplit.Quals);
4581
4582 // Get the new insert position for the node we care about.
4583 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4584 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4585 }
4586
4587 auto *newType = new (*this, alignof(IncompleteArrayType))
4588 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4589
4590 IncompleteArrayTypes.insert(newType, Token);
4591 Types.push_back(newType);
4592 return QualType(newType, 0);
4593}
4594
4597#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4598 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4599 NUMVECTORS};
4600
4601#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4602 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4603
4604 switch (Ty->getKind()) {
4605 default:
4606 llvm_unreachable("Unsupported builtin vector type");
4607
4608#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4609 ElBits, NF, IsSigned) \
4610 case BuiltinType::Id: \
4611 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4612 llvm::ElementCount::getScalable(NumEls), NF};
4613#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4614 ElBits, NF) \
4615 case BuiltinType::Id: \
4616 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4617 llvm::ElementCount::getScalable(NumEls), NF};
4618#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4619 ElBits, NF) \
4620 case BuiltinType::Id: \
4621 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4622#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4623 ElBits, NF) \
4624 case BuiltinType::Id: \
4625 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4626#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4627 case BuiltinType::Id: \
4628 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4629#include "clang/Basic/AArch64ACLETypes.def"
4630
4631#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4632 IsSigned) \
4633 case BuiltinType::Id: \
4634 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4635 llvm::ElementCount::getScalable(NumEls), NF};
4636#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4637 case BuiltinType::Id: \
4638 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4639 llvm::ElementCount::getScalable(NumEls), NF};
4640#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4641 case BuiltinType::Id: \
4642 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4643#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4644 case BuiltinType::Id: \
4645 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4646#include "clang/Basic/RISCVVTypes.def"
4647 }
4648}
4649
4650/// getExternrefType - Return a WebAssembly externref type, which represents an
4651/// opaque reference to a host value.
4653 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4654#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4655 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4656 return SingletonId;
4657#include "clang/Basic/WebAssemblyReferenceTypes.def"
4658 }
4659 llvm_unreachable(
4660 "shouldn't try to generate type externref outside WebAssembly target");
4661}
4662
4663/// getScalableVectorType - Return the unique reference to a scalable vector
4664/// type of the specified element type and size. VectorType must be a built-in
4665/// type.
4667 unsigned NumFields) const {
4668 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4669 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4670 return It->second;
4671
4672 if (Target->hasAArch64ACLETypes()) {
4673 uint64_t EltTySize = getTypeSize(EltTy);
4674
4675#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4676 ElBits, NF, IsSigned) \
4677 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4678 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4679 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4680 return ScalableVecTyMap[K] = SingletonId; \
4681 }
4682#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4683 ElBits, NF) \
4684 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4685 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4686 return ScalableVecTyMap[K] = SingletonId; \
4687 }
4688#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4689 ElBits, NF) \
4690 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4691 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4692 return ScalableVecTyMap[K] = SingletonId; \
4693 }
4694#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4695 ElBits, NF) \
4696 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4697 NumElts == (NumEls * NF) && NumFields == 1) { \
4698 return ScalableVecTyMap[K] = SingletonId; \
4699 }
4700#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4701 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4702 return ScalableVecTyMap[K] = SingletonId;
4703#include "clang/Basic/AArch64ACLETypes.def"
4704 } else if (Target->hasRISCVVTypes()) {
4705 uint64_t EltTySize = getTypeSize(EltTy);
4706#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4707 IsFP, IsBF) \
4708 if (!EltTy->isBooleanType() && \
4709 ((EltTy->hasIntegerRepresentation() && \
4710 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4711 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4712 IsFP && !IsBF) || \
4713 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4714 IsBF && !IsFP)) && \
4715 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4716 return ScalableVecTyMap[K] = SingletonId;
4717#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4718 if (EltTy->isBooleanType() && NumElts == NumEls) \
4719 return ScalableVecTyMap[K] = SingletonId;
4720#include "clang/Basic/RISCVVTypes.def"
4721 }
4722 return QualType();
4723}
4724
4725/// getVectorType - Return the unique reference to a vector type of
4726/// the specified element type and size. VectorType must be a built-in type.
4728 VectorKind VecKind) const {
4729 assert(vecType->isBuiltinType() ||
4730 (vecType->isBitIntType() &&
4731 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4732 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4733
4734 // Check if we've already instantiated a vector of this type.
4735 llvm::FoldingSetNodeID ID;
4736 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4737
4738 llvm::FoldingSetInsertToken Token;
4739 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4740 return QualType(VTP, 0);
4741
4742 // If the element type isn't canonical, this won't be a canonical type either,
4743 // so fill in the canonical type field.
4744 QualType Canonical;
4745 if (!vecType.isCanonical()) {
4746 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4747
4748 // Get the new insert position for the node we care about.
4749 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4750 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4751 }
4752 auto *New = new (*this, alignof(VectorType))
4753 VectorType(vecType, NumElts, Canonical, VecKind);
4754 VectorTypes.insert(New, Token);
4755 Types.push_back(New);
4756 return QualType(New, 0);
4757}
4758
4760 SourceLocation AttrLoc,
4761 VectorKind VecKind) const {
4762 llvm::FoldingSetNodeID ID;
4763 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4764 VecKind);
4765 llvm::FoldingSetInsertToken Token;
4766 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4768
4769 if (Canon) {
4770 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4771 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4772 } else {
4773 QualType CanonVecTy = getCanonicalType(VecType);
4774 if (CanonVecTy == VecType) {
4775 New = new (*this, alignof(DependentVectorType))
4776 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4777
4778 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4779 assert(!CanonCheck &&
4780 "Dependent-sized vector_size canonical type broken");
4781 (void)CanonCheck;
4782 DependentVectorTypes.insert(New, Token);
4783 } else {
4784 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4785 SourceLocation(), VecKind);
4786 New = new (*this, alignof(DependentVectorType))
4787 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4788 }
4789 }
4790
4791 Types.push_back(New);
4792 return QualType(New, 0);
4793}
4794
4795/// getExtVectorType - Return the unique reference to an extended vector type of
4796/// the specified element type and size. VectorType must be a built-in type.
4798 unsigned NumElts) const {
4799 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4800 (vecType->isBitIntType() &&
4801 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4802 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4803
4804 // Check if we've already instantiated a vector of this type.
4805 llvm::FoldingSetNodeID ID;
4806 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4808 llvm::FoldingSetInsertToken Token;
4809 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4810 return QualType(VTP, 0);
4811
4812 // If the element type isn't canonical, this won't be a canonical type either,
4813 // so fill in the canonical type field.
4814 QualType Canonical;
4815 if (!vecType.isCanonical()) {
4816 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4817
4818 // Get the new insert position for the node we care about.
4819 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4820 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4821 }
4822 auto *New = new (*this, alignof(ExtVectorType))
4823 ExtVectorType(vecType, NumElts, Canonical);
4824 VectorTypes.insert(New, Token);
4825 Types.push_back(New);
4826 return QualType(New, 0);
4827}
4828
4831 Expr *SizeExpr,
4832 SourceLocation AttrLoc) const {
4833 llvm::FoldingSetNodeID ID;
4835 SizeExpr);
4836
4837 llvm::FoldingSetInsertToken Token;
4839 DependentSizedExtVectorTypes.lookup(ID, Token);
4841 if (Canon) {
4842 // We already have a canonical version of this array type; use it as
4843 // the canonical type for a newly-built type.
4844 New = new (*this, alignof(DependentSizedExtVectorType))
4845 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4846 AttrLoc);
4847 } else {
4848 QualType CanonVecTy = getCanonicalType(vecType);
4849 if (CanonVecTy == vecType) {
4850 New = new (*this, alignof(DependentSizedExtVectorType))
4851 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4852
4853 DependentSizedExtVectorType *CanonCheck =
4854 DependentSizedExtVectorTypes.lookup(ID, Token);
4855 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4856 (void)CanonCheck;
4857 DependentSizedExtVectorTypes.insert(New, Token);
4858 } else {
4859 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4860 SourceLocation());
4861 New = new (*this, alignof(DependentSizedExtVectorType))
4862 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4863 }
4864 }
4865
4866 Types.push_back(New);
4867 return QualType(New, 0);
4868}
4869
4871 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4872 std::optional<MatrixType::LayoutKind> Layout) const {
4873 llvm::FoldingSetNodeID ID;
4874 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, Layout,
4875 Type::ConstantMatrix);
4876
4877 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4878 "need a valid element type");
4879 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4880 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4881 "need valid matrix dimensions");
4882 llvm::FoldingSetInsertToken Token;
4883 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4884 return QualType(MTP, 0);
4885
4886 QualType Canonical;
4887 if (Layout || !ElementTy.isCanonical()) {
4888 Canonical = getConstantMatrixType(getCanonicalType(ElementTy), NumRows,
4889 NumColumns, std::nullopt);
4890
4891 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4892 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4893 (void)NewIP;
4894 }
4895
4896 auto *New = new (*this, alignof(ConstantMatrixType))
4897 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4898 MatrixTypes.insert(New, Token);
4899 Types.push_back(New);
4900 return QualType(New, 0);
4901}
4902
4904 Expr *RowExpr,
4905 Expr *ColumnExpr,
4906 SourceLocation AttrLoc) const {
4907 QualType CanonElementTy = getCanonicalType(ElementTy);
4908 llvm::FoldingSetNodeID ID;
4909 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4910 ColumnExpr);
4911
4912 llvm::FoldingSetInsertToken Token;
4913 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4914
4915 if (!Canon) {
4916 Canon = new (*this, alignof(DependentSizedMatrixType))
4917 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4918 ColumnExpr, AttrLoc);
4919#ifndef NDEBUG
4920 DependentSizedMatrixType *CanonCheck =
4921 DependentSizedMatrixTypes.lookup(ID, Token);
4922 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4923#endif
4924 DependentSizedMatrixTypes.insert(Canon, Token);
4925 Types.push_back(Canon);
4926 }
4927
4928 // Already have a canonical version of the matrix type
4929 //
4930 // If it exactly matches the requested type, use it directly.
4931 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4932 Canon->getRowExpr() == ColumnExpr)
4933 return QualType(Canon, 0);
4934
4935 // Use Canon as the canonical type for newly-built type.
4937 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4938 ColumnExpr, AttrLoc);
4939 Types.push_back(New);
4940 return QualType(New, 0);
4941}
4942
4945 MatrixType::LayoutKind Layout) const {
4946 Qualifiers Quals = T.getQualifiers();
4947 const Type *Ty = T->getUnqualifiedDesugaredType();
4948
4949 if (const auto *MT = dyn_cast<ConstantMatrixType>(Ty))
4950 return getQualifiedType(getConstantMatrixType(MT->getElementType(),
4951 MT->getNumRows(),
4952 MT->getNumColumns(), Layout),
4953 Quals);
4954
4955 const auto *CAT = dyn_cast<ConstantArrayType>(Ty);
4956 if (!CAT)
4957 return T;
4958
4960 getMatrixTypeWithLayout(CAT->getElementType(), Layout), CAT->getSize(),
4961 CAT->getSizeExpr(), CAT->getSizeModifier(),
4962 CAT->getIndexTypeCVRQualifiers());
4963 if (isa<ArrayParameterType>(CAT))
4965
4966 return getQualifiedType(Result, Quals);
4967}
4968
4970 Expr *AddrSpaceExpr,
4971 SourceLocation AttrLoc) const {
4972 assert(AddrSpaceExpr->isInstantiationDependent());
4973
4974 QualType canonPointeeType = getCanonicalType(PointeeType);
4975
4976 llvm::FoldingSetInsertToken Token;
4977 llvm::FoldingSetNodeID ID;
4978 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4979 AddrSpaceExpr);
4980
4981 DependentAddressSpaceType *canonTy =
4982 DependentAddressSpaceTypes.lookup(ID, Token);
4983
4984 if (!canonTy) {
4985 canonTy = new (*this, alignof(DependentAddressSpaceType))
4986 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4987 AttrLoc);
4988 DependentAddressSpaceTypes.insert(canonTy, Token);
4989 Types.push_back(canonTy);
4990 }
4991
4992 if (canonPointeeType == PointeeType &&
4993 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4994 return QualType(canonTy, 0);
4995
4996 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4997 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4998 AddrSpaceExpr, AttrLoc);
4999 Types.push_back(sugaredType);
5000 return QualType(sugaredType, 0);
5001}
5002
5003/// Determine whether \p T is canonical as the result type of a function.
5005 return T.isCanonical() &&
5006 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5007 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5008}
5009
5010/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5011QualType
5013 const FunctionType::ExtInfo &Info) const {
5014 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5015 // functionality creates a function without a prototype regardless of
5016 // language mode (so it makes them even in C++). Once the rewriter has been
5017 // fixed, this assertion can be enabled again.
5018 //assert(!LangOpts.requiresStrictPrototypes() &&
5019 // "strict prototypes are disabled");
5020
5021 // Unique functions, to guarantee there is only one function of a particular
5022 // structure.
5023 llvm::FoldingSetNodeID ID;
5024 FunctionNoProtoType::Profile(ID, ResultTy, Info);
5025
5026 llvm::FoldingSetInsertToken Token;
5027 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5028 return QualType(FT, 0);
5029
5030 QualType Canonical;
5031 if (!isCanonicalResultType(ResultTy)) {
5032 Canonical =
5034
5035 // Get the new insert position for the node we care about.
5036 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5037 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5038 }
5039
5040 auto *New = new (*this, alignof(FunctionNoProtoType))
5041 FunctionNoProtoType(ResultTy, Canonical, Info);
5042 Types.push_back(New);
5043 FunctionNoProtoTypes.insert(New, Token);
5044 return QualType(New, 0);
5045}
5046
5049 CanQualType CanResultType = getCanonicalType(ResultType);
5050
5051 // Canonical result types do not have ARC lifetime qualifiers.
5052 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5053 Qualifiers Qs = CanResultType.getQualifiers();
5054 Qs.removeObjCLifetime();
5056 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5057 }
5058
5059 return CanResultType;
5060}
5061
5063 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5064 if (ESI.Type == EST_None)
5065 return true;
5066 if (!NoexceptInType)
5067 return false;
5068
5069 // C++17 onwards: exception specification is part of the type, as a simple
5070 // boolean "can this function type throw".
5071 if (ESI.Type == EST_BasicNoexcept)
5072 return true;
5073
5074 // A noexcept(expr) specification is (possibly) canonical if expr is
5075 // value-dependent.
5076 if (ESI.Type == EST_DependentNoexcept)
5077 return true;
5078
5079 // A dynamic exception specification is canonical if it only contains pack
5080 // expansions (so we can't tell whether it's non-throwing) and all its
5081 // contained types are canonical.
5082 if (ESI.Type == EST_Dynamic) {
5083 bool AnyPackExpansions = false;
5084 for (QualType ET : ESI.Exceptions) {
5085 if (!ET.isCanonical())
5086 return false;
5087 if (ET->getAs<PackExpansionType>())
5088 AnyPackExpansions = true;
5089 }
5090 return AnyPackExpansions;
5091 }
5092
5093 return false;
5094}
5095
5096QualType ASTContext::getFunctionTypeInternal(
5097 QualType ResultTy, ArrayRef<QualType> ArgArray,
5098 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5099 size_t NumArgs = ArgArray.size();
5100
5101 // Unique functions, to guarantee there is only one function of a particular
5102 // structure.
5103 llvm::FoldingSetNodeID ID;
5104 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5105 *this);
5106
5107 QualType Canonical;
5108 bool Unique = false;
5109
5110 llvm::FoldingSetInsertToken Token;
5111 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5112 QualType Existing = QualType(FPT, 0);
5113
5114 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5115 // it so long as our exception specification doesn't contain a dependent
5116 // noexcept expression, or we're just looking for a canonical type.
5117 // Otherwise, we're going to need to create a type
5118 // sugar node to hold the concrete expression.
5119 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5120 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5121 return Existing;
5122
5123 // We need a new type sugar node for this one, to hold the new noexcept
5124 // expression. We do no canonicalization here, but that's OK since we don't
5125 // expect to see the same noexcept expression much more than once.
5126 Canonical = getCanonicalType(Existing);
5127 Unique = true;
5128 }
5129
5130 bool NoexceptInType = getLangOpts().CPlusPlus17;
5131 bool IsCanonicalExceptionSpec =
5133
5134 // Determine whether the type being created is already canonical or not.
5135 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5136 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5137 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5138 if (!ArgArray[i].isCanonicalAsParam())
5139 isCanonical = false;
5140
5141 if (OnlyWantCanonical)
5142 assert(isCanonical &&
5143 "given non-canonical parameters constructing canonical type");
5144
5145 // If this type isn't canonical, get the canonical version of it if we don't
5146 // already have it. The exception spec is only partially part of the
5147 // canonical type, and only in C++17 onwards.
5148 if (!isCanonical && Canonical.isNull()) {
5149 SmallVector<QualType, 16> CanonicalArgs;
5150 CanonicalArgs.reserve(NumArgs);
5151 for (unsigned i = 0; i != NumArgs; ++i)
5152 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5153
5154 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5155 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5156 CanonicalEPI.HasTrailingReturn = false;
5157
5158 if (IsCanonicalExceptionSpec) {
5159 // Exception spec is already OK.
5160 } else if (NoexceptInType) {
5161 switch (EPI.ExceptionSpec.Type) {
5163 // We don't know yet. It shouldn't matter what we pick here; no-one
5164 // should ever look at this.
5165 [[fallthrough]];
5166 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5167 CanonicalEPI.ExceptionSpec.Type = EST_None;
5168 break;
5169
5170 // A dynamic exception specification is almost always "not noexcept",
5171 // with the exception that a pack expansion might expand to no types.
5172 case EST_Dynamic: {
5173 bool AnyPacks = false;
5174 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5175 if (ET->getAs<PackExpansionType>())
5176 AnyPacks = true;
5177 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5178 }
5179 if (!AnyPacks)
5180 CanonicalEPI.ExceptionSpec.Type = EST_None;
5181 else {
5182 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5183 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5184 }
5185 break;
5186 }
5187
5188 case EST_DynamicNone:
5189 case EST_BasicNoexcept:
5190 case EST_NoexceptTrue:
5191 case EST_NoThrow:
5192 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5193 break;
5194
5196 llvm_unreachable("dependent noexcept is already canonical");
5197 }
5198 } else {
5199 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5200 }
5201
5202 // Adjust the canonical function result type.
5203 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5204 Canonical =
5205 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5206
5207 // Get the new insert position for the node we care about.
5208 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5209 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5210 }
5211
5212 // Compute the needed size to hold this FunctionProtoType and the
5213 // various trailing objects.
5214 auto ESH = FunctionProtoType::getExceptionSpecSize(
5215 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5216 size_t Size = FunctionProtoType::totalSizeToAlloc<
5217 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5218 FunctionType::FunctionTypeExtraAttributeInfo,
5219 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5220 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5221 FunctionEffect, EffectConditionExpr>(
5224 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5225 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5226 EPI.ExtParameterInfos ? NumArgs : 0,
5228 EPI.FunctionEffects.conditions().size());
5229
5230 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5231 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5232 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5233 Types.push_back(FTP);
5234 if (!Unique)
5235 FunctionProtoTypes.insert(FTP, Token);
5236 if (!EPI.FunctionEffects.empty())
5237 AnyFunctionEffects = true;
5238 return QualType(FTP, 0);
5239}
5240
5241QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5242 llvm::FoldingSetInsertToken Token;
5243 if (PipeType *PT = PipeTypes.lookup({T, ReadOnly}, Token))
5244 return QualType(PT, 0);
5245
5246 // If the pipe element type isn't canonical, this won't be a canonical type
5247 // either, so fill in the canonical type field.
5248 QualType Canonical;
5249 if (!T.isCanonical()) {
5250 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5251
5252 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5253 "Shouldn't be in the map!");
5254 }
5255 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5256 Types.push_back(New);
5257 PipeTypes.insert(New, Token);
5258 return QualType(New, 0);
5259}
5260
5262 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5263 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5264 : Ty;
5265}
5266
5268 return getPipeType(T, true);
5269}
5270
5272 return getPipeType(T, false);
5273}
5274
5275QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5276 auto Key = std::make_pair(unsigned(IsUnsigned), NumBits);
5277
5278 llvm::FoldingSetInsertToken Token;
5279 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5280 return QualType(EIT, 0);
5281
5282 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5283 BitIntTypes.insert(New, Token);
5284 Types.push_back(New);
5285 return QualType(New, 0);
5286}
5287
5289 Expr *NumBitsExpr) const {
5290 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5291 llvm::FoldingSetNodeID ID;
5292 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5293
5294 llvm::FoldingSetInsertToken Token;
5295 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5296 return QualType(Existing, 0);
5297
5298 auto *New = new (*this, alignof(DependentBitIntType))
5299 DependentBitIntType(IsUnsigned, NumBitsExpr);
5300 DependentBitIntTypes.insert(New, Token);
5301
5302 Types.push_back(New);
5303 return QualType(New, 0);
5304}
5305
5308 using Kind = PredefinedSugarType::Kind;
5309
5310 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5311 Target != nullptr)
5312 return QualType(Target, 0);
5313
5314 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5315 switch (KDI) {
5316 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5317 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5318 // are part of the core language and are widely used. Using
5319 // PredefinedSugarType makes these types as named sugar types rather than
5320 // standard integer types, enabling better hints and diagnostics.
5321 case Kind::SizeT:
5322 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5323 case Kind::SignedSizeT:
5324 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5325 case Kind::PtrdiffT:
5326 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5327 }
5328 llvm_unreachable("unexpected kind");
5329 };
5330 auto *New = new (*this, alignof(PredefinedSugarType))
5331 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5332 getCanonicalType(*this, static_cast<Kind>(KD)));
5333 Types.push_back(New);
5334 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5335 return QualType(New, 0);
5336}
5337
5339 NestedNameSpecifier Qualifier,
5340 const TypeDecl *Decl) const {
5341 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5342 return getTagType(Keyword, Qualifier, Tag,
5343 /*OwnsTag=*/false);
5344 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5345 return getTypedefType(Keyword, Qualifier, Typedef);
5346 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5347 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5348
5350 assert(!Qualifier);
5351 return QualType(Decl->TypeForDecl, 0);
5352}
5353
5355 if (auto *Tag = dyn_cast<TagDecl>(TD))
5356 return getCanonicalTagType(Tag);
5357 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5358 return getCanonicalType(TN->getUnderlyingType());
5359 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5361 assert(TD->TypeForDecl);
5362 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5363}
5364
5366 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5367 return getCanonicalTagType(TD);
5368 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5369 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5371 /*Qualifier=*/std::nullopt, TD);
5372 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5373 return getCanonicalUnresolvedUsingType(Using);
5374
5375 assert(Decl->TypeForDecl);
5376 return QualType(Decl->TypeForDecl, 0);
5377}
5378
5379/// getTypedefType - Return the unique reference to the type for the
5380/// specified typedef name decl.
5383 NestedNameSpecifier Qualifier,
5384 const TypedefNameDecl *Decl, QualType UnderlyingType,
5385 std::optional<bool> TypeMatchesDeclOrNone) const {
5386 if (!TypeMatchesDeclOrNone) {
5387 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5388 assert(!DeclUnderlyingType.isNull());
5389 if (UnderlyingType.isNull())
5390 UnderlyingType = DeclUnderlyingType;
5391 else
5392 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5393 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5394 } else {
5395 // FIXME: This is a workaround for a serialization cycle: assume the decl
5396 // underlying type is not available; don't touch it.
5397 assert(!UnderlyingType.isNull());
5398 }
5399
5400 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5401 *TypeMatchesDeclOrNone) {
5402 if (Decl->TypeForDecl)
5403 return QualType(Decl->TypeForDecl, 0);
5404
5405 auto *NewType = new (*this, alignof(TypedefType))
5406 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5407 !*TypeMatchesDeclOrNone);
5408
5409 Types.push_back(NewType);
5410 Decl->TypeForDecl = NewType;
5411 return QualType(NewType, 0);
5412 }
5413
5414 llvm::FoldingSetNodeID ID;
5415 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5416 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5417
5418 llvm::FoldingSetInsertToken Token;
5419 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5420 TypedefTypes.lookup(ID, Token))
5421 return QualType(Placeholder->getType(), 0);
5422
5423 void *Mem =
5424 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5426 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5427 alignof(TypedefType));
5428 auto *NewType =
5429 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5430 UnderlyingType, !*TypeMatchesDeclOrNone);
5431 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5433 TypedefTypes.insert(Placeholder, Token);
5434 Types.push_back(NewType);
5435 return QualType(NewType, 0);
5436}
5437
5439 NestedNameSpecifier Qualifier,
5440 const UsingShadowDecl *D,
5441 QualType UnderlyingType) const {
5442 // FIXME: This is expensive to compute every time!
5443 if (UnderlyingType.isNull()) {
5444 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5445 UnderlyingType =
5448 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5449 }
5450
5451 llvm::FoldingSetNodeID ID;
5452 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5453
5454 llvm::FoldingSetInsertToken Token;
5455 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5456 return QualType(T, 0);
5457
5458 assert(!UnderlyingType.hasLocalQualifiers());
5459
5460 assert(
5462 UnderlyingType));
5463
5464 void *Mem =
5465 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5466 alignof(UsingType));
5467 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5468 Types.push_back(T);
5469 UsingTypes.insert(T, Token);
5470 return QualType(T, 0);
5471}
5472
5473TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5474 NestedNameSpecifier Qualifier,
5475 const TagDecl *TD, bool OwnsTag,
5476 bool IsInjected,
5477 const Type *CanonicalType,
5478 bool WithFoldingSetNode) const {
5479 auto [TC, Size] = [&] {
5480 switch (TD->getDeclKind()) {
5481 case Decl::Enum:
5482 static_assert(alignof(EnumType) == alignof(TagType));
5483 return std::make_tuple(Type::Enum, sizeof(EnumType));
5484 case Decl::ClassTemplatePartialSpecialization:
5485 case Decl::ClassTemplateSpecialization:
5486 case Decl::CXXRecord:
5487 static_assert(alignof(RecordType) == alignof(TagType));
5488 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5489 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5490 return std::make_tuple(Type::InjectedClassName,
5491 sizeof(InjectedClassNameType));
5492 [[fallthrough]];
5493 case Decl::Record:
5494 return std::make_tuple(Type::Record, sizeof(RecordType));
5495 default:
5496 llvm_unreachable("unexpected decl kind");
5497 }
5498 }();
5499
5500 if (Qualifier) {
5501 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5502 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5503 sizeof(NestedNameSpecifier);
5504 }
5505 void *Mem;
5506 if (WithFoldingSetNode) {
5507 // FIXME: It would be more profitable to tail allocate the folding set node
5508 // from the type, instead of the other way around, due to the greater
5509 // alignment requirements of the type. But this makes it harder to deal with
5510 // the different type node sizes. This would require either uniquing from
5511 // different folding sets, or having the folding setaccept a
5512 // contextual parameter which is not fixed at construction.
5513 Mem = Allocate(
5514 sizeof(TagTypeFoldingSetPlaceholder) +
5515 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5516 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5517 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5518 Mem = T->getTagType();
5519 } else {
5520 Mem = Allocate(Size, alignof(TagType));
5521 }
5522
5523 auto *T = [&, TC = TC]() -> TagType * {
5524 switch (TC) {
5525 case Type::Enum: {
5526 assert(isa<EnumDecl>(TD));
5527 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5528 IsInjected, CanonicalType);
5529 assert(reinterpret_cast<void *>(T) ==
5530 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5531 "TagType must be the first base of EnumType");
5532 return T;
5533 }
5534 case Type::Record: {
5535 assert(isa<RecordDecl>(TD));
5536 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5537 IsInjected, CanonicalType);
5538 assert(reinterpret_cast<void *>(T) ==
5539 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5540 "TagType must be the first base of RecordType");
5541 return T;
5542 }
5543 case Type::InjectedClassName: {
5544 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5545 IsInjected, CanonicalType);
5546 assert(reinterpret_cast<void *>(T) ==
5547 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5548 "TagType must be the first base of InjectedClassNameType");
5549 return T;
5550 }
5551 default:
5552 llvm_unreachable("unexpected type class");
5553 }
5554 }();
5555 assert(T->getKeyword() == Keyword);
5556 assert(T->getQualifier() == Qualifier);
5557 assert(T->getDecl() == TD);
5558 assert(T->isInjected() == IsInjected);
5559 assert(T->isTagOwned() == OwnsTag);
5560 assert((T->isCanonicalUnqualified()
5561 ? QualType()
5562 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5563 Types.push_back(T);
5564 return T;
5565}
5566
5567static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5568 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5569 RD && RD->isInjectedClassName())
5570 return cast<TagDecl>(RD->getDeclContext());
5571 return TD;
5572}
5573
5576 if (TD->TypeForDecl)
5577 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5578
5579 const Type *CanonicalType = getTagTypeInternal(
5581 /*Qualifier=*/std::nullopt, TD,
5582 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5583 /*WithFoldingSetNode=*/false);
5584 TD->TypeForDecl = CanonicalType;
5585 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5586}
5587
5589 NestedNameSpecifier Qualifier,
5590 const TagDecl *TD, bool OwnsTag) const {
5591
5592 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5593 bool IsInjected = TD != NonInjectedTD;
5594
5595 ElaboratedTypeKeyword PreferredKeyword =
5598 NonInjectedTD->getTagKind());
5599
5600 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5601 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5602 return QualType(T, 0);
5603
5604 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5605 const Type *T =
5606 getTagTypeInternal(Keyword,
5607 /*Qualifier=*/std::nullopt, NonInjectedTD,
5608 /*OwnsTag=*/false, IsInjected, CanonicalType,
5609 /*WithFoldingSetNode=*/false);
5610 TD->TypeForDecl = T;
5611 return QualType(T, 0);
5612 }
5613
5614 llvm::FoldingSetNodeID ID;
5615 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5616 OwnsTag, IsInjected);
5617
5618 llvm::FoldingSetInsertToken Token;
5619 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5620 return QualType(T->getTagType(), 0);
5621
5622 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5623 TagType *T =
5624 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5625 CanonicalType, /*WithFoldingSetNode=*/true);
5626 TagTypes.insert(TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5627 return QualType(T, 0);
5628}
5629
5630bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5631 unsigned NumPositiveBits,
5632 QualType &BestType,
5633 QualType &BestPromotionType) {
5634 unsigned IntWidth = Target->getIntWidth();
5635 unsigned CharWidth = Target->getCharWidth();
5636 unsigned ShortWidth = Target->getShortWidth();
5637 bool EnumTooLarge = false;
5638 unsigned BestWidth;
5639 if (NumNegativeBits) {
5640 // If there is a negative value, figure out the smallest integer type (of
5641 // int/long/longlong) that fits.
5642 // If it's packed, check also if it fits a char or a short.
5643 if (IsPacked && NumNegativeBits <= CharWidth &&
5644 NumPositiveBits < CharWidth) {
5645 BestType = SignedCharTy;
5646 BestWidth = CharWidth;
5647 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5648 NumPositiveBits < ShortWidth) {
5649 BestType = ShortTy;
5650 BestWidth = ShortWidth;
5651 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5652 BestType = IntTy;
5653 BestWidth = IntWidth;
5654 } else {
5655 BestWidth = Target->getLongWidth();
5656
5657 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5658 BestType = LongTy;
5659 } else {
5660 BestWidth = Target->getLongLongWidth();
5661
5662 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5663 EnumTooLarge = true;
5664 BestType = LongLongTy;
5665 }
5666 }
5667 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5668 } else {
5669 // If there is no negative value, figure out the smallest type that fits
5670 // all of the enumerator values.
5671 // If it's packed, check also if it fits a char or a short.
5672 if (IsPacked && NumPositiveBits <= CharWidth) {
5673 BestType = UnsignedCharTy;
5674 BestPromotionType = IntTy;
5675 BestWidth = CharWidth;
5676 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5677 BestType = UnsignedShortTy;
5678 BestPromotionType = IntTy;
5679 BestWidth = ShortWidth;
5680 } else if (NumPositiveBits <= IntWidth) {
5681 BestType = UnsignedIntTy;
5682 BestWidth = IntWidth;
5683 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5685 : IntTy;
5686 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5687 BestType = UnsignedLongTy;
5688 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5690 : LongTy;
5691 } else {
5692 BestWidth = Target->getLongLongWidth();
5693 if (NumPositiveBits > BestWidth) {
5694 // This can happen with bit-precise integer types, but those are not
5695 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5696 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5697 // a 128-bit integer, we should consider doing the same.
5698 EnumTooLarge = true;
5699 }
5700 BestType = UnsignedLongLongTy;
5701 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5703 : LongLongTy;
5704 }
5705 }
5706 return EnumTooLarge;
5707}
5708
5710 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5711 "Integral type required!");
5712 unsigned BitWidth = getIntWidth(T);
5713
5714 if (Value.isUnsigned() || Value.isNonNegative()) {
5715 if (T->isSignedIntegerOrEnumerationType())
5716 --BitWidth;
5717 return Value.getActiveBits() <= BitWidth;
5718 }
5719 return Value.getSignificantBits() <= BitWidth;
5720}
5721
5722UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5724 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5725 const Type *CanonicalType) const {
5726 void *Mem = Allocate(
5727 UnresolvedUsingType::totalSizeToAlloc<
5729 !!Token, !!Qualifier),
5730 alignof(UnresolvedUsingType));
5731 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5732 if (Token) {
5733 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5735 UnresolvedUsingTypes.insert(Placeholder, Token);
5736 }
5737 Types.push_back(T);
5738 return T;
5739}
5740
5742 const UnresolvedUsingTypenameDecl *D) const {
5743 D = D->getCanonicalDecl();
5744 if (D->TypeForDecl)
5745 return D->TypeForDecl->getCanonicalTypeUnqualified();
5746
5747 const Type *CanonicalType =
5748 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5749 /*Qualifier=*/std::nullopt, D,
5750 /*Token=*/{}, /*CanonicalType=*/nullptr);
5751 D->TypeForDecl = CanonicalType;
5752 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5753}
5754
5757 NestedNameSpecifier Qualifier,
5758 const UnresolvedUsingTypenameDecl *D) const {
5759 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5760 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5761 return QualType(T, 0);
5762
5763 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5764 const Type *T =
5765 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5766 /*Qualifier=*/std::nullopt, D,
5767 /*Token=*/{}, CanonicalType);
5768 D->TypeForDecl = T;
5769 return QualType(T, 0);
5770 }
5771
5772 llvm::FoldingSetNodeID ID;
5773 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5774
5775 llvm::FoldingSetInsertToken Token;
5777 UnresolvedUsingTypes.lookup(ID, Token))
5778 return QualType(Placeholder->getType(), 0);
5779 assert(Token);
5780
5781 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5782 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5783 CanonicalType);
5784 return QualType(T, 0);
5785}
5786
5788 QualType modifiedType,
5789 QualType equivalentType,
5790 const Attr *attr) const {
5791 llvm::FoldingSetNodeID id;
5792 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5793 attr);
5794
5795 llvm::FoldingSetInsertToken Token;
5796 AttributedType *type = AttributedTypes.lookup(id, Token);
5797 if (type) return QualType(type, 0);
5798
5799 assert(!attr || attr->getKind() == attrKind);
5800
5801 QualType canon = getCanonicalType(equivalentType);
5802 type = new (*this, alignof(AttributedType))
5803 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5804
5805 Types.push_back(type);
5806 AttributedTypes.insert(type, Token);
5807
5808 return QualType(type, 0);
5809}
5810
5812 QualType equivalentType) const {
5813 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5814}
5815
5817 QualType modifiedType,
5818 QualType equivalentType) const {
5819 switch (nullability) {
5821 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5822
5824 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5825
5827 return getAttributedType(attr::TypeNullableResult, modifiedType,
5828 equivalentType);
5829
5831 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5832 equivalentType);
5833 }
5834
5835 llvm_unreachable("Unknown nullability kind");
5836}
5837
5838QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5839 QualType Wrapped) const {
5840 llvm::FoldingSetNodeID ID;
5841 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5842
5843 llvm::FoldingSetInsertToken Token;
5844 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5845 if (Ty)
5846 return QualType(Ty, 0);
5847
5848 QualType Canon = getCanonicalType(Wrapped);
5849 Ty = new (*this, alignof(BTFTagAttributedType))
5850 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5851
5852 Types.push_back(Ty);
5853 BTFTagAttributedTypes.insert(Ty, Token);
5854
5855 return QualType(Ty, 0);
5856}
5857
5859 QualType Underlying) const {
5860 const IdentifierInfo *II = Attr->getBehaviorKind();
5861 StringRef IdentName = II->getName();
5862 OverflowBehaviorType::OverflowBehaviorKind Kind;
5863 if (IdentName == "wrap") {
5864 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5865 } else if (IdentName == "trap") {
5866 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5867 } else {
5868 return Underlying;
5869 }
5870
5871 return getOverflowBehaviorType(Kind, Underlying);
5872}
5873
5875 OverflowBehaviorType::OverflowBehaviorKind Kind,
5876 QualType Underlying) const {
5877 assert(!Underlying->isOverflowBehaviorType() &&
5878 "Cannot have underlying types that are themselves OBTs");
5879
5880 llvm::FoldingSetInsertToken Token;
5881 if (OverflowBehaviorType *OBT =
5882 OverflowBehaviorTypes.lookup({Underlying, Kind}, Token)) {
5883 return QualType(OBT, 0);
5884 }
5885
5886 QualType Canonical;
5887 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5888 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5889 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5890 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5891 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5892 "Shouldn't be in the map");
5893 }
5894
5895 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5896 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5897
5898 Types.push_back(Ty);
5899 OverflowBehaviorTypes.insert(Ty, Token);
5900 return QualType(Ty, 0);
5901}
5902
5904 QualType Wrapped, QualType Contained,
5905 const HLSLAttributedResourceType::Attributes &Attrs) {
5906
5907 llvm::FoldingSetNodeID ID;
5908 HLSLAttributedResourceType::Profile(ID, *this, Wrapped, Contained, Attrs);
5909
5910 llvm::FoldingSetInsertToken Token;
5911 HLSLAttributedResourceType *Ty =
5912 HLSLAttributedResourceTypes.lookup(ID, Token);
5913 if (Ty)
5914 return QualType(Ty, 0);
5915
5916 Ty = new (*this, alignof(HLSLAttributedResourceType))
5917 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5918
5919 Types.push_back(Ty);
5920 HLSLAttributedResourceTypes.insert(Ty, Token);
5921
5922 return QualType(Ty, 0);
5923}
5924
5925QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5926 uint32_t Alignment,
5927 ArrayRef<SpirvOperand> Operands) {
5928 llvm::FoldingSetNodeID ID;
5929 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5930
5931 llvm::FoldingSetInsertToken Token;
5932 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5933 if (Ty)
5934 return QualType(Ty, 0);
5935
5936 void *Mem = Allocate(
5937 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5938 alignof(HLSLInlineSpirvType));
5939
5940 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5941
5942 Types.push_back(Ty);
5943 HLSLInlineSpirvTypes.insert(Ty, Token);
5944
5945 return QualType(Ty, 0);
5946}
5947
5948/// Retrieve a substitution-result type.
5950 Decl *AssociatedDecl,
5951 unsigned Index,
5953 bool Final) const {
5954 auto Key =
5955 std::make_tuple(Replacement, AssociatedDecl, Index,
5956 PackIndex.toInternalRepresentation(), unsigned(Final));
5957 llvm::FoldingSetInsertToken Token;
5958 SubstTemplateTypeParmType *SubstParm =
5959 SubstTemplateTypeParmTypes.lookup(Key, Token);
5960
5961 if (!SubstParm) {
5962 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5963 !Replacement.isCanonical()),
5964 alignof(SubstTemplateTypeParmType));
5965 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5966 Index, PackIndex, Final);
5967 Types.push_back(SubstParm);
5968 SubstTemplateTypeParmTypes.insert(SubstParm, Token);
5969 }
5970
5971 return QualType(SubstParm, 0);
5972}
5973
5976 unsigned Index, bool Final,
5977 const TemplateArgument &ArgPack) {
5978#ifndef NDEBUG
5979 for (const auto &P : ArgPack.pack_elements())
5980 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5981#endif
5982
5983 llvm::FoldingSetNodeID ID;
5984 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5985 ArgPack);
5986 llvm::FoldingSetInsertToken Token;
5987 if (SubstTemplateTypeParmPackType *SubstParm =
5988 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
5989 return QualType(SubstParm, 0);
5990
5991 QualType Canon;
5992 {
5993 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5994 if (!AssociatedDecl->isCanonicalDecl() ||
5995 !CanonArgPack.structurallyEquals(ArgPack)) {
5997 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5998 [[maybe_unused]] const auto *Nothing =
5999 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6000 assert(!Nothing);
6001 }
6002 }
6003
6004 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6005 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6006 ArgPack);
6007 Types.push_back(SubstParm);
6008 SubstTemplateTypeParmPackTypes.insert(SubstParm, Token);
6009 return QualType(SubstParm, 0);
6010}
6011
6014 assert(llvm::all_of(ArgPack.pack_elements(),
6015 [](const auto &P) {
6016 return P.getKind() == TemplateArgument::Type;
6017 }) &&
6018 "Pack contains a non-type");
6019
6020 llvm::FoldingSetNodeID ID;
6021 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6022
6023 llvm::FoldingSetInsertToken Token;
6024 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6025 return QualType(T, 0);
6026
6027 QualType Canon;
6028 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6029 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6030 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6031 // Refresh Token, in case the recursive call above caused rehashing,
6032 // which would invalidate the bucket pointer.
6033 [[maybe_unused]] const auto *Nothing =
6034 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6035 assert(!Nothing);
6036 }
6037
6038 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6039 SubstBuiltinTemplatePackType(Canon, ArgPack);
6040 Types.push_back(PackType);
6041 SubstBuiltinTemplatePackTypes.insert(PackType, Token);
6042 return QualType(PackType, 0);
6043}
6044
6045/// Retrieve the template type parameter type for a template
6046/// parameter or parameter pack with the given depth, index, and (optionally)
6047/// name.
6049ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6050 TemplateTypeParmDecl *TTPDecl) const {
6051 assert(Depth >= 0 && "Depth must be non-negative");
6052 assert(Index >= 0 && "Index must be non-negative");
6053
6054 auto Key = std::make_tuple(unsigned(Depth), unsigned(Index),
6055 unsigned(ParameterPack), TTPDecl);
6056 llvm::FoldingSetInsertToken Token;
6057 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6058
6059 if (TypeParm)
6060 return QualType(TypeParm, 0);
6061
6062 if (TTPDecl) {
6063 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6064 TypeParm = new (*this, alignof(TemplateTypeParmType))
6065 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6066 } else
6067 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6068 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6069
6070 Types.push_back(TypeParm);
6071 TemplateTypeParmTypes.insert(TypeParm, Token);
6072
6073 return QualType(TypeParm, 0);
6074}
6075
6078 switch (Keyword) {
6079 // These are just themselves.
6085 return Keyword;
6086
6087 // These are equivalent.
6090
6091 // These are functionally equivalent, so relying on their equivalence is
6092 // IFNDR. By making them equivalent, we disallow overloading, which at least
6093 // can produce a diagnostic.
6096 }
6097 llvm_unreachable("unexpected keyword kind");
6098}
6099
6101 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6102 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6103 TemplateName Name, SourceLocation NameLoc,
6104 const TemplateArgumentListInfo &SpecifiedArgs,
6105 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6107 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6108
6111 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6112 SpecifiedArgs);
6113 return TSI;
6114}
6115
6118 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6119 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6120 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6121 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6122 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6123 SpecifiedArgVec.push_back(Arg.getArgument());
6124
6125 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6126 CanonicalArgs, Underlying);
6127}
6128
6129[[maybe_unused]] static bool
6131 for (const TemplateArgument &Arg : Args)
6132 if (Arg.isPackExpansion())
6133 return true;
6134 return false;
6135}
6136
6139 ArrayRef<TemplateArgument> Args) const {
6140 assert(Template ==
6141 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6143 Template.getAsDependentTemplateName()));
6144#ifndef NDEBUG
6145 for (const auto &Arg : Args)
6146 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6147#endif
6148
6149 llvm::FoldingSetNodeID ID;
6150 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6151 *this);
6152 llvm::FoldingSetInsertToken Token;
6153 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6154 return QualType(T, 0);
6155
6156 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6157 sizeof(TemplateArgument) * Args.size(),
6158 alignof(TemplateSpecializationType));
6159 auto *Spec =
6160 new (Mem) TemplateSpecializationType(Keyword, Template,
6161 /*IsAlias=*/false, Args, QualType());
6162 assert(Spec->isDependentType() &&
6163 "canonical template specialization must be dependent");
6164 Types.push_back(Spec);
6165 TemplateSpecializationTypes.insert(Spec, Token);
6166 return QualType(Spec, 0);
6167}
6168
6171 ArrayRef<TemplateArgument> SpecifiedArgs,
6172 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6173 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6174 bool IsTypeAlias = TD && TD->isTypeAlias();
6175 if (Underlying.isNull()) {
6176 TemplateName CanonTemplate =
6177 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6178 ElaboratedTypeKeyword CanonKeyword =
6179 CanonTemplate.getAsDependentTemplateName()
6182 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6184 if (CanonicalArgs.empty()) {
6185 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6186 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6187 CanonicalArgs = CanonArgsVec;
6188 } else {
6189 NonCanonical |= !llvm::equal(
6190 SpecifiedArgs, CanonicalArgs,
6191 [](const TemplateArgument &A, const TemplateArgument &B) {
6192 return A.structurallyEquals(B);
6193 });
6194 }
6195
6196 // We can get here with an alias template when the specialization
6197 // contains a pack expansion that does not match up with a parameter
6198 // pack, or a builtin template which cannot be resolved due to dependency.
6199 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6200 hasAnyPackExpansions(CanonicalArgs)) &&
6201 "Caller must compute aliased type");
6202 IsTypeAlias = false;
6203
6205 CanonKeyword, CanonTemplate, CanonicalArgs);
6206 if (!NonCanonical)
6207 return Underlying;
6208 }
6209 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6210 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6211 (IsTypeAlias ? sizeof(QualType) : 0),
6212 alignof(TemplateSpecializationType));
6213 auto *Spec = new (Mem) TemplateSpecializationType(
6214 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6215 Types.push_back(Spec);
6216 return QualType(Spec, 0);
6217}
6218
6221 llvm::FoldingSetInsertToken Token;
6222 ParenType *T = ParenTypes.lookup(InnerType, Token);
6223 if (T)
6224 return QualType(T, 0);
6225
6226 QualType Canon = InnerType;
6227 if (!Canon.isCanonical()) {
6228 Canon = getCanonicalType(InnerType);
6229 assert(!ParenTypes.lookup(InnerType, Token) &&
6230 "Paren canonical type broken");
6231 }
6232
6233 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6234 Types.push_back(T);
6235 ParenTypes.insert(T, Token);
6236 return QualType(T, 0);
6237}
6238
6241 const IdentifierInfo *MacroII) const {
6242 QualType Canon = UnderlyingTy;
6243 if (!Canon.isCanonical())
6244 Canon = getCanonicalType(UnderlyingTy);
6245
6246 auto *newType = new (*this, alignof(MacroQualifiedType))
6247 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6248 Types.push_back(newType);
6249 return QualType(newType, 0);
6250}
6251
6254 const IdentifierInfo *Name) const {
6255 llvm::FoldingSetNodeID ID;
6256 DependentNameType::Profile(ID, Keyword, NNS, Name);
6257
6258 llvm::FoldingSetInsertToken Token;
6259 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6260 return QualType(T, 0);
6261
6262 ElaboratedTypeKeyword CanonKeyword =
6264 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6265
6266 QualType Canon;
6267 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6268 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6269 [[maybe_unused]] DependentNameType *T =
6270 DependentNameTypes.lookup(ID, Token);
6271 assert(!T && "broken canonicalization");
6272 assert(Canon.isCanonical());
6273 }
6274
6275 DependentNameType *T = new (*this, alignof(DependentNameType))
6276 DependentNameType(Keyword, NNS, Name, Canon);
6277 Types.push_back(T);
6278 DependentNameTypes.insert(T, Token);
6279 return QualType(T, 0);
6280}
6281
6283 TemplateArgument Arg;
6284 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6286 if (TTP->isParameterPack())
6287 ArgType = getPackExpansionType(ArgType, std::nullopt);
6288
6290 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6291 QualType T =
6292 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6293 // For class NTTPs, ensure we include the 'const' so the type matches that
6294 // of a real template argument.
6295 // FIXME: It would be more faithful to model this as something like an
6296 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6298 if (NTTP->getType()->isReferenceType()) {
6299 // As in Sema::BuildDeclarationNameExpr, a parameter of reference
6300 // type, even an rvalue reference, is an lvalue.
6301 VK = VK_LValue;
6302 } else if (T->isRecordType()) {
6303 // C++ [temp.param]p8: An id-expression naming a non-type
6304 // template-parameter of class type T denotes a static storage duration
6305 // object of type const T.
6306 T.addConst();
6307 VK = VK_LValue;
6308 }
6309 Expr *E = new (*this)
6310 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6311 T, VK, NTTP->getLocation());
6312
6313 if (NTTP->isParameterPack())
6314 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6315 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6316 } else {
6317 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6319 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6320 TemplateName(TTP));
6321 if (TTP->isParameterPack())
6322 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6323 else
6324 Arg = TemplateArgument(Name);
6325 }
6326
6327 if (Param->isTemplateParameterPack())
6328 Arg =
6329 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6330
6331 return Arg;
6332}
6333
6335 UnsignedOrNone NumExpansions,
6336 bool ExpectPackInType) const {
6337 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6338 "Pack expansions must expand one or more parameter packs");
6339
6340 auto Key = std::make_pair(Pattern, NumExpansions.toInternalRepresentation());
6341
6342 llvm::FoldingSetInsertToken Token;
6343 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6344 if (T)
6345 return QualType(T, 0);
6346
6347 QualType Canon;
6348 if (!Pattern.isCanonical()) {
6349 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6350 /*ExpectPackInType=*/false);
6351
6352 // Find the insert position again, in case we inserted an element into
6353 // PackExpansionTypes and invalidated our insert position.
6354 PackExpansionTypes.lookup(Key, Token);
6355 }
6356
6357 T = new (*this, alignof(PackExpansionType))
6358 PackExpansionType(Pattern, Canon, NumExpansions);
6359 Types.push_back(T);
6360 PackExpansionTypes.insert(T, Token);
6361 return QualType(T, 0);
6362}
6363
6364/// CmpProtocolNames - Comparison predicate for sorting protocols
6365/// alphabetically.
6366static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6367 ObjCProtocolDecl *const *RHS) {
6368 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6369}
6370
6372 if (Protocols.empty()) return true;
6373
6374 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6375 return false;
6376
6377 for (unsigned i = 1; i != Protocols.size(); ++i)
6378 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6379 Protocols[i]->getCanonicalDecl() != Protocols[i])
6380 return false;
6381 return true;
6382}
6383
6384static void
6386 // Sort protocols, keyed by name.
6387 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6388
6389 // Canonicalize.
6390 for (ObjCProtocolDecl *&P : Protocols)
6391 P = P->getCanonicalDecl();
6392
6393 // Remove duplicates.
6394 auto ProtocolsEnd = llvm::unique(Protocols);
6395 Protocols.erase(ProtocolsEnd, Protocols.end());
6396}
6397
6399 ObjCProtocolDecl * const *Protocols,
6400 unsigned NumProtocols) const {
6401 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6402 /*isKindOf=*/false);
6403}
6404
6406 QualType baseType,
6407 ArrayRef<QualType> typeArgs,
6409 bool isKindOf) const {
6410 // If the base type is an interface and there aren't any protocols or
6411 // type arguments to add, then the interface type will do just fine.
6412 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6413 isa<ObjCInterfaceType>(baseType))
6414 return baseType;
6415
6416 // Look in the folding set for an existing type.
6417 llvm::FoldingSetNodeID ID;
6418 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6419 llvm::FoldingSetInsertToken Token;
6420 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6421 return QualType(QT, 0);
6422
6423 // Determine the type arguments to be used for canonicalization,
6424 // which may be explicitly specified here or written on the base
6425 // type.
6426 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6427 if (effectiveTypeArgs.empty()) {
6428 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6429 effectiveTypeArgs = baseObject->getTypeArgs();
6430 }
6431
6432 // Build the canonical type, which has the canonical base type and a
6433 // sorted-and-uniqued list of protocols and the type arguments
6434 // canonicalized.
6435 QualType canonical;
6436 bool typeArgsAreCanonical = llvm::all_of(
6437 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6438 bool protocolsSorted = areSortedAndUniqued(protocols);
6439 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6440 // Determine the canonical type arguments.
6441 ArrayRef<QualType> canonTypeArgs;
6442 SmallVector<QualType, 4> canonTypeArgsVec;
6443 if (!typeArgsAreCanonical) {
6444 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6445 for (auto typeArg : effectiveTypeArgs)
6446 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6447 canonTypeArgs = canonTypeArgsVec;
6448 } else {
6449 canonTypeArgs = effectiveTypeArgs;
6450 }
6451
6452 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6453 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6454 if (!protocolsSorted) {
6455 canonProtocolsVec.append(protocols.begin(), protocols.end());
6456 SortAndUniqueProtocols(canonProtocolsVec);
6457 canonProtocols = canonProtocolsVec;
6458 } else {
6459 canonProtocols = protocols;
6460 }
6461
6462 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6463 canonProtocols, isKindOf);
6464
6465 // Regenerate Token.
6466 ObjCObjectTypes.lookup(ID, Token);
6467 }
6468
6469 unsigned size = sizeof(ObjCObjectTypeImpl);
6470 size += typeArgs.size() * sizeof(QualType);
6471 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6472 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6473 auto *T =
6474 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6475 isKindOf);
6476
6477 Types.push_back(T);
6478 ObjCObjectTypes.insert(T, Token);
6479 return QualType(T, 0);
6480}
6481
6482/// Apply Objective-C protocol qualifiers to the given type.
6483/// If this is for the canonical type of a type parameter, we can apply
6484/// protocol qualifiers on the ObjCObjectPointerType.
6487 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6488 bool allowOnPointerType) const {
6489 hasError = false;
6490
6491 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6492 return getObjCTypeParamType(objT->getDecl(), protocols);
6493 }
6494
6495 // Apply protocol qualifiers to ObjCObjectPointerType.
6496 if (allowOnPointerType) {
6497 if (const auto *objPtr =
6498 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6499 const ObjCObjectType *objT = objPtr->getObjectType();
6500 // Merge protocol lists and construct ObjCObjectType.
6502 protocolsVec.append(objT->qual_begin(),
6503 objT->qual_end());
6504 protocolsVec.append(protocols.begin(), protocols.end());
6505 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6507 objT->getBaseType(),
6508 objT->getTypeArgsAsWritten(),
6509 protocols,
6510 objT->isKindOfTypeAsWritten());
6512 }
6513 }
6514
6515 // Apply protocol qualifiers to ObjCObjectType.
6516 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6517 // FIXME: Check for protocols to which the class type is already
6518 // known to conform.
6519
6520 return getObjCObjectType(objT->getBaseType(),
6521 objT->getTypeArgsAsWritten(),
6522 protocols,
6523 objT->isKindOfTypeAsWritten());
6524 }
6525
6526 // If the canonical type is ObjCObjectType, ...
6527 if (type->isObjCObjectType()) {
6528 // Silently overwrite any existing protocol qualifiers.
6529 // TODO: determine whether that's the right thing to do.
6530
6531 // FIXME: Check for protocols to which the class type is already
6532 // known to conform.
6533 return getObjCObjectType(type, {}, protocols, false);
6534 }
6535
6536 // id<protocol-list>
6537 if (type->isObjCIdType()) {
6538 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6539 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6540 objPtr->isKindOfType());
6542 }
6543
6544 // Class<protocol-list>
6545 if (type->isObjCClassType()) {
6546 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6547 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6548 objPtr->isKindOfType());
6550 }
6551
6552 hasError = true;
6553 return type;
6554}
6555
6558 ArrayRef<ObjCProtocolDecl *> protocols) const {
6559 // We canonicalize to the underlying type.
6560 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6561 if (!protocols.empty()) {
6562 // Apply the protocol qualifers.
6563 bool hasError;
6565 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6566 assert(!hasError && "Error when apply protocol qualifier to bound type");
6567 }
6568
6569 // Key on the canonical type the node is constructed with, which is what
6570 // Profile() reports; the decl's underlying type can be updated later.
6571 auto Key = std::make_tuple(Decl, Canonical, protocols);
6572 llvm::FoldingSetInsertToken Token;
6573 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6574 return QualType(TypeParam, 0);
6575
6576 unsigned size = sizeof(ObjCTypeParamType);
6577 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6578 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6579 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6580
6581 Types.push_back(newType);
6582 ObjCTypeParamTypes.insert(newType, Token);
6583 return QualType(newType, 0);
6584}
6585
6587 ObjCTypeParamDecl *New) const {
6588 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6589 // Update TypeForDecl after updating TypeSourceInfo.
6590 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6592 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6593 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6594 New->TypeForDecl = UpdatedTy.getTypePtr();
6595}
6596
6597/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6598/// protocol list adopt all protocols in QT's qualified-id protocol
6599/// list.
6601 ObjCInterfaceDecl *IC) {
6602 if (!QT->isObjCQualifiedIdType())
6603 return false;
6604
6605 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6606 // If both the right and left sides have qualifiers.
6607 for (auto *Proto : OPT->quals()) {
6608 if (!IC->ClassImplementsProtocol(Proto, false))
6609 return false;
6610 }
6611 return true;
6612 }
6613 return false;
6614}
6615
6616/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6617/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6618/// of protocols.
6620 ObjCInterfaceDecl *IDecl) {
6621 if (!QT->isObjCQualifiedIdType())
6622 return false;
6623 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6624 if (!OPT)
6625 return false;
6626 if (!IDecl->hasDefinition())
6627 return false;
6629 CollectInheritedProtocols(IDecl, InheritedProtocols);
6630 if (InheritedProtocols.empty())
6631 return false;
6632 // Check that if every protocol in list of id<plist> conforms to a protocol
6633 // of IDecl's, then bridge casting is ok.
6634 bool Conforms = false;
6635 for (auto *Proto : OPT->quals()) {
6636 Conforms = false;
6637 for (auto *PI : InheritedProtocols) {
6638 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6639 Conforms = true;
6640 break;
6641 }
6642 }
6643 if (!Conforms)
6644 break;
6645 }
6646 if (Conforms)
6647 return true;
6648
6649 for (auto *PI : InheritedProtocols) {
6650 // If both the right and left sides have qualifiers.
6651 bool Adopts = false;
6652 for (auto *Proto : OPT->quals()) {
6653 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6654 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6655 break;
6656 }
6657 if (!Adopts)
6658 return false;
6659 }
6660 return true;
6661}
6662
6663/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6664/// the given object type.
6666 llvm::FoldingSetInsertToken Token;
6667 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(ObjectT, Token))
6668 return QualType(QT, 0);
6669
6670 // Find the canonical object type.
6671 QualType Canonical;
6672 if (!ObjectT.isCanonical())
6673 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6674
6675 // No match.
6676 void *Mem =
6678 auto *QType =
6679 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6680
6681 Types.push_back(QType);
6682 ObjCObjectPointerTypes.insert(QType, Token);
6683 return QualType(QType, 0);
6684}
6685
6686/// getObjCInterfaceType - Return the unique reference to the type for the
6687/// specified ObjC interface decl. The list of protocols is optional.
6689 ObjCInterfaceDecl *PrevDecl) const {
6690 if (Decl->TypeForDecl)
6691 return QualType(Decl->TypeForDecl, 0);
6692
6693 if (PrevDecl) {
6694 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6695 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6696 return QualType(PrevDecl->TypeForDecl, 0);
6697 }
6698
6699 // Prefer the definition, if there is one.
6700 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6701 Decl = Def;
6702
6703 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6704 auto *T = new (Mem) ObjCInterfaceType(Decl);
6705 Decl->TypeForDecl = T;
6706 Types.push_back(T);
6707 return QualType(T, 0);
6708}
6709
6710/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6711/// TypeOfExprType AST's (since expression's are never shared). For example,
6712/// multiple declarations that refer to "typeof(x)" all contain different
6713/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6714/// on canonical type's (which are always unique).
6716 TypeOfExprType *toe;
6717 if (tofExpr->isTypeDependent()) {
6718 llvm::FoldingSetNodeID ID;
6719 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6720 Kind == TypeOfKind::Unqualified);
6721
6722 llvm::FoldingSetInsertToken Token;
6723 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6724 if (Canon) {
6725 // We already have a "canonical" version of an identical, dependent
6726 // typeof(expr) type. Use that as our canonical type.
6727 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6728 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6729 } else {
6730 // Build a new, canonical typeof(expr) type.
6731 Canon = new (*this, alignof(DependentTypeOfExprType))
6732 DependentTypeOfExprType(*this, tofExpr, Kind);
6733 DependentTypeOfExprTypes.insert(Canon, Token);
6734 toe = Canon;
6735 }
6736 } else {
6737 QualType Canonical = getCanonicalType(tofExpr->getType());
6738 toe = new (*this, alignof(TypeOfExprType))
6739 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6740 }
6741 Types.push_back(toe);
6742 return QualType(toe, 0);
6743}
6744
6745/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6746/// TypeOfType nodes. The only motivation to unique these nodes would be
6747/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6748/// an issue. This doesn't affect the type checker, since it operates
6749/// on canonical types (which are always unique).
6751 QualType Canonical = getCanonicalType(tofType);
6752 auto *tot = new (*this, alignof(TypeOfType))
6753 TypeOfType(*this, tofType, Canonical, Kind);
6754 Types.push_back(tot);
6755 return QualType(tot, 0);
6756}
6757
6758/// getReferenceQualifiedType - Given an expr, will return the type for
6759/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6760/// and class member access into account.
6762 // C++11 [dcl.type.simple]p4:
6763 // [...]
6764 QualType T = E->getType();
6765 switch (E->getValueKind()) {
6766 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6767 // type of e;
6768 case VK_XValue:
6769 return getRValueReferenceType(T);
6770 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6771 // type of e;
6772 case VK_LValue:
6773 return getLValueReferenceType(T);
6774 // - otherwise, decltype(e) is the type of e.
6775 case VK_PRValue:
6776 return T;
6777 }
6778 llvm_unreachable("Unknown value kind");
6779}
6780
6781/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6782/// nodes. This would never be helpful, since each such type has its own
6783/// expression, and would not give a significant memory saving, since there
6784/// is an Expr tree under each such type.
6786 // C++11 [temp.type]p2:
6787 // If an expression e involves a template parameter, decltype(e) denotes a
6788 // unique dependent type. Two such decltype-specifiers refer to the same
6789 // type only if their expressions are equivalent (14.5.6.1).
6790 QualType CanonType;
6791 if (!E->isInstantiationDependent()) {
6792 CanonType = getCanonicalType(UnderlyingType);
6793 } else if (!UnderlyingType.isNull()) {
6794 CanonType = getDecltypeType(E, QualType());
6795 } else {
6796 llvm::FoldingSetNodeID ID;
6797 DependentDecltypeType::Profile(ID, *this, E);
6798
6799 llvm::FoldingSetInsertToken Token;
6800 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6801 return QualType(Canon, 0);
6802
6803 // Build a new, canonical decltype(expr) type.
6804 auto *DT =
6805 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6806 DependentDecltypeTypes.insert(DT, Token);
6807 Types.push_back(DT);
6808 return QualType(DT, 0);
6809 }
6810 auto *DT = new (*this, alignof(DecltypeType))
6811 DecltypeType(E, UnderlyingType, CanonType);
6812 Types.push_back(DT);
6813 return QualType(DT, 0);
6814}
6815
6817 bool FullySubstituted,
6818 ArrayRef<QualType> Expansions,
6819 UnsignedOrNone Index) const {
6820 QualType Canonical;
6821 if (FullySubstituted && Index) {
6822 Canonical = getCanonicalType(Expansions[*Index]);
6823 } else {
6824 llvm::FoldingSetNodeID ID;
6825 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6826 FullySubstituted, Expansions);
6827 llvm::FoldingSetInsertToken Token;
6828 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6829 if (!Canon) {
6830 void *Mem = Allocate(
6831 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6833 Canon =
6834 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6835 IndexExpr, FullySubstituted, Expansions);
6836 DependentPackIndexingTypes.insert(Canon, Token);
6837 }
6838 Canonical = QualType(Canon, 0);
6839 }
6840
6841 void *Mem =
6842 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6844 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6845 FullySubstituted, Expansions);
6846 Types.push_back(T);
6847 return QualType(T, 0);
6848}
6849
6850/// getUnaryTransformationType - We don't unique these, since the memory
6851/// savings are minimal and these are rare.
6854 UnaryTransformType::UTTKind Kind) const {
6855 // Clear UnderlyingType for a dependent base before building the ID: that is
6856 // what the node is constructed with, and what Profile() reports.
6857 if (BaseType->isDependentType()) {
6858 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6859 UnderlyingType = QualType();
6860 }
6861
6862 auto Key = std::make_tuple(BaseType, UnderlyingType, Kind);
6863
6864 llvm::FoldingSetInsertToken Token;
6865 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6866 return QualType(UT, 0);
6867
6868 QualType CanonType;
6869 if (!BaseType->isDependentType()) {
6870 CanonType = UnderlyingType.getCanonicalType();
6871 } else {
6872 if (QualType CanonBase = BaseType.getCanonicalType();
6873 BaseType != CanonBase) {
6874 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6875 assert(CanonType.isCanonical());
6876 }
6877 }
6878
6879 auto *UT = new (*this, alignof(UnaryTransformType))
6880 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6881 UnaryTransformTypes.insert(UT, Token);
6882 Types.push_back(UT);
6883 return QualType(UT, 0);
6884}
6885
6886/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6887/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6888/// canonical deduced-but-dependent 'auto' type.
6892 TemplateName TypeConstraintConcept,
6893 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6895 TypeConstraintConcept.isNull()) {
6896 assert(DeducedAsType.isNull() && "");
6897 assert(TypeConstraintArgs.empty() && "");
6898 return getAutoDeductType();
6899 }
6900
6901 // Look in the folding set for an existing type.
6902 llvm::FoldingSetNodeID ID;
6903 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6904 TypeConstraintConcept, TypeConstraintArgs);
6905 if (auto const AT_iter = AutoTypes.find_as(ID); AT_iter != AutoTypes.end())
6906 return QualType(AT_iter->getSecond(), 0);
6907
6908 if (DK == DeducedKind::Deduced) {
6909 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6910 } else {
6911 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6912 if (!TypeConstraintConcept.isNull()) {
6913 bool AnyNonCanonArgs = false;
6914 TemplateName CanonicalConcept =
6915 getCanonicalTemplateName(TypeConstraintConcept);
6916 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6917 *this, TypeConstraintArgs, AnyNonCanonArgs);
6918 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6919 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6920 CanonicalConceptArgs);
6921 }
6922 }
6923
6924 void *Mem = Allocate(sizeof(AutoType) +
6925 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6926 alignof(AutoType));
6927 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6928 TypeConstraintConcept, TypeConstraintArgs);
6929#ifndef NDEBUG
6930 llvm::FoldingSetNodeID InsertedID;
6931 AT->Profile(InsertedID, *this);
6932 assert(InsertedID == ID && "ID does not match");
6933#endif
6934 Types.push_back(AT);
6935 AutoTypes.try_emplace(ID.Intern(BumpAlloc), AT);
6936 return QualType(AT, 0);
6937}
6938
6940 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6941
6942 // Remove a type-constraint from a top-level auto or decltype(auto).
6943 if (auto *AT = CanonT->getAs<AutoType>()) {
6944 if (!AT->isConstrained())
6945 return T;
6946 return getQualifiedType(
6947 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6948 T.getQualifiers());
6949 }
6950
6951 // FIXME: We only support constrained auto at the top level in the type of a
6952 // non-type template parameter at the moment. Once we lift that restriction,
6953 // we'll need to recursively build types containing auto here.
6954 assert(!CanonT->getContainedAutoType() ||
6955 !CanonT->getContainedAutoType()->isConstrained());
6956 return T;
6957}
6958
6959/// Return the uniqued reference to the deduced template specialization type
6960/// which has been deduced to the given type, or to the canonical undeduced
6961/// such type, or the canonical deduced-but-dependent such type.
6964 TemplateName Template) const {
6965 // Look in the folding set for an existing type.
6966 llvm::FoldingSetInsertToken Token;
6967 llvm::FoldingSetNodeID ID;
6968 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6969 Template);
6970 if (DeducedTemplateSpecializationType *DTST =
6971 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6972 return QualType(DTST, 0);
6973
6974 if (DK == DeducedKind::Deduced) {
6975 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6976 } else {
6977 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6978 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6979 // FIXME: Can this be formed from a DependentTemplateName, such that the
6980 // keyword should be part of the canonical type?
6982 Template != CanonTemplateName) {
6984 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6985 // Find the insertion position again.
6986 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6987 DeducedTemplateSpecializationTypes.lookup(ID, Token);
6988 assert(!DTST && "broken canonicalization");
6989 }
6990 }
6991
6992 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6993 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6994
6995#ifndef NDEBUG
6996 llvm::FoldingSetNodeID TempID;
6997 DTST->Profile(TempID);
6998 assert(ID == TempID && "ID does not match");
6999#endif
7000 Types.push_back(DTST);
7001 DeducedTemplateSpecializationTypes.insert(DTST, Token);
7002 return QualType(DTST, 0);
7003}
7004
7005/// getAtomicType - Return the uniqued reference to the atomic type for
7006/// the given value type.
7008 // Unique pointers, to guarantee there is only one pointer of a particular
7009 // structure.
7010 llvm::FoldingSetInsertToken Token;
7011 if (AtomicType *AT = AtomicTypes.lookup(T, Token))
7012 return QualType(AT, 0);
7013
7014 // If the atomic value type isn't canonical, this won't be a canonical type
7015 // either, so fill in the canonical type field.
7016 QualType Canonical;
7017 if (!T.isCanonical()) {
7018 Canonical = getAtomicType(getCanonicalType(T));
7019
7020 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7021 }
7022 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7023 Types.push_back(New);
7024 AtomicTypes.insert(New, Token);
7025 return QualType(New, 0);
7026}
7027
7028/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7030 if (AutoDeductTy.isNull())
7032 new (*this, alignof(AutoType))
7034 /*TypeConstraintConcept=*/TemplateName(),
7035 /*TypeConstraintArgs=*/{}),
7036 0);
7037 return AutoDeductTy;
7038}
7039
7040/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7042 if (AutoRRefDeductTy.isNull())
7044 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7045 return AutoRRefDeductTy;
7046}
7047
7048/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7049/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7050/// needs to agree with the definition in <stddef.h>.
7054
7056 return getFromTargetType(Target->getSizeType());
7057}
7058
7059/// Return the unique signed counterpart of the integer type
7060/// corresponding to size_t.
7064
7065/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7066/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7070
7071/// Return the unique unsigned counterpart of "ptrdiff_t"
7072/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7073/// in the definition of %tu format specifier.
7075 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7076}
7077
7078/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7080 return getFromTargetType(Target->getIntMaxType());
7081}
7082
7083/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7085 return getFromTargetType(Target->getUIntMaxType());
7086}
7087
7088/// getSignedWCharType - Return the type of "signed wchar_t".
7089/// Used when in C++, as a GCC extension.
7091 // FIXME: derive from "Target" ?
7092 return WCharTy;
7093}
7094
7095/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7096/// Used when in C++, as a GCC extension.
7098 // FIXME: derive from "Target" ?
7099 return UnsignedIntTy;
7100}
7101
7103 return getFromTargetType(Target->getIntPtrType());
7104}
7105
7109
7110/// Return the unique type for "pid_t" defined in
7111/// <sys/types.h>. We need this to compute the correct type for vfork().
7113 return getFromTargetType(Target->getProcessIDType());
7114}
7115
7116//===----------------------------------------------------------------------===//
7117// Type Operators
7118//===----------------------------------------------------------------------===//
7119
7121 // Push qualifiers into arrays, and then discard any remaining
7122 // qualifiers.
7123 T = getCanonicalType(T);
7125 const Type *Ty = T.getTypePtr();
7129 } else if (isa<ArrayType>(Ty)) {
7131 } else if (isa<FunctionType>(Ty)) {
7132 Result = getPointerType(QualType(Ty, 0));
7133 } else {
7134 Result = QualType(Ty, 0);
7135 }
7136
7138}
7139
7141 Qualifiers &quals) const {
7142 SplitQualType splitType = type.getSplitUnqualifiedType();
7143
7144 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7145 // the unqualified desugared type and then drops it on the floor.
7146 // We then have to strip that sugar back off with
7147 // getUnqualifiedDesugaredType(), which is silly.
7148 const auto *AT =
7149 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7150
7151 // If we don't have an array, just use the results in splitType.
7152 if (!AT) {
7153 quals = splitType.Quals;
7154 return QualType(splitType.Ty, 0);
7155 }
7156
7157 // Otherwise, recurse on the array's element type.
7158 QualType elementType = AT->getElementType();
7159 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7160
7161 // If that didn't change the element type, AT has no qualifiers, so we
7162 // can just use the results in splitType.
7163 if (elementType == unqualElementType) {
7164 assert(quals.empty()); // from the recursive call
7165 quals = splitType.Quals;
7166 return QualType(splitType.Ty, 0);
7167 }
7168
7169 // Otherwise, add in the qualifiers from the outermost type, then
7170 // build the type back up.
7171 quals.addConsistentQualifiers(splitType.Quals);
7172
7173 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7174 return getConstantArrayType(unqualElementType, CAT->getSize(),
7175 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7176 }
7177
7178 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7179 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7180 }
7181
7182 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7183 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7184 VAT->getSizeModifier(),
7185 VAT->getIndexTypeCVRQualifiers());
7186 }
7187
7188 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7189 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7190 DSAT->getSizeModifier(), 0);
7191}
7192
7193/// Attempt to unwrap two types that may both be array types with the same bound
7194/// (or both be array types of unknown bound) for the purpose of comparing the
7195/// cv-decomposition of two types per C++ [conv.qual].
7196///
7197/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7198/// C++20 [conv.qual], if permitted by the current language mode.
7200 bool AllowPiMismatch) const {
7201 while (true) {
7202 auto *AT1 = getAsArrayType(T1);
7203 if (!AT1)
7204 return;
7205
7206 auto *AT2 = getAsArrayType(T2);
7207 if (!AT2)
7208 return;
7209
7210 // If we don't have two array types with the same constant bound nor two
7211 // incomplete array types, we've unwrapped everything we can.
7212 // C++20 also permits one type to be a constant array type and the other
7213 // to be an incomplete array type.
7214 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7215 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7216 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7217 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7218 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7220 return;
7221 } else if (isa<IncompleteArrayType>(AT1)) {
7222 if (!(isa<IncompleteArrayType>(AT2) ||
7223 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7225 return;
7226 } else {
7227 return;
7228 }
7229
7230 T1 = AT1->getElementType();
7231 T2 = AT2->getElementType();
7232 }
7233}
7234
7235/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7236///
7237/// If T1 and T2 are both pointer types of the same kind, or both array types
7238/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7239/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7240///
7241/// This function will typically be called in a loop that successively
7242/// "unwraps" pointer and pointer-to-member types to compare them at each
7243/// level.
7244///
7245/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7246/// C++20 [conv.qual], if permitted by the current language mode.
7247///
7248/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7249/// pair of types that can't be unwrapped further.
7251 bool AllowPiMismatch) const {
7252 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7253
7254 const auto *T1PtrType = T1->getAs<PointerType>();
7255 const auto *T2PtrType = T2->getAs<PointerType>();
7256 if (T1PtrType && T2PtrType) {
7257 T1 = T1PtrType->getPointeeType();
7258 T2 = T2PtrType->getPointeeType();
7259 return true;
7260 }
7261
7262 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7263 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7264 T1MPType && T2MPType) {
7265 // Compare the qualifiers of the canonical type, as the non-canonical type
7266 // may have qualifiers pointing to a base or derived class.
7267 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7268 return false;
7269 // Get the pointee types of the non-canonical type, in order to preserve
7270 // their sugar.
7271 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7272 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7273 return true;
7274 }
7275
7276 if (getLangOpts().ObjC) {
7277 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7278 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7279 if (T1OPType && T2OPType) {
7280 T1 = T1OPType->getPointeeType();
7281 T2 = T2OPType->getPointeeType();
7282 return true;
7283 }
7284 }
7285
7286 // FIXME: Block pointers, too?
7287
7288 return false;
7289}
7290
7292 while (true) {
7293 Qualifiers Quals;
7294 T1 = getUnqualifiedArrayType(T1, Quals);
7295 T2 = getUnqualifiedArrayType(T2, Quals);
7296 if (hasSameType(T1, T2))
7297 return true;
7298 if (!UnwrapSimilarTypes(T1, T2))
7299 return false;
7300 }
7301}
7302
7304 while (true) {
7305 Qualifiers Quals1, Quals2;
7306 T1 = getUnqualifiedArrayType(T1, Quals1);
7307 T2 = getUnqualifiedArrayType(T2, Quals2);
7308
7309 Quals1.removeCVRQualifiers();
7310 Quals2.removeCVRQualifiers();
7311 if (Quals1 != Quals2)
7312 return false;
7313
7314 if (hasSameType(T1, T2))
7315 return true;
7316
7317 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7318 return false;
7319 }
7320}
7321
7324 SourceLocation NameLoc) const {
7325 switch (Name.getKind()) {
7328 // DNInfo work in progress: CHECKME: what about DNLoc?
7330 NameLoc);
7331
7334 // DNInfo work in progress: CHECKME: what about DNLoc?
7335 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7336 }
7337
7340 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7341 }
7342
7346 DeclarationName DName;
7347 if (const IdentifierInfo *II = TN.getIdentifier()) {
7348 DName = DeclarationNames.getIdentifier(II);
7349 return DeclarationNameInfo(DName, NameLoc);
7350 } else {
7351 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7352 // DNInfo work in progress: FIXME: source locations?
7353 DeclarationNameLoc DNLoc =
7355 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7356 }
7357 }
7358
7362 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7363 NameLoc);
7364 }
7365
7370 NameLoc);
7371 }
7374 NameLoc);
7377 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7378 }
7381 return getNameForTemplate(PI->getPattern(), NameLoc);
7382 }
7383 }
7384
7385 llvm_unreachable("bad template name kind!");
7386}
7387
7388const TemplateArgument *
7390 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7391 if (!TP->hasDefaultArgument())
7392 return nullptr;
7393 return &TP->getDefaultArgument().getArgument();
7394 };
7395 switch (P->getKind()) {
7396 case NamedDecl::TemplateTypeParm:
7397 return handleParam(cast<TemplateTypeParmDecl>(P));
7398 case NamedDecl::NonTypeTemplateParm:
7399 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7400 case NamedDecl::TemplateTemplateParm:
7401 return handleParam(cast<TemplateTemplateParmDecl>(P));
7402 default:
7403 llvm_unreachable("Unexpected template parameter kind");
7404 }
7405}
7406
7408 bool IgnoreDeduced) const {
7409 while (std::optional<TemplateName> UnderlyingOrNone =
7410 Name.desugar(IgnoreDeduced))
7411 Name = *UnderlyingOrNone;
7412
7413 switch (Name.getKind()) {
7416 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7418
7419 // The canonical template name is the canonical template declaration.
7420 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7421 }
7422
7424 // An assumed template is just a name, so it is already canonical.
7425 return Name;
7426
7428 llvm_unreachable("cannot canonicalize overloaded template");
7429
7432 assert(DTN && "Non-dependent template names must refer to template decls.");
7433 NestedNameSpecifier Qualifier = DTN->getQualifier();
7434 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7435 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7436 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7437 /*HasTemplateKeyword=*/true});
7438 return Name;
7439 }
7440
7444 TemplateArgument canonArgPack =
7447 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7448 subst->getIndex(), subst->getFinal());
7449 }
7450
7453 SmallVector<TemplateName, 4> CanonExpansions;
7454 for (TemplateName T : PI->getExpansions())
7455 CanonExpansions.push_back(getCanonicalTemplateName(T, IgnoreDeduced));
7457 getCanonicalTemplateName(PI->getPattern(), IgnoreDeduced),
7458 PI->getIndexExpr(), PI->isFullySubstituted(), CanonExpansions);
7459 }
7461 assert(IgnoreDeduced == false);
7463 DefaultArguments DefArgs = DTS->getDefaultArguments();
7464 TemplateName Underlying = DTS->getUnderlying();
7465
7466 TemplateName CanonUnderlying =
7467 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7468 bool NonCanonical = CanonUnderlying != Underlying;
7469 auto CanonArgs =
7470 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7471
7472 ArrayRef<NamedDecl *> Params =
7473 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7474 assert(CanonArgs.size() <= Params.size());
7475 // A deduced template name which deduces the same default arguments already
7476 // declared in the underlying template is the same template as the
7477 // underlying template. We need need to note any arguments which differ from
7478 // the corresponding declaration. If any argument differs, we must build a
7479 // deduced template name.
7480 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7482 if (!A)
7483 break;
7484 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7485 TemplateArgument &CanonDefArg = CanonArgs[I];
7486 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7487 continue;
7488 // Keep popping from the back any deault arguments which are the same.
7489 if (I == int(CanonArgs.size() - 1))
7490 CanonArgs.pop_back();
7491 NonCanonical = true;
7492 }
7493 return NonCanonical ? getDeducedTemplateName(
7494 CanonUnderlying,
7495 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7496 : Name;
7497 }
7501 llvm_unreachable("always sugar node");
7502 }
7503
7504 llvm_unreachable("bad template name!");
7505}
7506
7508 const TemplateName &Y,
7509 bool IgnoreDeduced) const {
7510 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7511 getCanonicalTemplateName(Y, IgnoreDeduced);
7512}
7513
7515 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7516 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7517 return false;
7519 return false;
7520 return true;
7521}
7522
7523bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7524 if (!XCE != !YCE)
7525 return false;
7526
7527 if (!XCE)
7528 return true;
7529
7530 llvm::FoldingSetNodeID XCEID, YCEID;
7531 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7532 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7533 return XCEID == YCEID;
7534}
7535
7537 const TypeConstraint *YTC) const {
7538 if (!XTC != !YTC)
7539 return false;
7540
7541 if (!XTC)
7542 return true;
7543
7546 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7547 return false;
7550 return false;
7552 if (XTC->getConceptReference()
7554 ->NumTemplateArgs !=
7556 return false;
7557
7558 // Compare slowly by profiling.
7559 //
7560 // We couldn't compare the profiling result for the template
7561 // args here. Consider the following example in different modules:
7562 //
7563 // template <__integer_like _Tp, C<_Tp> Sentinel>
7564 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7565 // return __t;
7566 // }
7567 //
7568 // When we compare the profiling result for `C<_Tp>` in different
7569 // modules, it will compare the type of `_Tp` in different modules.
7570 // However, the type of `_Tp` in different modules refer to different
7571 // types here naturally. So we couldn't compare the profiling result
7572 // for the template args directly.
7575}
7576
7578 const NamedDecl *Y) const {
7579 if (X->getKind() != Y->getKind())
7580 return false;
7581
7582 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7583 auto *TY = cast<TemplateTypeParmDecl>(Y);
7584 if (TX->isParameterPack() != TY->isParameterPack())
7585 return false;
7586 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7587 return false;
7588 return isSameTypeConstraint(TX->getTypeConstraint(),
7589 TY->getTypeConstraint());
7590 }
7591
7592 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7593 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7594 return TX->isParameterPack() == TY->isParameterPack() &&
7595 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7596 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7597 TY->getPlaceholderTypeConstraint());
7598 }
7599
7601 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7602 return TX->isParameterPack() == TY->isParameterPack() &&
7603 isSameTemplateParameterList(TX->getTemplateParameters(),
7604 TY->getTemplateParameters());
7605}
7606
7608 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7609 if (X->size() != Y->size())
7610 return false;
7611
7612 for (unsigned I = 0, N = X->size(); I != N; ++I)
7613 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7614 return false;
7615
7616 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7617}
7618
7620 const NamedDecl *Y) const {
7621 // If the type parameter isn't the same already, we don't need to check the
7622 // default argument further.
7623 if (!isSameTemplateParameter(X, Y))
7624 return false;
7625
7626 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7627 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7628 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7629 return false;
7630
7631 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7632 TTPY->getDefaultArgument().getArgument().getAsType());
7633 }
7634
7635 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7636 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7637 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7638 return false;
7639
7640 Expr *DefaultArgumentX =
7641 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7642 Expr *DefaultArgumentY =
7643 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7644 llvm::FoldingSetNodeID XID, YID;
7645 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7646 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7647 return XID == YID;
7648 }
7649
7650 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7651 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7652
7653 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7654 return false;
7655
7656 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7657 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7658 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7659}
7660
7662 const NestedNameSpecifier Y) {
7663 if (X == Y)
7664 return true;
7665 if (!X || !Y)
7666 return false;
7667
7668 auto Kind = X.getKind();
7669 if (Kind != Y.getKind())
7670 return false;
7671
7672 // FIXME: For namespaces and types, we're permitted to check that the entity
7673 // is named via the same tokens. We should probably do so.
7674 switch (Kind) {
7676 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7677 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7678 if (!declaresSameEntity(NamespaceX->getNamespace(),
7679 NamespaceY->getNamespace()))
7680 return false;
7681 return isSameQualifier(PrefixX, PrefixY);
7682 }
7684 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7685 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7686 return false;
7687 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7688 }
7692 return true;
7693 }
7694 llvm_unreachable("unhandled qualifier kind");
7695}
7696
7697static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7698 if (!A->getASTContext().getLangOpts().CUDA)
7699 return true; // Target attributes are overloadable in CUDA compilation only.
7700 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7701 return false;
7702 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7703 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7704 return true; // unattributed and __host__ functions are the same.
7705}
7706
7707/// Determine whether the attributes we can overload on are identical for A and
7708/// B. Will ignore any overloadable attrs represented in the type of A and B.
7710 const FunctionDecl *B) {
7711 // Note that pass_object_size attributes are represented in the function's
7712 // ExtParameterInfo, so we don't need to check them here.
7713
7714 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7715 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7716 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7717
7718 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7719 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7720 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7721
7722 // Return false if the number of enable_if attributes is different.
7723 if (!Cand1A || !Cand2A)
7724 return false;
7725
7726 Cand1ID.clear();
7727 Cand2ID.clear();
7728
7729 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7730 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7731
7732 // Return false if any of the enable_if expressions of A and B are
7733 // different.
7734 if (Cand1ID != Cand2ID)
7735 return false;
7736 }
7737 return hasSameCudaAttrs(A, B);
7738}
7739
7740bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7741 // Caution: this function is called by the AST reader during deserialization,
7742 // so it cannot rely on AST invariants being met. Non-trivial accessors
7743 // should be avoided, along with any traversal of redeclaration chains.
7744
7745 if (X == Y)
7746 return true;
7747
7748 if (X->getDeclName() != Y->getDeclName())
7749 return false;
7750
7751 // Must be in the same context.
7752 //
7753 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7754 // could be two different declarations of the same function. (We will fix the
7755 // semantic DC to refer to the primary definition after merging.)
7756 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7758 return false;
7759
7760 // If either X or Y are local to the owning module, they are only possible to
7761 // be the same entity if they are in the same module, or if they are members
7762 // of a lambda closure type. Closure types are merged by identity, and a class
7763 // definition determines its members, so the members of a merged closure type
7764 // are the same entity even if they are module-local to different modules.
7765 // Two distinct closure types are still not merged, so their members are never
7766 // compared.
7767 if (X->isModuleLocal() || Y->isModuleLocal()) {
7768 auto *RD = dyn_cast<CXXRecordDecl>(X->getDeclContext());
7769 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()) &&
7770 !(RD && RD->isLambda()))
7771 return false;
7772 }
7773
7774 // Two typedefs refer to the same entity if they have the same underlying
7775 // type.
7776 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7777 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7778 return hasSameType(TypedefX->getUnderlyingType(),
7779 TypedefY->getUnderlyingType());
7780
7781 // Must have the same kind.
7782 if (X->getKind() != Y->getKind())
7783 return false;
7784
7785 // Objective-C classes and protocols with the same name always match.
7787 return true;
7788
7790 // No need to handle these here: we merge them when adding them to the
7791 // template.
7792 return false;
7793 }
7794
7795 // Compatible tags match.
7796 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7797 const auto *TagY = cast<TagDecl>(Y);
7798 return (TagX->getTagKind() == TagY->getTagKind()) ||
7799 ((TagX->getTagKind() == TagTypeKind::Struct ||
7800 TagX->getTagKind() == TagTypeKind::Class ||
7801 TagX->getTagKind() == TagTypeKind::Interface) &&
7802 (TagY->getTagKind() == TagTypeKind::Struct ||
7803 TagY->getTagKind() == TagTypeKind::Class ||
7804 TagY->getTagKind() == TagTypeKind::Interface));
7805 }
7806
7807 // Functions with the same type and linkage match.
7808 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7809 // functions, etc.
7810 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7811 const auto *FuncY = cast<FunctionDecl>(Y);
7812 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7813 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7814 if (CtorX->getInheritedConstructor() &&
7815 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7816 CtorY->getInheritedConstructor().getConstructor()))
7817 return false;
7818 }
7819
7820 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7821 return false;
7822
7823 // Multiversioned functions with different feature strings are represented
7824 // as separate declarations.
7825 if (FuncX->isMultiVersion()) {
7826 const auto *TAX = FuncX->getAttr<TargetAttr>();
7827 const auto *TAY = FuncY->getAttr<TargetAttr>();
7828 assert(TAX && TAY && "Multiversion Function without target attribute");
7829
7830 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7831 return false;
7832 }
7833
7834 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7835 // not the same entity if they are constrained.
7836 if ((FuncX->isMemberLikeConstrainedFriend() ||
7837 FuncY->isMemberLikeConstrainedFriend()) &&
7838 !FuncX->getLexicalDeclContext()->Equals(
7839 FuncY->getLexicalDeclContext())) {
7840 return false;
7841 }
7842
7843 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7844 FuncY->getTrailingRequiresClause()))
7845 return false;
7846
7847 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7848 // Map to the first declaration that we've already merged into this one.
7849 // The TSI of redeclarations might not match (due to calling conventions
7850 // being inherited onto the type but not the TSI), but the TSI type of
7851 // the first declaration of the function should match across modules.
7852 FD = FD->getCanonicalDecl();
7853 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7854 : FD->getType();
7855 };
7856 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7857 if (!hasSameType(XT, YT)) {
7858 // We can get functions with different types on the redecl chain in C++17
7859 // if they have differing exception specifications and at least one of
7860 // the excpetion specs is unresolved.
7861 auto *XFPT = XT->getAs<FunctionProtoType>();
7862 auto *YFPT = YT->getAs<FunctionProtoType>();
7863 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7864 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7867 return true;
7868 return false;
7869 }
7870
7871 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7872 hasSameOverloadableAttrs(FuncX, FuncY);
7873 }
7874
7875 // Variables with the same type and linkage match.
7876 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7877 const auto *VarY = cast<VarDecl>(Y);
7878 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7879 // During deserialization, we might compare variables before we load
7880 // their types. Assume the types will end up being the same.
7881 if (VarX->getType().isNull() || VarY->getType().isNull())
7882 return true;
7883
7884 if (hasSameType(VarX->getType(), VarY->getType()))
7885 return true;
7886
7887 // We can get decls with different types on the redecl chain. Eg.
7888 // template <typename T> struct S { static T Var[]; }; // #1
7889 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7890 // Only? happens when completing an incomplete array type. In this case
7891 // when comparing #1 and #2 we should go through their element type.
7892 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7893 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7894 if (!VarXTy || !VarYTy)
7895 return false;
7896 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7897 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7898 }
7899 return false;
7900 }
7901
7902 // Namespaces with the same name and inlinedness match.
7903 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7904 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7905 return NamespaceX->isInline() == NamespaceY->isInline();
7906 }
7907
7908 // Identical template names and kinds match if their template parameter lists
7909 // and patterns match.
7910 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7911 const auto *TemplateY = cast<TemplateDecl>(Y);
7912
7913 // ConceptDecl wouldn't be the same if their constraint expression differs.
7914 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7915 const auto *ConceptY = cast<ConceptDecl>(Y);
7916 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7917 ConceptY->getConstraintExpr()))
7918 return false;
7919 }
7920
7921 return isSameEntity(TemplateX->getTemplatedDecl(),
7922 TemplateY->getTemplatedDecl()) &&
7923 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7924 TemplateY->getTemplateParameters());
7925 }
7926
7927 // Fields with the same name and the same type match.
7928 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7929 const auto *FDY = cast<FieldDecl>(Y);
7930 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7931 return hasSameType(FDX->getType(), FDY->getType());
7932 }
7933
7934 // Indirect fields with the same target field match.
7935 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7936 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7937 return IFDX->getAnonField()->getCanonicalDecl() ==
7938 IFDY->getAnonField()->getCanonicalDecl();
7939 }
7940
7941 // Enumerators with the same name match.
7943 // FIXME: Also check the value is odr-equivalent.
7944 return true;
7945
7946 // Using shadow declarations with the same target match.
7947 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7948 const auto *USY = cast<UsingShadowDecl>(Y);
7949 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7950 }
7951
7952 // Using declarations with the same qualifier match. (We already know that
7953 // the name matches.)
7954 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7955 const auto *UY = cast<UsingDecl>(Y);
7956 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7957 UX->hasTypename() == UY->hasTypename() &&
7958 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7959 }
7960 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7961 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7962 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7963 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7964 }
7965 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7966 return isSameQualifier(
7967 UX->getQualifier(),
7968 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7969 }
7970
7971 // Using-pack declarations are only created by instantiation, and match if
7972 // they're instantiated from matching UnresolvedUsing...Decls.
7973 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7974 return declaresSameEntity(
7975 UX->getInstantiatedFromUsingDecl(),
7976 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7977 }
7978
7979 // Namespace alias definitions with the same target match.
7980 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7981 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7982 return NAX->getNamespace()->Equals(NAY->getNamespace());
7983 }
7984
7985 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7986 const auto *UY = cast<UsingEnumDecl>(Y);
7987 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7988 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7989 }
7990
7991 return false;
7992}
7993
7996 switch (Arg.getKind()) {
7998 return Arg;
7999
8001 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8002 Arg.getIsDefaulted());
8003
8005 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8007 Arg.getIsDefaulted());
8008 }
8009
8012 /*isNullPtr*/ true, Arg.getIsDefaulted());
8013
8016 Arg.getIsDefaulted());
8017
8019 return TemplateArgument(
8022
8025
8027 return TemplateArgument(*this,
8030
8033 /*isNullPtr*/ false, Arg.getIsDefaulted());
8034
8036 bool AnyNonCanonArgs = false;
8037 auto CanonArgs = ::getCanonicalTemplateArguments(
8038 *this, Arg.pack_elements(), AnyNonCanonArgs);
8039 if (!AnyNonCanonArgs)
8040 return Arg;
8042 const_cast<ASTContext &>(*this), CanonArgs);
8043 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8044 return NewArg;
8045 }
8046 }
8047
8048 // Silence GCC warning
8049 llvm_unreachable("Unhandled template argument kind");
8050}
8051
8053 const TemplateArgument &Arg2) const {
8054 if (Arg1.getKind() != Arg2.getKind())
8055 return false;
8056
8057 switch (Arg1.getKind()) {
8059 llvm_unreachable("Comparing NULL template argument");
8060
8062 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8063
8065 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8067
8069 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8070
8075
8077 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8078 Arg2.getAsIntegral());
8079
8081 return Arg1.structurallyEquals(Arg2);
8082
8084 llvm::FoldingSetNodeID ID1, ID2;
8085 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8086 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8087 return ID1 == ID2;
8088 }
8089
8091 return llvm::equal(
8092 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8093 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8094 return isSameTemplateArgument(Arg1, Arg2);
8095 });
8096 }
8097
8098 llvm_unreachable("Unhandled template argument kind");
8099}
8100
8102 // Handle the non-qualified case efficiently.
8103 if (!T.hasLocalQualifiers()) {
8104 // Handle the common positive case fast.
8105 if (const auto *AT = dyn_cast<ArrayType>(T))
8106 return AT;
8107 }
8108
8109 // Handle the common negative case fast.
8110 if (!isa<ArrayType>(T.getCanonicalType()))
8111 return nullptr;
8112
8113 // Apply any qualifiers from the array type to the element type. This
8114 // implements C99 6.7.3p8: "If the specification of an array type includes
8115 // any type qualifiers, the element type is so qualified, not the array type."
8116
8117 // If we get here, we either have type qualifiers on the type, or we have
8118 // sugar such as a typedef in the way. If we have type qualifiers on the type
8119 // we must propagate them down into the element type.
8120
8121 SplitQualType split = T.getSplitDesugaredType();
8122 Qualifiers qs = split.Quals;
8123
8124 // If we have a simple case, just return now.
8125 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8126 if (!ATy || qs.empty())
8127 return ATy;
8128
8129 // Otherwise, we have an array and we have qualifiers on it. Push the
8130 // qualifiers into the array element type and return a new array type.
8131 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8132
8133 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8134 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8135 CAT->getSizeExpr(),
8136 CAT->getSizeModifier(),
8137 CAT->getIndexTypeCVRQualifiers()));
8138 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8140 IAT->getSizeModifier(),
8141 IAT->getIndexTypeCVRQualifiers()));
8142
8143 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8145 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8146 DSAT->getIndexTypeCVRQualifiers()));
8147
8148 const auto *VAT = cast<VariableArrayType>(ATy);
8149 return cast<ArrayType>(
8150 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8151 VAT->getIndexTypeCVRQualifiers()));
8152}
8153
8155 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8156 return getLValueReferenceType(T);
8157 if (getLangOpts().HLSL && T->isConstantArrayType())
8158 return getArrayParameterType(T);
8159 if (T->isArrayType() || T->isFunctionType())
8160 return getDecayedType(T);
8161 return T;
8162}
8163
8167 return T.getUnqualifiedType();
8168}
8169
8171 // C++ [except.throw]p3:
8172 // A throw-expression initializes a temporary object, called the exception
8173 // object, the type of which is determined by removing any top-level
8174 // cv-qualifiers from the static type of the operand of throw and adjusting
8175 // the type from "array of T" or "function returning T" to "pointer to T"
8176 // or "pointer to function returning T", [...]
8178 if (T->isArrayType() || T->isFunctionType())
8179 T = getDecayedType(T);
8180 return T.getUnqualifiedType();
8181}
8182
8183/// getArrayDecayedType - Return the properly qualified result of decaying the
8184/// specified array type to a pointer. This operation is non-trivial when
8185/// handling typedefs etc. The canonical type of "T" must be an array type,
8186/// this returns a pointer to a properly qualified element of the array.
8187///
8188/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8190 // Get the element type with 'getAsArrayType' so that we don't lose any
8191 // typedefs in the element type of the array. This also handles propagation
8192 // of type qualifiers from the array type into the element type if present
8193 // (C99 6.7.3p8).
8194 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8195 assert(PrettyArrayType && "Not an array type!");
8196
8197 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8198
8199 // int x[restrict 4] -> int *restrict
8201 PrettyArrayType->getIndexTypeQualifiers());
8202
8203 // int x[_Nullable] -> int * _Nullable
8204 if (auto Nullability = Ty->getNullability()) {
8205 Result = getAttributedType(*Nullability, Result, Result);
8206 }
8207 return Result;
8208}
8209
8211 return getBaseElementType(array->getElementType());
8212}
8213
8215 Qualifiers qs;
8216 while (true) {
8217 SplitQualType split = type.getSplitDesugaredType();
8218 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8219 if (!array) break;
8220
8221 type = array->getElementType();
8223 }
8224
8225 return getQualifiedType(type, qs);
8226}
8227
8229 uint64_t ElementCount = 1;
8230 do {
8231 ElementCount *= CA->getZExtSize();
8232 CA = dyn_cast_if_present<ConstantArrayType>(
8234 } while (CA);
8235 return ElementCount;
8236}
8237
8238uint64_t
8240 if (!AILE)
8241 return 0;
8242
8243 uint64_t ElementCount = 1;
8244
8245 do {
8246 ElementCount *= AILE->getArraySize().getZExtValue();
8247 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8248 } while (AILE);
8249
8250 return ElementCount;
8251}
8252
8253/// getFloatingRank - Return a relative rank for floating point types.
8254/// This routine will assert if passed a built-in type that isn't a float.
8256 if (const auto *CT = T->getAs<ComplexType>())
8257 return getFloatingRank(CT->getElementType());
8258
8259 switch (T->castAs<BuiltinType>()->getKind()) {
8260 default: llvm_unreachable("getFloatingRank(): not a floating type");
8261 case BuiltinType::Float16: return Float16Rank;
8262 case BuiltinType::Half: return HalfRank;
8263 case BuiltinType::Float: return FloatRank;
8264 case BuiltinType::Double: return DoubleRank;
8265 case BuiltinType::LongDouble: return LongDoubleRank;
8266 case BuiltinType::Float128: return Float128Rank;
8267 case BuiltinType::BFloat16: return BFloat16Rank;
8268 case BuiltinType::Ibm128: return Ibm128Rank;
8269 }
8270}
8271
8272/// getFloatingTypeOrder - Compare the rank of the two specified floating
8273/// point types, ignoring the domain of the type (i.e. 'double' ==
8274/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8275/// LHS < RHS, return -1.
8277 FloatingRank LHSR = getFloatingRank(LHS);
8278 FloatingRank RHSR = getFloatingRank(RHS);
8279
8280 if (LHSR == RHSR)
8281 return 0;
8282 if (LHSR > RHSR)
8283 return 1;
8284 return -1;
8285}
8286
8289 return 0;
8290 return getFloatingTypeOrder(LHS, RHS);
8291}
8292
8293/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8294/// routine will assert if passed a built-in type that isn't an integer or enum,
8295/// or if it is not canonicalized.
8296unsigned ASTContext::getIntegerRank(const Type *T) const {
8297 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8298
8299 // Results in this 'losing' to any type of the same size, but winning if
8300 // larger.
8301 if (const auto *EIT = dyn_cast<BitIntType>(T))
8302 return 0 + (EIT->getNumBits() << 3);
8303
8304 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8305 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8306
8307 switch (cast<BuiltinType>(T)->getKind()) {
8308 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8309 case BuiltinType::Bool:
8310 return 1 + (getIntWidth(BoolTy) << 3);
8311 case BuiltinType::Char_S:
8312 case BuiltinType::Char_U:
8313 case BuiltinType::SChar:
8314 case BuiltinType::UChar:
8315 return 2 + (getIntWidth(CharTy) << 3);
8316 case BuiltinType::Short:
8317 case BuiltinType::UShort:
8318 return 3 + (getIntWidth(ShortTy) << 3);
8319 case BuiltinType::Int:
8320 case BuiltinType::UInt:
8321 return 4 + (getIntWidth(IntTy) << 3);
8322 case BuiltinType::Long:
8323 case BuiltinType::ULong:
8324 return 5 + (getIntWidth(LongTy) << 3);
8325 case BuiltinType::LongLong:
8326 case BuiltinType::ULongLong:
8327 return 6 + (getIntWidth(LongLongTy) << 3);
8328 case BuiltinType::Int128:
8329 case BuiltinType::UInt128:
8330 return 7 + (getIntWidth(Int128Ty) << 3);
8331
8332 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8333 // their underlying types" [c++20 conv.rank]
8334 case BuiltinType::Char8:
8335 return getIntegerRank(UnsignedCharTy.getTypePtr());
8336 case BuiltinType::Char16:
8337 return getIntegerRank(
8338 getFromTargetType(Target->getChar16Type()).getTypePtr());
8339 case BuiltinType::Char32:
8340 return getIntegerRank(
8341 getFromTargetType(Target->getChar32Type()).getTypePtr());
8342 case BuiltinType::WChar_S:
8343 case BuiltinType::WChar_U:
8344 return getIntegerRank(
8345 getFromTargetType(Target->getWCharType()).getTypePtr());
8346 }
8347}
8348
8349/// Whether this is a promotable bitfield reference according
8350/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8351///
8352/// \returns the type this bit-field will promote to, or NULL if no
8353/// promotion occurs.
8355 if (E->isTypeDependent() || E->isValueDependent())
8356 return {};
8357
8358 // C++ [conv.prom]p5:
8359 // If the bit-field has an enumerated type, it is treated as any other
8360 // value of that type for promotion purposes.
8362 return {};
8363
8364 // FIXME: We should not do this unless E->refersToBitField() is true. This
8365 // matters in C where getSourceBitField() will find bit-fields for various
8366 // cases where the source expression is not a bit-field designator.
8367
8368 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8369 if (!Field)
8370 return {};
8371
8372 QualType FT = Field->getType();
8373
8374 uint64_t BitWidth = Field->getBitWidthValue();
8375 uint64_t IntSize = getTypeSize(IntTy);
8376 // C++ [conv.prom]p5:
8377 // A prvalue for an integral bit-field can be converted to a prvalue of type
8378 // int if int can represent all the values of the bit-field; otherwise, it
8379 // can be converted to unsigned int if unsigned int can represent all the
8380 // values of the bit-field. If the bit-field is larger yet, no integral
8381 // promotion applies to it.
8382 // C11 6.3.1.1/2:
8383 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8384 // If an int can represent all values of the original type (as restricted by
8385 // the width, for a bit-field), the value is converted to an int; otherwise,
8386 // it is converted to an unsigned int.
8387 //
8388 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8389 // We perform that promotion here to match GCC and C++.
8390 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8391 // greater than that of 'int'. We perform that promotion to match GCC.
8392 //
8393 // C23 6.3.1.1p2:
8394 // The value from a bit-field of a bit-precise integer type is converted to
8395 // the corresponding bit-precise integer type. (The rest is the same as in
8396 // C11.)
8397 if (QualType QT = Field->getType(); QT->isBitIntType())
8398 return QT;
8399
8400 if (BitWidth < IntSize)
8401 return IntTy;
8402
8403 if (BitWidth == IntSize)
8404 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8405
8406 // Bit-fields wider than int are not subject to promotions, and therefore act
8407 // like the base type. GCC has some weird bugs in this area that we
8408 // deliberately do not follow (GCC follows a pre-standard resolution to
8409 // C's DR315 which treats bit-width as being part of the type, and this leaks
8410 // into their semantics in some cases).
8411 return {};
8412}
8413
8414/// getPromotedIntegerType - Returns the type that Promotable will
8415/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8416/// integer type.
8418 assert(!Promotable.isNull());
8419 assert(isPromotableIntegerType(Promotable));
8420 if (const auto *ED = Promotable->getAsEnumDecl())
8421 return ED->getPromotionType();
8422
8423 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8424 // qualifier.
8425 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8426 QualType PromotedUnderlying =
8427 getPromotedIntegerType(OBT->getUnderlyingType());
8428 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8429 }
8430
8431 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8432 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8433 // (3.9.1) can be converted to a prvalue of the first of the following
8434 // types that can represent all the values of its underlying type:
8435 // int, unsigned int, long int, unsigned long int, long long int, or
8436 // unsigned long long int [...]
8437 // FIXME: Is there some better way to compute this?
8438 if (BT->getKind() == BuiltinType::WChar_S ||
8439 BT->getKind() == BuiltinType::WChar_U ||
8440 BT->getKind() == BuiltinType::Char8 ||
8441 BT->getKind() == BuiltinType::Char16 ||
8442 BT->getKind() == BuiltinType::Char32) {
8443 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8444 uint64_t FromSize = getTypeSize(BT);
8445 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8447 for (const auto &PT : PromoteTypes) {
8448 uint64_t ToSize = getTypeSize(PT);
8449 if (FromSize < ToSize ||
8450 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8451 return PT;
8452 }
8453 llvm_unreachable("char type should fit into long long");
8454 }
8455 }
8456
8457 // At this point, we should have a signed or unsigned integer type.
8458 if (Promotable->isSignedIntegerType())
8459 return IntTy;
8460 uint64_t PromotableSize = getIntWidth(Promotable);
8461 uint64_t IntSize = getIntWidth(IntTy);
8462 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8463 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8464}
8465
8466/// Recurses in pointer/array types until it finds an objc retainable
8467/// type and returns its ownership.
8469 while (!T.isNull()) {
8470 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8471 return T.getObjCLifetime();
8472 if (T->isArrayType())
8474 else if (const auto *PT = T->getAs<PointerType>())
8475 T = PT->getPointeeType();
8476 else if (const auto *RT = T->getAs<ReferenceType>())
8477 T = RT->getPointeeType();
8478 else
8479 break;
8480 }
8481
8482 return Qualifiers::OCL_None;
8483}
8484
8485static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8486 // Incomplete enum types are not treated as integer types.
8487 // FIXME: In C++, enum types are never integer types.
8488 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8489 if (ED->isComplete() && !ED->isScoped())
8490 return ED->getIntegerType().getTypePtr();
8491 return nullptr;
8492}
8493
8494/// getIntegerTypeOrder - Returns the highest ranked integer type:
8495/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8496/// LHS < RHS, return -1.
8498 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8499 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8500
8501 // Unwrap enums to their underlying type.
8502 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8503 LHSC = getIntegerTypeForEnum(ET);
8504 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8505 RHSC = getIntegerTypeForEnum(ET);
8506
8507 if (LHSC == RHSC) return 0;
8508
8509 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8510 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8511
8512 unsigned LHSRank = getIntegerRank(LHSC);
8513 unsigned RHSRank = getIntegerRank(RHSC);
8514
8515 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8516 if (LHSRank == RHSRank) return 0;
8517 return LHSRank > RHSRank ? 1 : -1;
8518 }
8519
8520 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8521 if (LHSUnsigned) {
8522 // If the unsigned [LHS] type is larger, return it.
8523 if (LHSRank >= RHSRank)
8524 return 1;
8525
8526 // If the signed type can represent all values of the unsigned type, it
8527 // wins. Because we are dealing with 2's complement and types that are
8528 // powers of two larger than each other, this is always safe.
8529 return -1;
8530 }
8531
8532 // If the unsigned [RHS] type is larger, return it.
8533 if (RHSRank >= LHSRank)
8534 return -1;
8535
8536 // If the signed type can represent all values of the unsigned type, it
8537 // wins. Because we are dealing with 2's complement and types that are
8538 // powers of two larger than each other, this is always safe.
8539 return 1;
8540}
8541
8543 if (CFConstantStringTypeDecl)
8544 return CFConstantStringTypeDecl;
8545
8546 assert(!CFConstantStringTagDecl &&
8547 "tag and typedef should be initialized together");
8548 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8549 CFConstantStringTagDecl->startDefinition();
8550
8551 struct {
8552 QualType Type;
8553 const char *Name;
8554 } Fields[5];
8555 unsigned Count = 0;
8556
8557 /// Objective-C ABI
8558 ///
8559 /// typedef struct __NSConstantString_tag {
8560 /// const int *isa;
8561 /// int flags;
8562 /// const char *str;
8563 /// long length;
8564 /// } __NSConstantString;
8565 ///
8566 /// Swift ABI (4.1, 4.2)
8567 ///
8568 /// typedef struct __NSConstantString_tag {
8569 /// uintptr_t _cfisa;
8570 /// uintptr_t _swift_rc;
8571 /// _Atomic(uint64_t) _cfinfoa;
8572 /// const char *_ptr;
8573 /// uint32_t _length;
8574 /// } __NSConstantString;
8575 ///
8576 /// Swift ABI (5.0)
8577 ///
8578 /// typedef struct __NSConstantString_tag {
8579 /// uintptr_t _cfisa;
8580 /// uintptr_t _swift_rc;
8581 /// _Atomic(uint64_t) _cfinfoa;
8582 /// const char *_ptr;
8583 /// uintptr_t _length;
8584 /// } __NSConstantString;
8585
8586 const auto CFRuntime = getLangOpts().CFRuntime;
8587 if (static_cast<unsigned>(CFRuntime) <
8588 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8589 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8590 Fields[Count++] = { IntTy, "flags" };
8591 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8592 Fields[Count++] = { LongTy, "length" };
8593 } else {
8594 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8595 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8596 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8597 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8600 Fields[Count++] = { IntTy, "_ptr" };
8601 else
8602 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8603 }
8604
8605 // Create fields
8606 for (unsigned i = 0; i < Count; ++i) {
8607 FieldDecl *Field =
8608 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8609 SourceLocation(), &Idents.get(Fields[i].Name),
8610 Fields[i].Type, /*TInfo=*/nullptr,
8611 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8612 Field->setAccess(AS_public);
8613 CFConstantStringTagDecl->addDecl(Field);
8614 }
8615
8616 CFConstantStringTagDecl->completeDefinition();
8617 // This type is designed to be compatible with NSConstantString, but cannot
8618 // use the same name, since NSConstantString is an interface.
8619 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8620 CFConstantStringTypeDecl =
8621 buildImplicitTypedef(tagType, "__NSConstantString");
8622
8623 return CFConstantStringTypeDecl;
8624}
8625
8627 if (!CFConstantStringTagDecl)
8628 getCFConstantStringDecl(); // Build the tag and the typedef.
8629 return CFConstantStringTagDecl;
8630}
8631
8632// getCFConstantStringType - Return the type used for constant CFStrings.
8637
8639 if (ObjCSuperType.isNull()) {
8640 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8641 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8642 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8643 }
8644 return ObjCSuperType;
8645}
8646
8648 const auto *TT = T->castAs<TypedefType>();
8649 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8650 CFConstantStringTagDecl = TT->castAsRecordDecl();
8651}
8652
8654 if (BlockDescriptorType)
8655 return getCanonicalTagType(BlockDescriptorType);
8656
8657 RecordDecl *RD;
8658 // FIXME: Needs the FlagAppleBlock bit.
8659 RD = buildImplicitRecord("__block_descriptor");
8660 RD->startDefinition();
8661
8662 QualType FieldTypes[] = {
8665 };
8666
8667 static const char *const FieldNames[] = {
8668 "reserved",
8669 "Size"
8670 };
8671
8672 for (size_t i = 0; i < 2; ++i) {
8674 *this, RD, SourceLocation(), SourceLocation(),
8675 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8676 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8677 Field->setAccess(AS_public);
8678 RD->addDecl(Field);
8679 }
8680
8681 RD->completeDefinition();
8682
8683 BlockDescriptorType = RD;
8684
8685 return getCanonicalTagType(BlockDescriptorType);
8686}
8687
8689 if (BlockDescriptorExtendedType)
8690 return getCanonicalTagType(BlockDescriptorExtendedType);
8691
8692 RecordDecl *RD;
8693 // FIXME: Needs the FlagAppleBlock bit.
8694 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8695 RD->startDefinition();
8696
8697 QualType FieldTypes[] = {
8702 };
8703
8704 static const char *const FieldNames[] = {
8705 "reserved",
8706 "Size",
8707 "CopyFuncPtr",
8708 "DestroyFuncPtr"
8709 };
8710
8711 for (size_t i = 0; i < 4; ++i) {
8713 *this, RD, SourceLocation(), SourceLocation(),
8714 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8715 /*BitWidth=*/nullptr,
8716 /*Mutable=*/false, ICIS_NoInit);
8717 Field->setAccess(AS_public);
8718 RD->addDecl(Field);
8719 }
8720
8721 RD->completeDefinition();
8722
8723 BlockDescriptorExtendedType = RD;
8724 return getCanonicalTagType(BlockDescriptorExtendedType);
8725}
8726
8728 const auto *BT = dyn_cast<BuiltinType>(T);
8729
8730 if (!BT) {
8731 if (isa<PipeType>(T))
8732 return OCLTK_Pipe;
8733
8734 return OCLTK_Default;
8735 }
8736
8737 switch (BT->getKind()) {
8738#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8739 case BuiltinType::Id: \
8740 return OCLTK_Image;
8741#include "clang/Basic/OpenCLImageTypes.def"
8742
8743 case BuiltinType::OCLClkEvent:
8744 return OCLTK_ClkEvent;
8745
8746 case BuiltinType::OCLEvent:
8747 return OCLTK_Event;
8748
8749 case BuiltinType::OCLQueue:
8750 return OCLTK_Queue;
8751
8752 case BuiltinType::OCLReserveID:
8753 return OCLTK_ReserveID;
8754
8755 case BuiltinType::OCLSampler:
8756 return OCLTK_Sampler;
8757
8758 default:
8759 return OCLTK_Default;
8760 }
8761}
8762
8764 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8765}
8766
8767/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8768/// requires copy/dispose. Note that this must match the logic
8769/// in buildByrefHelpers.
8771 const VarDecl *D) {
8772 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8773 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8774 if (!copyExpr && record->hasTrivialDestructor()) return false;
8775
8776 return true;
8777 }
8778
8780 return true;
8781
8782 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8783 // move or destroy.
8785 return true;
8786
8787 if (!Ty->isObjCRetainableType()) return false;
8788
8789 Qualifiers qs = Ty.getQualifiers();
8790
8791 // If we have lifetime, that dominates.
8792 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8793 switch (lifetime) {
8794 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8795
8796 // These are just bits as far as the runtime is concerned.
8799 return false;
8800
8801 // These cases should have been taken care of when checking the type's
8802 // non-triviality.
8805 llvm_unreachable("impossible");
8806 }
8807 llvm_unreachable("fell out of lifetime switch!");
8808 }
8809 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8811}
8812
8814 Qualifiers::ObjCLifetime &LifeTime,
8815 bool &HasByrefExtendedLayout) const {
8816 if (!getLangOpts().ObjC ||
8817 getLangOpts().getGC() != LangOptions::NonGC)
8818 return false;
8819
8820 HasByrefExtendedLayout = false;
8821 if (Ty->isRecordType()) {
8822 HasByrefExtendedLayout = true;
8823 LifeTime = Qualifiers::OCL_None;
8824 } else if ((LifeTime = Ty.getObjCLifetime())) {
8825 // Honor the ARC qualifiers.
8826 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8827 // The MRR rule.
8829 } else {
8830 LifeTime = Qualifiers::OCL_None;
8831 }
8832 return true;
8833}
8834
8836 assert(Target && "Expected target to be initialized");
8837 const llvm::Triple &T = Target->getTriple();
8838 // Windows is LLP64 rather than LP64
8839 if (T.isOSWindows() && T.isArch64Bit())
8840 return UnsignedLongLongTy;
8841 return UnsignedLongTy;
8842}
8843
8845 assert(Target && "Expected target to be initialized");
8846 const llvm::Triple &T = Target->getTriple();
8847 // Windows is LLP64 rather than LP64
8848 if (T.isOSWindows() && T.isArch64Bit())
8849 return LongLongTy;
8850 return LongTy;
8851}
8852
8854 if (!ObjCInstanceTypeDecl)
8855 ObjCInstanceTypeDecl =
8856 buildImplicitTypedef(getObjCIdType(), "instancetype");
8857 return ObjCInstanceTypeDecl;
8858}
8859
8860// This returns true if a type has been typedefed to BOOL:
8861// typedef <type> BOOL;
8863 if (const auto *TT = dyn_cast<TypedefType>(T))
8864 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8865 return II->isStr("BOOL");
8866
8867 return false;
8868}
8869
8870/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8871/// purpose.
8873 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8874 return CharUnits::Zero();
8875
8877
8878 // Make all integer and enum types at least as large as an int
8879 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8880 sz = std::max(sz, getTypeSizeInChars(IntTy));
8881 // Treat arrays as pointers, since that's how they're passed in.
8882 else if (type->isArrayType())
8884 return sz;
8885}
8886
8893
8896 if (!VD->isInline())
8898
8899 // In almost all cases, it's a weak definition.
8900 auto *First = VD->getFirstDecl();
8901 if (First->isInlineSpecified() || !First->isStaticDataMember())
8903
8904 // If there's a file-context declaration in this translation unit, it's a
8905 // non-discardable definition.
8906 for (auto *D : VD->redecls())
8908 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8910
8911 // If we've not seen one yet, we don't know.
8913}
8914
8915static std::string charUnitsToString(CharUnits CU) {
8916 return llvm::itostr(CU.getQuantity());
8917}
8918
8919/// getObjCEncodingForBlock - Return the encoded type for this block
8920/// declaration.
8922 std::string S;
8923
8924 const BlockDecl *Decl = Expr->getBlockDecl();
8925 QualType BlockTy =
8927 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8928 // Encode result type.
8929 if (getLangOpts().EncodeExtendedBlockSig)
8931 true /*Extended*/);
8932 else
8933 getObjCEncodingForType(BlockReturnTy, S);
8934 // Compute size of all parameters.
8935 // Start with computing size of a pointer in number of bytes.
8936 // FIXME: There might(should) be a better way of doing this computation!
8938 CharUnits ParmOffset = PtrSize;
8939 for (auto *PI : Decl->parameters()) {
8940 QualType PType = PI->getType();
8942 if (sz.isZero())
8943 continue;
8944 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8945 ParmOffset += sz;
8946 }
8947 // Size of the argument frame
8948 S += charUnitsToString(ParmOffset);
8949 // Block pointer and offset.
8950 S += "@?0";
8951
8952 // Argument types.
8953 ParmOffset = PtrSize;
8954 for (auto *PVDecl : Decl->parameters()) {
8955 QualType PType = PVDecl->getOriginalType();
8956 if (const auto *AT =
8957 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8958 // Use array's original type only if it has known number of
8959 // elements.
8960 if (!isa<ConstantArrayType>(AT))
8961 PType = PVDecl->getType();
8962 } else if (PType->isFunctionType())
8963 PType = PVDecl->getType();
8964 if (getLangOpts().EncodeExtendedBlockSig)
8966 S, true /*Extended*/);
8967 else
8968 getObjCEncodingForType(PType, S);
8969 S += charUnitsToString(ParmOffset);
8970 ParmOffset += getObjCEncodingTypeSize(PType);
8971 }
8972
8973 return S;
8974}
8975
8976std::string
8978 std::string S;
8979 // Encode result type.
8980 getObjCEncodingForType(Decl->getReturnType(), S);
8981 CharUnits ParmOffset;
8982 // Compute size of all parameters.
8983 for (auto *PI : Decl->parameters()) {
8984 QualType PType = PI->getType();
8986 if (sz.isZero())
8987 continue;
8988
8989 assert(sz.isPositive() &&
8990 "getObjCEncodingForFunctionDecl - Incomplete param type");
8991 ParmOffset += sz;
8992 }
8993 S += charUnitsToString(ParmOffset);
8994 ParmOffset = CharUnits::Zero();
8995
8996 // Argument types.
8997 for (auto *PVDecl : Decl->parameters()) {
8998 QualType PType = PVDecl->getOriginalType();
8999 if (const auto *AT =
9000 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9001 // Use array's original type only if it has known number of
9002 // elements.
9003 if (!isa<ConstantArrayType>(AT))
9004 PType = PVDecl->getType();
9005 } else if (PType->isFunctionType())
9006 PType = PVDecl->getType();
9007 getObjCEncodingForType(PType, S);
9008 S += charUnitsToString(ParmOffset);
9009 ParmOffset += getObjCEncodingTypeSize(PType);
9010 }
9011
9012 return S;
9013}
9014
9015/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9016/// method parameter or return type. If Extended, include class names and
9017/// block object types.
9019 QualType T, std::string& S,
9020 bool Extended) const {
9021 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9023 // Encode parameter type.
9024 ObjCEncOptions Options = ObjCEncOptions()
9025 .setExpandPointedToStructures()
9026 .setExpandStructures()
9027 .setIsOutermostType();
9028 if (Extended)
9029 Options.setEncodeBlockParameters().setEncodeClassNames();
9030 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9031}
9032
9033/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9034/// declaration.
9036 bool Extended) const {
9037 // FIXME: This is not very efficient.
9038 // Encode return type.
9039 std::string S;
9040 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9041 Decl->getReturnType(), S, Extended);
9042 // Compute size of all parameters.
9043 // Start with computing size of a pointer in number of bytes.
9044 // FIXME: There might(should) be a better way of doing this computation!
9046 // The first two arguments (self and _cmd) are pointers; account for
9047 // their size.
9048 CharUnits ParmOffset = 2 * PtrSize;
9049 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9050 E = Decl->sel_param_end(); PI != E; ++PI) {
9051 QualType PType = (*PI)->getType();
9053 if (sz.isZero())
9054 continue;
9055
9056 assert(sz.isPositive() &&
9057 "getObjCEncodingForMethodDecl - Incomplete param type");
9058 ParmOffset += sz;
9059 }
9060 S += charUnitsToString(ParmOffset);
9061 S += "@0:";
9062 S += charUnitsToString(PtrSize);
9063
9064 // Argument types.
9065 ParmOffset = 2 * PtrSize;
9066 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9067 E = Decl->sel_param_end(); PI != E; ++PI) {
9068 const ParmVarDecl *PVDecl = *PI;
9069 QualType PType = PVDecl->getOriginalType();
9070 if (const auto *AT =
9071 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9072 // Use array's original type only if it has known number of
9073 // elements.
9074 if (!isa<ConstantArrayType>(AT))
9075 PType = PVDecl->getType();
9076 } else if (PType->isFunctionType())
9077 PType = PVDecl->getType();
9079 PType, S, Extended);
9080 S += charUnitsToString(ParmOffset);
9081 ParmOffset += getObjCEncodingTypeSize(PType);
9082 }
9083
9084 return S;
9085}
9086
9089 const ObjCPropertyDecl *PD,
9090 const Decl *Container) const {
9091 if (!Container)
9092 return nullptr;
9093 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9094 for (auto *PID : CID->property_impls())
9095 if (PID->getPropertyDecl() == PD)
9096 return PID;
9097 } else {
9098 const auto *OID = cast<ObjCImplementationDecl>(Container);
9099 for (auto *PID : OID->property_impls())
9100 if (PID->getPropertyDecl() == PD)
9101 return PID;
9102 }
9103 return nullptr;
9104}
9105
9106/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9107/// property declaration. If non-NULL, Container must be either an
9108/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9109/// NULL when getting encodings for protocol properties.
9110/// Property attributes are stored as a comma-delimited C string. The simple
9111/// attributes readonly and bycopy are encoded as single characters. The
9112/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9113/// encoded as single characters, followed by an identifier. Property types
9114/// are also encoded as a parametrized attribute. The characters used to encode
9115/// these attributes are defined by the following enumeration:
9116/// @code
9117/// enum PropertyAttributes {
9118/// kPropertyReadOnly = 'R', // property is read-only.
9119/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9120/// kPropertyByref = '&', // property is a reference to the value last assigned
9121/// kPropertyDynamic = 'D', // property is dynamic
9122/// kPropertyGetter = 'G', // followed by getter selector name
9123/// kPropertySetter = 'S', // followed by setter selector name
9124/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9125/// kPropertyType = 'T' // followed by old-style type encoding.
9126/// kPropertyWeak = 'W' // 'weak' property
9127/// kPropertyStrong = 'P' // property GC'able
9128/// kPropertyNonAtomic = 'N' // property non-atomic
9129/// kPropertyOptional = '?' // property optional
9130/// };
9131/// @endcode
9132std::string
9134 const Decl *Container) const {
9135 // Collect information from the property implementation decl(s).
9136 bool Dynamic = false;
9137 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9138
9139 if (ObjCPropertyImplDecl *PropertyImpDecl =
9141 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9142 Dynamic = true;
9143 else
9144 SynthesizePID = PropertyImpDecl;
9145 }
9146
9147 // FIXME: This is not very efficient.
9148 std::string S = "T";
9149
9150 // Encode result type.
9151 // GCC has some special rules regarding encoding of properties which
9152 // closely resembles encoding of ivars.
9154
9155 if (PD->isOptional())
9156 S += ",?";
9157
9158 if (PD->isReadOnly()) {
9159 S += ",R";
9161 S += ",C";
9163 S += ",&";
9165 S += ",W";
9166 } else {
9167 switch (PD->getSetterKind()) {
9168 case ObjCPropertyDecl::Assign: break;
9169 case ObjCPropertyDecl::Copy: S += ",C"; break;
9170 case ObjCPropertyDecl::Retain: S += ",&"; break;
9171 case ObjCPropertyDecl::Weak: S += ",W"; break;
9172 }
9173 }
9174
9175 // It really isn't clear at all what this means, since properties
9176 // are "dynamic by default".
9177 if (Dynamic)
9178 S += ",D";
9179
9181 S += ",N";
9182
9184 S += ",G";
9185 S += PD->getGetterName().getAsString();
9186 }
9187
9189 S += ",S";
9190 S += PD->getSetterName().getAsString();
9191 }
9192
9193 if (SynthesizePID) {
9194 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9195 S += ",V";
9196 S += OID->getNameAsString();
9197 }
9198
9199 // FIXME: OBJCGC: weak & strong
9200 return S;
9201}
9202
9203/// getLegacyIntegralTypeEncoding -
9204/// Another legacy compatibility encoding: 32-bit longs are encoded as
9205/// 'l' or 'L' , but not always. For typedefs, we need to use
9206/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9208 if (PointeeTy->getAs<TypedefType>()) {
9209 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9210 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9211 PointeeTy = UnsignedIntTy;
9212 else
9213 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9214 PointeeTy = IntTy;
9215 }
9216 }
9217}
9218
9220 const FieldDecl *Field,
9221 QualType *NotEncodedT) const {
9222 // We follow the behavior of gcc, expanding structures which are
9223 // directly pointed to, and expanding embedded structures. Note that
9224 // these rules are sufficient to prevent recursive encoding of the
9225 // same type.
9226 getObjCEncodingForTypeImpl(T, S,
9227 ObjCEncOptions()
9228 .setExpandPointedToStructures()
9229 .setExpandStructures()
9230 .setIsOutermostType(),
9231 Field, NotEncodedT);
9232}
9233
9235 std::string& S) const {
9236 // Encode result type.
9237 // GCC has some special rules regarding encoding of properties which
9238 // closely resembles encoding of ivars.
9239 getObjCEncodingForTypeImpl(T, S,
9240 ObjCEncOptions()
9241 .setExpandPointedToStructures()
9242 .setExpandStructures()
9243 .setIsOutermostType()
9244 .setEncodingProperty(),
9245 /*Field=*/nullptr);
9246}
9247
9249 const BuiltinType *BT) {
9251 switch (kind) {
9252 case BuiltinType::Void: return 'v';
9253 case BuiltinType::Bool: return 'B';
9254 case BuiltinType::Char8:
9255 case BuiltinType::Char_U:
9256 case BuiltinType::UChar: return 'C';
9257 case BuiltinType::Char16:
9258 case BuiltinType::UShort: return 'S';
9259 case BuiltinType::Char32:
9260 case BuiltinType::UInt: return 'I';
9261 case BuiltinType::ULong:
9262 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9263 case BuiltinType::UInt128: return 'T';
9264 case BuiltinType::ULongLong: return 'Q';
9265 case BuiltinType::Char_S:
9266 case BuiltinType::SChar: return 'c';
9267 case BuiltinType::Short: return 's';
9268 case BuiltinType::WChar_S:
9269 case BuiltinType::WChar_U:
9270 case BuiltinType::Int: return 'i';
9271 case BuiltinType::Long:
9272 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9273 case BuiltinType::LongLong: return 'q';
9274 case BuiltinType::Int128: return 't';
9275 case BuiltinType::Float: return 'f';
9276 case BuiltinType::Double: return 'd';
9277 case BuiltinType::LongDouble: return 'D';
9278 case BuiltinType::NullPtr: return '*'; // like char*
9279
9280 case BuiltinType::BFloat16:
9281 case BuiltinType::Float16:
9282 case BuiltinType::Float128:
9283 case BuiltinType::Ibm128:
9284 case BuiltinType::Half:
9285 case BuiltinType::ShortAccum:
9286 case BuiltinType::Accum:
9287 case BuiltinType::LongAccum:
9288 case BuiltinType::UShortAccum:
9289 case BuiltinType::UAccum:
9290 case BuiltinType::ULongAccum:
9291 case BuiltinType::ShortFract:
9292 case BuiltinType::Fract:
9293 case BuiltinType::LongFract:
9294 case BuiltinType::UShortFract:
9295 case BuiltinType::UFract:
9296 case BuiltinType::ULongFract:
9297 case BuiltinType::SatShortAccum:
9298 case BuiltinType::SatAccum:
9299 case BuiltinType::SatLongAccum:
9300 case BuiltinType::SatUShortAccum:
9301 case BuiltinType::SatUAccum:
9302 case BuiltinType::SatULongAccum:
9303 case BuiltinType::SatShortFract:
9304 case BuiltinType::SatFract:
9305 case BuiltinType::SatLongFract:
9306 case BuiltinType::SatUShortFract:
9307 case BuiltinType::SatUFract:
9308 case BuiltinType::SatULongFract:
9309 // FIXME: potentially need @encodes for these!
9310 return ' ';
9311
9312#define SVE_TYPE(Name, Id, SingletonId) \
9313 case BuiltinType::Id:
9314#include "clang/Basic/AArch64ACLETypes.def"
9315#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9316#include "clang/Basic/RISCVVTypes.def"
9317#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9318#include "clang/Basic/WebAssemblyReferenceTypes.def"
9319#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9320#include "clang/Basic/AMDGPUTypes.def"
9321#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9322#include "clang/Basic/SPIRVTypes.def"
9323 {
9324 DiagnosticsEngine &Diags = C->getDiagnostics();
9325 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9326 << QualType(BT, 0);
9327 return ' ';
9328 }
9329
9330 case BuiltinType::ObjCId:
9331 case BuiltinType::ObjCClass:
9332 case BuiltinType::ObjCSel:
9333 llvm_unreachable("@encoding ObjC primitive type");
9334
9335 // OpenCL and placeholder types don't need @encodings.
9336#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9337 case BuiltinType::Id:
9338#include "clang/Basic/OpenCLImageTypes.def"
9339#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9340 case BuiltinType::Id:
9341#include "clang/Basic/OpenCLExtensionTypes.def"
9342 case BuiltinType::OCLEvent:
9343 case BuiltinType::OCLClkEvent:
9344 case BuiltinType::OCLQueue:
9345 case BuiltinType::OCLReserveID:
9346 case BuiltinType::OCLSampler:
9347 case BuiltinType::Dependent:
9348 case BuiltinType::MetaInfo:
9349#define PPC_VECTOR_TYPE(Name, Id, Size) \
9350 case BuiltinType::Id:
9351#include "clang/Basic/PPCTypes.def"
9352#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9353#include "clang/Basic/HLSLIntangibleTypes.def"
9354#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9355#include "clang/Basic/HLSLPackedTypes.def"
9356#define BUILTIN_TYPE(KIND, ID)
9357#define PLACEHOLDER_TYPE(KIND, ID) \
9358 case BuiltinType::KIND:
9359#include "clang/AST/BuiltinTypes.def"
9360 llvm_unreachable("invalid builtin type for @encode");
9361 }
9362 llvm_unreachable("invalid BuiltinType::Kind value");
9363}
9364
9365static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9367
9368 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9369 if (!Enum->isFixed())
9370 return 'i';
9371
9372 // The encoding of a fixed enum type matches its fixed underlying type.
9373 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9375}
9376
9377static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9378 QualType T, const FieldDecl *FD) {
9379 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9380 S += 'b';
9381 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9382 // The GNU runtime requires more information; bitfields are encoded as b,
9383 // then the offset (in bits) of the first element, then the type of the
9384 // bitfield, then the size in bits. For example, in this structure:
9385 //
9386 // struct
9387 // {
9388 // int integer;
9389 // int flags:2;
9390 // };
9391 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9392 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9393 // information is not especially sensible, but we're stuck with it for
9394 // compatibility with GCC, although providing it breaks anything that
9395 // actually uses runtime introspection and wants to work on both runtimes...
9396 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9397 uint64_t Offset;
9398
9399 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9400 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9401 } else {
9402 const RecordDecl *RD = FD->getParent();
9403 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9404 Offset = RL.getFieldOffset(FD->getFieldIndex());
9405 }
9406
9407 S += llvm::utostr(Offset);
9408
9409 if (const auto *ET = T->getAsCanonical<EnumType>())
9410 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9411 else {
9412 const auto *BT = T->castAs<BuiltinType>();
9413 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9414 }
9415 }
9416 S += llvm::utostr(FD->getBitWidthValue());
9417}
9418
9419// Helper function for determining whether the encoded type string would include
9420// a template specialization type.
9422 bool VisitBasesAndFields) {
9423 T = T->getBaseElementTypeUnsafe();
9424
9425 if (auto *PT = T->getAs<PointerType>())
9427 PT->getPointeeType().getTypePtr(), false);
9428
9429 auto *CXXRD = T->getAsCXXRecordDecl();
9430
9431 if (!CXXRD)
9432 return false;
9433
9435 return true;
9436
9437 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9438 return false;
9439
9440 for (const auto &B : CXXRD->bases())
9441 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9442 true))
9443 return true;
9444
9445 for (auto *FD : CXXRD->fields())
9446 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9447 true))
9448 return true;
9449
9450 return false;
9451}
9452
9453// FIXME: Use SmallString for accumulating string.
9454void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9455 const ObjCEncOptions Options,
9456 const FieldDecl *FD,
9457 QualType *NotEncodedT) const {
9459 switch (CT->getTypeClass()) {
9460 case Type::Builtin:
9461 case Type::Enum:
9462 if (FD && FD->isBitField())
9463 return EncodeBitField(this, S, T, FD);
9464 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9465 S += getObjCEncodingForPrimitiveType(this, BT);
9466 else
9467 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9468 return;
9469
9470 case Type::Complex:
9471 S += 'j';
9472 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9473 ObjCEncOptions(),
9474 /*Field=*/nullptr);
9475 return;
9476
9477 case Type::Atomic:
9478 S += 'A';
9479 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9480 ObjCEncOptions(),
9481 /*Field=*/nullptr);
9482 return;
9483
9484 // encoding for pointer or reference types.
9485 case Type::Pointer:
9486 case Type::LValueReference:
9487 case Type::RValueReference: {
9488 QualType PointeeTy;
9489 if (isa<PointerType>(CT)) {
9490 const auto *PT = T->castAs<PointerType>();
9491 if (PT->isObjCSelType()) {
9492 S += ':';
9493 return;
9494 }
9495 PointeeTy = PT->getPointeeType();
9496 } else {
9497 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9498 }
9499
9500 bool isReadOnly = false;
9501 // For historical/compatibility reasons, the read-only qualifier of the
9502 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9503 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9504 // Also, do not emit the 'r' for anything but the outermost type!
9505 if (T->getAs<TypedefType>()) {
9506 if (Options.IsOutermostType() && T.isConstQualified()) {
9507 isReadOnly = true;
9508 S += 'r';
9509 }
9510 } else if (Options.IsOutermostType()) {
9511 QualType P = PointeeTy;
9512 while (auto PT = P->getAs<PointerType>())
9513 P = PT->getPointeeType();
9514 if (P.isConstQualified()) {
9515 isReadOnly = true;
9516 S += 'r';
9517 }
9518 }
9519 if (isReadOnly) {
9520 // Another legacy compatibility encoding. Some ObjC qualifier and type
9521 // combinations need to be rearranged.
9522 // Rewrite "in const" from "nr" to "rn"
9523 if (StringRef(S).ends_with("nr"))
9524 S.replace(S.end()-2, S.end(), "rn");
9525 }
9526
9527 if (PointeeTy->isCharType()) {
9528 // char pointer types should be encoded as '*' unless it is a
9529 // type that has been typedef'd to 'BOOL'.
9530 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9531 S += '*';
9532 return;
9533 }
9534 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9535 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9536 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9537 if (II == &Idents.get("objc_class")) {
9538 S += '#';
9539 return;
9540 }
9541 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9542 if (II == &Idents.get("objc_object")) {
9543 S += '@';
9544 return;
9545 }
9546 // If the encoded string for the class includes template names, just emit
9547 // "^v" for pointers to the class.
9548 if (getLangOpts().CPlusPlus &&
9549 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9551 RTy, Options.ExpandPointedToStructures()))) {
9552 S += "^v";
9553 return;
9554 }
9555 // fall through...
9556 }
9557 S += '^';
9559
9560 ObjCEncOptions NewOptions;
9561 if (Options.ExpandPointedToStructures())
9562 NewOptions.setExpandStructures();
9563 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9564 /*Field=*/nullptr, NotEncodedT);
9565 return;
9566 }
9567
9568 case Type::ConstantArray:
9569 case Type::IncompleteArray:
9570 case Type::VariableArray: {
9571 const auto *AT = cast<ArrayType>(CT);
9572
9573 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9574 // Incomplete arrays are encoded as a pointer to the array element.
9575 S += '^';
9576
9577 getObjCEncodingForTypeImpl(
9578 AT->getElementType(), S,
9579 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9580 } else {
9581 S += '[';
9582
9583 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9584 S += llvm::utostr(CAT->getZExtSize());
9585 else {
9586 //Variable length arrays are encoded as a regular array with 0 elements.
9588 "Unknown array type!");
9589 S += '0';
9590 }
9591
9592 getObjCEncodingForTypeImpl(
9593 AT->getElementType(), S,
9594 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9595 NotEncodedT);
9596 S += ']';
9597 }
9598 return;
9599 }
9600
9601 case Type::FunctionNoProto:
9602 case Type::FunctionProto:
9603 S += '?';
9604 return;
9605
9606 case Type::Record: {
9607 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9608 S += RDecl->isUnion() ? '(' : '{';
9609 // Anonymous structures print as '?'
9610 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9611 S += II->getName();
9612 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9613 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9614 llvm::raw_string_ostream OS(S);
9615 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9617 }
9618 } else {
9619 S += '?';
9620 }
9621 if (Options.ExpandStructures()) {
9622 S += '=';
9623 if (!RDecl->isUnion()) {
9624 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9625 } else {
9626 for (const auto *Field : RDecl->fields()) {
9627 if (FD) {
9628 S += '"';
9629 S += Field->getNameAsString();
9630 S += '"';
9631 }
9632
9633 // Special case bit-fields.
9634 if (Field->isBitField()) {
9635 getObjCEncodingForTypeImpl(Field->getType(), S,
9636 ObjCEncOptions().setExpandStructures(),
9637 Field);
9638 } else {
9639 QualType qt = Field->getType();
9641 getObjCEncodingForTypeImpl(
9642 qt, S,
9643 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9644 NotEncodedT);
9645 }
9646 }
9647 }
9648 }
9649 S += RDecl->isUnion() ? ')' : '}';
9650 return;
9651 }
9652
9653 case Type::BlockPointer: {
9654 const auto *BT = T->castAs<BlockPointerType>();
9655 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9656 if (Options.EncodeBlockParameters()) {
9657 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9658
9659 S += '<';
9660 // Block return type
9661 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9662 Options.forComponentType(), FD, NotEncodedT);
9663 // Block self
9664 S += "@?";
9665 // Block parameters
9666 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9667 for (const auto &I : FPT->param_types())
9668 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9669 NotEncodedT);
9670 }
9671 S += '>';
9672 }
9673 return;
9674 }
9675
9676 case Type::ObjCObject: {
9677 // hack to match legacy encoding of *id and *Class
9678 QualType Ty = getObjCObjectPointerType(CT);
9679 if (Ty->isObjCIdType()) {
9680 S += "{objc_object=}";
9681 return;
9682 }
9683 else if (Ty->isObjCClassType()) {
9684 S += "{objc_class=}";
9685 return;
9686 }
9687 // TODO: Double check to make sure this intentionally falls through.
9688 [[fallthrough]];
9689 }
9690
9691 case Type::ObjCInterface: {
9692 // Ignore protocol qualifiers when mangling at this level.
9693 // @encode(class_name)
9694 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9695 S += '{';
9696 S += OI->getObjCRuntimeNameAsString();
9697 if (Options.ExpandStructures()) {
9698 S += '=';
9699 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9700 DeepCollectObjCIvars(OI, true, Ivars);
9701 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9702 const FieldDecl *Field = Ivars[i];
9703 if (Field->isBitField())
9704 getObjCEncodingForTypeImpl(Field->getType(), S,
9705 ObjCEncOptions().setExpandStructures(),
9706 Field);
9707 else
9708 getObjCEncodingForTypeImpl(Field->getType(), S,
9709 ObjCEncOptions().setExpandStructures(), FD,
9710 NotEncodedT);
9711 }
9712 }
9713 S += '}';
9714 return;
9715 }
9716
9717 case Type::ObjCObjectPointer: {
9718 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9719 if (OPT->isObjCIdType()) {
9720 S += '@';
9721 return;
9722 }
9723
9724 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9725 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9726 // Since this is a binary compatibility issue, need to consult with
9727 // runtime folks. Fortunately, this is a *very* obscure construct.
9728 S += '#';
9729 return;
9730 }
9731
9732 if (OPT->isObjCQualifiedIdType()) {
9733 getObjCEncodingForTypeImpl(
9734 getObjCIdType(), S,
9735 Options.keepingOnly(ObjCEncOptions()
9736 .setExpandPointedToStructures()
9737 .setExpandStructures()),
9738 FD);
9739 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9740 // Note that we do extended encoding of protocol qualifier list
9741 // Only when doing ivar or property encoding.
9742 S += '"';
9743 for (const auto *I : OPT->quals()) {
9744 S += '<';
9745 S += I->getObjCRuntimeNameAsString();
9746 S += '>';
9747 }
9748 S += '"';
9749 }
9750 return;
9751 }
9752
9753 S += '@';
9754 if (OPT->getInterfaceDecl() &&
9755 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9756 S += '"';
9757 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9758 for (const auto *I : OPT->quals()) {
9759 S += '<';
9760 S += I->getObjCRuntimeNameAsString();
9761 S += '>';
9762 }
9763 S += '"';
9764 }
9765 return;
9766 }
9767
9768 // gcc just blithely ignores member pointers.
9769 // FIXME: we should do better than that. 'M' is available.
9770 case Type::MemberPointer:
9771 // This matches gcc's encoding, even though technically it is insufficient.
9772 //FIXME. We should do a better job than gcc.
9773 case Type::Vector:
9774 case Type::ExtVector:
9775 // Until we have a coherent encoding of these three types, issue warning.
9776 if (NotEncodedT)
9777 *NotEncodedT = T;
9778 return;
9779
9780 case Type::ConstantMatrix:
9781 if (NotEncodedT)
9782 *NotEncodedT = T;
9783 return;
9784
9785 case Type::BitInt:
9786 if (NotEncodedT)
9787 *NotEncodedT = T;
9788 return;
9789
9790 // We could see an undeduced auto type here during error recovery.
9791 // Just ignore it.
9792 case Type::Auto:
9793 case Type::DeducedTemplateSpecialization:
9794 return;
9795
9796 case Type::HLSLAttributedResource:
9797 case Type::HLSLInlineSpirv:
9798 case Type::OverflowBehavior:
9799 llvm_unreachable("unexpected type");
9800
9801 case Type::ArrayParameter:
9802 case Type::Pipe:
9803#define ABSTRACT_TYPE(KIND, BASE)
9804#define TYPE(KIND, BASE)
9805#define DEPENDENT_TYPE(KIND, BASE) \
9806 case Type::KIND:
9807#define NON_CANONICAL_TYPE(KIND, BASE) \
9808 case Type::KIND:
9809#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9810 case Type::KIND:
9811#include "clang/AST/TypeNodes.inc"
9812 llvm_unreachable("@encode for dependent type!");
9813 }
9814 llvm_unreachable("bad type kind!");
9815}
9816
9817void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9818 std::string &S,
9819 const FieldDecl *FD,
9820 bool includeVBases,
9821 QualType *NotEncodedT) const {
9822 assert(RDecl && "Expected non-null RecordDecl");
9823 assert(!RDecl->isUnion() && "Should not be called for unions");
9824 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9825 return;
9826
9827 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9828 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9829 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9830
9831 if (CXXRec) {
9832 for (const auto &BI : CXXRec->bases()) {
9833 if (!BI.isVirtual()) {
9834 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9835 if (base->isEmpty())
9836 continue;
9837 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9838 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9839 std::make_pair(offs, base));
9840 }
9841 }
9842 }
9843
9844 for (FieldDecl *Field : RDecl->fields()) {
9845 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9846 continue;
9847 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9848 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9849 std::make_pair(offs, Field));
9850 }
9851
9852 if (CXXRec && includeVBases) {
9853 for (const auto &BI : CXXRec->vbases()) {
9854 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9855 if (base->isEmpty())
9856 continue;
9857 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9858 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9859 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9860 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9861 std::make_pair(offs, base));
9862 }
9863 }
9864
9865 CharUnits size;
9866 if (CXXRec) {
9867 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9868 } else {
9869 size = layout.getSize();
9870 }
9871
9872#ifndef NDEBUG
9873 uint64_t CurOffs = 0;
9874#endif
9875 std::multimap<uint64_t, NamedDecl *>::iterator
9876 CurLayObj = FieldOrBaseOffsets.begin();
9877
9878 if (CXXRec && CXXRec->isDynamicClass() &&
9879 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9880 if (FD) {
9881 S += "\"_vptr$";
9882 std::string recname = CXXRec->getNameAsString();
9883 if (recname.empty()) recname = "?";
9884 S += recname;
9885 S += '"';
9886 }
9887 S += "^^?";
9888#ifndef NDEBUG
9889 CurOffs += getTypeSize(VoidPtrTy);
9890#endif
9891 }
9892
9893 if (!RDecl->hasFlexibleArrayMember()) {
9894 // Mark the end of the structure.
9895 uint64_t offs = toBits(size);
9896 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9897 std::make_pair(offs, nullptr));
9898 }
9899
9900 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9901#ifndef NDEBUG
9902 assert(CurOffs <= CurLayObj->first);
9903 if (CurOffs < CurLayObj->first) {
9904 uint64_t padding = CurLayObj->first - CurOffs;
9905 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9906 // packing/alignment of members is different that normal, in which case
9907 // the encoding will be out-of-sync with the real layout.
9908 // If the runtime switches to just consider the size of types without
9909 // taking into account alignment, we could make padding explicit in the
9910 // encoding (e.g. using arrays of chars). The encoding strings would be
9911 // longer then though.
9912 CurOffs += padding;
9913 }
9914#endif
9915
9916 NamedDecl *dcl = CurLayObj->second;
9917 if (!dcl)
9918 break; // reached end of structure.
9919
9920 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9921 // We expand the bases without their virtual bases since those are going
9922 // in the initial structure. Note that this differs from gcc which
9923 // expands virtual bases each time one is encountered in the hierarchy,
9924 // making the encoding type bigger than it really is.
9925 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9926 NotEncodedT);
9927 assert(!base->isEmpty());
9928#ifndef NDEBUG
9929 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9930#endif
9931 } else {
9932 const auto *field = cast<FieldDecl>(dcl);
9933 if (FD) {
9934 S += '"';
9935 S += field->getNameAsString();
9936 S += '"';
9937 }
9938
9939 if (field->isBitField()) {
9940 EncodeBitField(this, S, field->getType(), field);
9941#ifndef NDEBUG
9942 CurOffs += field->getBitWidthValue();
9943#endif
9944 } else {
9945 QualType qt = field->getType();
9947 getObjCEncodingForTypeImpl(
9948 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9949 FD, NotEncodedT);
9950#ifndef NDEBUG
9951 CurOffs += getTypeSize(field->getType());
9952#endif
9953 }
9954 }
9955 }
9956}
9957
9959 std::string& S) const {
9960 if (QT & Decl::OBJC_TQ_In)
9961 S += 'n';
9962 if (QT & Decl::OBJC_TQ_Inout)
9963 S += 'N';
9964 if (QT & Decl::OBJC_TQ_Out)
9965 S += 'o';
9966 if (QT & Decl::OBJC_TQ_Bycopy)
9967 S += 'O';
9968 if (QT & Decl::OBJC_TQ_Byref)
9969 S += 'R';
9970 if (QT & Decl::OBJC_TQ_Oneway)
9971 S += 'V';
9972}
9973
9975 if (!ObjCIdDecl) {
9978 ObjCIdDecl = buildImplicitTypedef(T, "id");
9979 }
9980 return ObjCIdDecl;
9981}
9982
9984 if (!ObjCSelDecl) {
9986 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9987 }
9988 return ObjCSelDecl;
9989}
9990
9992 if (!ObjCClassDecl) {
9995 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9996 }
9997 return ObjCClassDecl;
9998}
9999
10001 if (!ObjCProtocolClassDecl) {
10002 ObjCProtocolClassDecl
10005 &Idents.get("Protocol"),
10006 /*typeParamList=*/nullptr,
10007 /*PrevDecl=*/nullptr,
10008 SourceLocation(), true);
10009 }
10010
10011 return ObjCProtocolClassDecl;
10012}
10013
10015 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10016 return PointerAuthQualifier();
10018 getLangOpts().PointerAuthObjcInterfaceSelKey,
10019 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10021 /*isIsaPointer=*/false,
10022 /*authenticatesNullValues=*/false);
10023}
10024
10025//===----------------------------------------------------------------------===//
10026// __builtin_va_list Construction Functions
10027//===----------------------------------------------------------------------===//
10028
10030 StringRef Name) {
10031 // typedef char* __builtin[_ms]_va_list;
10032 QualType T = Context->getPointerType(Context->CharTy);
10033 return Context->buildImplicitTypedef(T, Name);
10034}
10035
10037 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10038}
10039
10041 // typedef char *__builtin_zos_va_list[2];
10042 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10043 QualType T = Context->getPointerType(Context->CharTy);
10044 QualType ArrayType = Context->getConstantArrayType(
10045 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10046 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10047}
10048
10050 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10051}
10052
10054 // typedef void* __builtin_va_list;
10055 QualType T = Context->getPointerType(Context->VoidTy);
10056 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10057}
10058
10059static TypedefDecl *
10061 // struct __va_list
10062 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10063 if (Context->getLangOpts().CPlusPlus) {
10064 // namespace std { struct __va_list {
10065 auto *NS = NamespaceDecl::Create(
10066 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10067 /*Inline=*/false, SourceLocation(), SourceLocation(),
10068 &Context->Idents.get("std"),
10069 /*PrevDecl=*/nullptr, /*Nested=*/false);
10070 NS->setImplicit();
10072 }
10073
10074 VaListTagDecl->startDefinition();
10075
10076 const size_t NumFields = 5;
10077 QualType FieldTypes[NumFields];
10078 const char *FieldNames[NumFields];
10079
10080 // void *__stack;
10081 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10082 FieldNames[0] = "__stack";
10083
10084 // void *__gr_top;
10085 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10086 FieldNames[1] = "__gr_top";
10087
10088 // void *__vr_top;
10089 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10090 FieldNames[2] = "__vr_top";
10091
10092 // int __gr_offs;
10093 FieldTypes[3] = Context->IntTy;
10094 FieldNames[3] = "__gr_offs";
10095
10096 // int __vr_offs;
10097 FieldTypes[4] = Context->IntTy;
10098 FieldNames[4] = "__vr_offs";
10099
10100 // Create fields
10101 for (unsigned i = 0; i < NumFields; ++i) {
10102 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10106 &Context->Idents.get(FieldNames[i]),
10107 FieldTypes[i], /*TInfo=*/nullptr,
10108 /*BitWidth=*/nullptr,
10109 /*Mutable=*/false,
10110 ICIS_NoInit);
10111 Field->setAccess(AS_public);
10112 VaListTagDecl->addDecl(Field);
10113 }
10114 VaListTagDecl->completeDefinition();
10115 Context->VaListTagDecl = VaListTagDecl;
10116 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10117
10118 // } __builtin_va_list;
10119 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10120}
10121
10123 // typedef struct __va_list_tag {
10125
10126 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10127 VaListTagDecl->startDefinition();
10128
10129 const size_t NumFields = 5;
10130 QualType FieldTypes[NumFields];
10131 const char *FieldNames[NumFields];
10132
10133 // unsigned char gpr;
10134 FieldTypes[0] = Context->UnsignedCharTy;
10135 FieldNames[0] = "gpr";
10136
10137 // unsigned char fpr;
10138 FieldTypes[1] = Context->UnsignedCharTy;
10139 FieldNames[1] = "fpr";
10140
10141 // unsigned short reserved;
10142 FieldTypes[2] = Context->UnsignedShortTy;
10143 FieldNames[2] = "reserved";
10144
10145 // void* overflow_arg_area;
10146 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10147 FieldNames[3] = "overflow_arg_area";
10148
10149 // void* reg_save_area;
10150 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10151 FieldNames[4] = "reg_save_area";
10152
10153 // Create fields
10154 for (unsigned i = 0; i < NumFields; ++i) {
10155 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10158 &Context->Idents.get(FieldNames[i]),
10159 FieldTypes[i], /*TInfo=*/nullptr,
10160 /*BitWidth=*/nullptr,
10161 /*Mutable=*/false,
10162 ICIS_NoInit);
10163 Field->setAccess(AS_public);
10164 VaListTagDecl->addDecl(Field);
10165 }
10166 VaListTagDecl->completeDefinition();
10167 Context->VaListTagDecl = VaListTagDecl;
10168 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10169
10170 // } __va_list_tag;
10171 TypedefDecl *VaListTagTypedefDecl =
10172 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10173
10174 QualType VaListTagTypedefType =
10175 Context->getTypedefType(ElaboratedTypeKeyword::None,
10176 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10177
10178 // typedef __va_list_tag __builtin_va_list[1];
10179 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10180 QualType VaListTagArrayType = Context->getConstantArrayType(
10181 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10182 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10183}
10184
10185static TypedefDecl *
10187 // struct __va_list_tag {
10189 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10190 VaListTagDecl->startDefinition();
10191
10192 const size_t NumFields = 4;
10193 QualType FieldTypes[NumFields];
10194 const char *FieldNames[NumFields];
10195
10196 // unsigned gp_offset;
10197 FieldTypes[0] = Context->UnsignedIntTy;
10198 FieldNames[0] = "gp_offset";
10199
10200 // unsigned fp_offset;
10201 FieldTypes[1] = Context->UnsignedIntTy;
10202 FieldNames[1] = "fp_offset";
10203
10204 // void* overflow_arg_area;
10205 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10206 FieldNames[2] = "overflow_arg_area";
10207
10208 // void* reg_save_area;
10209 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10210 FieldNames[3] = "reg_save_area";
10211
10212 // Create fields
10213 for (unsigned i = 0; i < NumFields; ++i) {
10214 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10218 &Context->Idents.get(FieldNames[i]),
10219 FieldTypes[i], /*TInfo=*/nullptr,
10220 /*BitWidth=*/nullptr,
10221 /*Mutable=*/false,
10222 ICIS_NoInit);
10223 Field->setAccess(AS_public);
10224 VaListTagDecl->addDecl(Field);
10225 }
10226 VaListTagDecl->completeDefinition();
10227 Context->VaListTagDecl = VaListTagDecl;
10228 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10229
10230 // };
10231
10232 // typedef struct __va_list_tag __builtin_va_list[1];
10233 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10234 QualType VaListTagArrayType = Context->getConstantArrayType(
10235 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10236 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10237}
10238
10239static TypedefDecl *
10241 // struct __va_list
10242 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10243 if (Context->getLangOpts().CPlusPlus) {
10244 // namespace std { struct __va_list {
10245 NamespaceDecl *NS;
10246 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10247 Context->getTranslationUnitDecl(),
10248 /*Inline=*/false, SourceLocation(),
10249 SourceLocation(), &Context->Idents.get("std"),
10250 /*PrevDecl=*/nullptr, /*Nested=*/false);
10251 NS->setImplicit();
10252 VaListDecl->setDeclContext(NS);
10253 }
10254
10255 VaListDecl->startDefinition();
10256
10257 // void * __ap;
10258 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10259 VaListDecl,
10262 &Context->Idents.get("__ap"),
10263 Context->getPointerType(Context->VoidTy),
10264 /*TInfo=*/nullptr,
10265 /*BitWidth=*/nullptr,
10266 /*Mutable=*/false,
10267 ICIS_NoInit);
10268 Field->setAccess(AS_public);
10269 VaListDecl->addDecl(Field);
10270
10271 // };
10272 VaListDecl->completeDefinition();
10273 Context->VaListTagDecl = VaListDecl;
10274
10275 // typedef struct __va_list __builtin_va_list;
10276 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10277 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10278}
10279
10280static TypedefDecl *
10282 // struct __va_list_tag {
10284 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10285 VaListTagDecl->startDefinition();
10286
10287 const size_t NumFields = 4;
10288 QualType FieldTypes[NumFields];
10289 const char *FieldNames[NumFields];
10290
10291 // long __gpr;
10292 FieldTypes[0] = Context->LongTy;
10293 FieldNames[0] = "__gpr";
10294
10295 // long __fpr;
10296 FieldTypes[1] = Context->LongTy;
10297 FieldNames[1] = "__fpr";
10298
10299 // void *__overflow_arg_area;
10300 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10301 FieldNames[2] = "__overflow_arg_area";
10302
10303 // void *__reg_save_area;
10304 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10305 FieldNames[3] = "__reg_save_area";
10306
10307 // Create fields
10308 for (unsigned i = 0; i < NumFields; ++i) {
10309 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10313 &Context->Idents.get(FieldNames[i]),
10314 FieldTypes[i], /*TInfo=*/nullptr,
10315 /*BitWidth=*/nullptr,
10316 /*Mutable=*/false,
10317 ICIS_NoInit);
10318 Field->setAccess(AS_public);
10319 VaListTagDecl->addDecl(Field);
10320 }
10321 VaListTagDecl->completeDefinition();
10322 Context->VaListTagDecl = VaListTagDecl;
10323 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10324
10325 // };
10326
10327 // typedef __va_list_tag __builtin_va_list[1];
10328 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10329 QualType VaListTagArrayType = Context->getConstantArrayType(
10330 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10331
10332 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10333}
10334
10336 // typedef struct __va_list_tag {
10338 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10339 VaListTagDecl->startDefinition();
10340
10341 const size_t NumFields = 3;
10342 QualType FieldTypes[NumFields];
10343 const char *FieldNames[NumFields];
10344
10345 // void *CurrentSavedRegisterArea;
10346 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10347 FieldNames[0] = "__current_saved_reg_area_pointer";
10348
10349 // void *SavedRegAreaEnd;
10350 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10351 FieldNames[1] = "__saved_reg_area_end_pointer";
10352
10353 // void *OverflowArea;
10354 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10355 FieldNames[2] = "__overflow_area_pointer";
10356
10357 // Create fields
10358 for (unsigned i = 0; i < NumFields; ++i) {
10360 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10361 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10362 /*TInfo=*/nullptr,
10363 /*BitWidth=*/nullptr,
10364 /*Mutable=*/false, ICIS_NoInit);
10365 Field->setAccess(AS_public);
10366 VaListTagDecl->addDecl(Field);
10367 }
10368 VaListTagDecl->completeDefinition();
10369 Context->VaListTagDecl = VaListTagDecl;
10370 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10371
10372 // } __va_list_tag;
10373 TypedefDecl *VaListTagTypedefDecl =
10374 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10375
10376 QualType VaListTagTypedefType =
10377 Context->getTypedefType(ElaboratedTypeKeyword::None,
10378 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10379
10380 // typedef __va_list_tag __builtin_va_list[1];
10381 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10382 QualType VaListTagArrayType = Context->getConstantArrayType(
10383 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10384
10385 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10386}
10387
10388static TypedefDecl *
10390 // typedef struct __va_list_tag {
10391 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10392
10393 VaListTagDecl->startDefinition();
10394
10395 // int* __va_stk;
10396 // int* __va_reg;
10397 // int __va_ndx;
10398 constexpr size_t NumFields = 3;
10399 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10400 Context->getPointerType(Context->IntTy),
10401 Context->IntTy};
10402 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10403
10404 // Create fields
10405 for (unsigned i = 0; i < NumFields; ++i) {
10408 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10409 /*BitWidth=*/nullptr,
10410 /*Mutable=*/false, ICIS_NoInit);
10411 Field->setAccess(AS_public);
10412 VaListTagDecl->addDecl(Field);
10413 }
10414 VaListTagDecl->completeDefinition();
10415 Context->VaListTagDecl = VaListTagDecl;
10416 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10417
10418 // } __va_list_tag;
10419 TypedefDecl *VaListTagTypedefDecl =
10420 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10421
10422 return VaListTagTypedefDecl;
10423}
10424
10427 switch (Kind) {
10429 return CreateCharPtrBuiltinVaListDecl(Context);
10431 return CreateVoidPtrBuiltinVaListDecl(Context);
10433 return CreateAArch64ABIBuiltinVaListDecl(Context);
10435 return CreatePowerABIBuiltinVaListDecl(Context);
10437 return CreateX86_64ABIBuiltinVaListDecl(Context);
10439 return CreateAAPCSABIBuiltinVaListDecl(Context);
10441 return CreateSystemZBuiltinVaListDecl(Context);
10443 return CreateHexagonBuiltinVaListDecl(Context);
10445 return CreateXtensaABIBuiltinVaListDecl(Context);
10446 }
10447
10448 llvm_unreachable("Unhandled __builtin_va_list type kind");
10449}
10450
10452 if (!BuiltinVaListDecl) {
10453 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10454 assert(BuiltinVaListDecl->isImplicit());
10455 }
10456
10457 return BuiltinVaListDecl;
10458}
10459
10461 // Force the creation of VaListTagDecl by building the __builtin_va_list
10462 // declaration.
10463 if (!VaListTagDecl)
10464 (void)getBuiltinVaListDecl();
10465
10466 return VaListTagDecl;
10467}
10468
10470 if (!BuiltinMSVaListDecl)
10471 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10472
10473 return BuiltinMSVaListDecl;
10474}
10475
10477 if (!BuiltinZOSVaListDecl)
10478 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10479
10480 return BuiltinZOSVaListDecl;
10481}
10482
10484 // Allow redecl custom type checking builtin for HLSL.
10485 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10486 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10487 return true;
10488 // Allow redecl custom type checking builtin for SPIR-V.
10489 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10490 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10491 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10492 return true;
10493 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10494}
10495
10497 assert(ObjCConstantStringType.isNull() &&
10498 "'NSConstantString' type already set!");
10499
10500 ObjCConstantStringType = getObjCInterfaceType(Decl);
10501}
10502
10503/// Retrieve the template name that corresponds to a non-empty
10504/// lookup.
10507 UnresolvedSetIterator End) const {
10508 unsigned size = End - Begin;
10509 assert(size > 1 && "set is not overloaded!");
10510
10511 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10512 size * sizeof(FunctionTemplateDecl*));
10513 auto *OT = new (memory) OverloadedTemplateStorage(size);
10514
10515 NamedDecl **Storage = OT->getStorage();
10516 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10517 NamedDecl *D = *I;
10518 assert(isa<FunctionTemplateDecl>(D) ||
10522 *Storage++ = D;
10523 }
10524
10525 return TemplateName(OT);
10526}
10527
10528/// Retrieve a template name representing an unqualified-id that has been
10529/// assumed to name a template for ADL purposes.
10531 auto *OT = new (*this) AssumedTemplateStorage(Name);
10532 return TemplateName(OT);
10533}
10534
10535/// Retrieve the template name that represents a qualified
10536/// template name such as \c std::vector.
10538 bool TemplateKeyword,
10539 TemplateName Template) const {
10540 assert(Template.getKind() == TemplateName::Template ||
10542
10543 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10544 assert(!Qualifier && "unexpected qualified template template parameter");
10545 assert(TemplateKeyword == false);
10546 return Template;
10547 }
10548
10549 // FIXME: Canonicalization?
10550 llvm::FoldingSetNodeID ID;
10551 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10552
10553 llvm::FoldingSetInsertToken Token;
10554 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10555 if (!QTN) {
10556 QTN = new (*this, alignof(QualifiedTemplateName))
10557 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10558 QualifiedTemplateNames.insert(QTN, Token);
10559 }
10560
10561 return TemplateName(QTN);
10562}
10563
10564/// Retrieve the template name that represents a dependent
10565/// template name such as \c MetaFun::template operator+.
10568 llvm::FoldingSetNodeID ID;
10569 S.Profile(ID);
10570
10571 llvm::FoldingSetInsertToken Token;
10572 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10573 return TemplateName(QTN);
10574
10576 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10577 DependentTemplateNames.insert(QTN, Token);
10578 return TemplateName(QTN);
10579}
10580
10582 Decl *AssociatedDecl,
10583 unsigned Index,
10585 bool Final) const {
10586 llvm::FoldingSetNodeID ID;
10587 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10588 Index, PackIndex, Final);
10589
10590 llvm::FoldingSetInsertToken Token;
10592 SubstTemplateTemplateParms.lookup(ID, Token);
10593
10594 if (!subst) {
10595 subst = new (*this) SubstTemplateTemplateParmStorage(
10596 Replacement, AssociatedDecl, Index, PackIndex, Final);
10597 SubstTemplateTemplateParms.insert(subst, Token);
10598 }
10599
10600 return TemplateName(subst);
10601}
10602
10605 Decl *AssociatedDecl,
10606 unsigned Index, bool Final) const {
10607 auto &Self = const_cast<ASTContext &>(*this);
10608 llvm::FoldingSetNodeID ID;
10610 AssociatedDecl, Index, Final);
10611
10612 llvm::FoldingSetInsertToken Token;
10614 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10615
10616 if (!Subst) {
10617 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10618 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10619 SubstTemplateTemplateParmPacks.insert(Subst, Token);
10620 }
10621
10622 return TemplateName(Subst);
10623}
10624
10625/// Retrieve the template name that represents a template name
10626/// deduced from a specialization.
10629 DefaultArguments DefaultArgs) const {
10630 if (!DefaultArgs)
10631 return Underlying;
10632
10633 llvm::FoldingSetNodeID ID;
10634 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10635
10636 llvm::FoldingSetInsertToken Token;
10637 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10638 if (!DTS) {
10639 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10640 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10641 alignof(DeducedTemplateStorage));
10642 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10643 DeducedTemplates.insert(DTS, Token);
10644 }
10645 return TemplateName(DTS);
10646}
10647
10649 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10650 ArrayRef<TemplateName> Expansions) const {
10651 auto &Self = const_cast<ASTContext &>(*this);
10652 llvm::FoldingSetNodeID ID;
10653 PackIndexingTemplateStorage::Profile(ID, Self, Pattern, IndexExpr,
10654 FullySubstituted, Expansions);
10655
10656 llvm::FoldingSetInsertToken Token;
10657 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10658 if (!PI) {
10659 void *Mem =
10660 Allocate(PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10661 Expansions.size()),
10663 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10664 FullySubstituted, Expansions);
10665 PackIndexingTemplates.insert(PI, Token);
10666 }
10667 return TemplateName(PI);
10668}
10669
10670/// getFromTargetType - Given one of the integer types provided by
10671/// TargetInfo, produce the corresponding type. The unsigned @p Type
10672/// is actually a value of type @c TargetInfo::IntType.
10673CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10674 switch (Type) {
10675 case TargetInfo::NoInt: return {};
10678 case TargetInfo::SignedShort: return ShortTy;
10680 case TargetInfo::SignedInt: return IntTy;
10682 case TargetInfo::SignedLong: return LongTy;
10686 }
10687
10688 llvm_unreachable("Unhandled TargetInfo::IntType value");
10689}
10690
10691//===----------------------------------------------------------------------===//
10692// Type Predicates.
10693//===----------------------------------------------------------------------===//
10694
10695/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10696/// garbage collection attribute.
10697///
10699 if (getLangOpts().getGC() == LangOptions::NonGC)
10700 return Qualifiers::GCNone;
10701
10702 assert(getLangOpts().ObjC);
10703 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10704
10705 // Default behaviour under objective-C's gc is for ObjC pointers
10706 // (or pointers to them) be treated as though they were declared
10707 // as __strong.
10708 if (GCAttrs == Qualifiers::GCNone) {
10710 return Qualifiers::Strong;
10711 else if (Ty->isPointerType())
10713 } else {
10714 // It's not valid to set GC attributes on anything that isn't a
10715 // pointer.
10716#ifndef NDEBUG
10718 while (const auto *AT = dyn_cast<ArrayType>(CT))
10719 CT = AT->getElementType();
10720 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10721#endif
10722 }
10723 return GCAttrs;
10724}
10725
10726//===----------------------------------------------------------------------===//
10727// Type Compatibility Testing
10728//===----------------------------------------------------------------------===//
10729
10730/// areCompatVectorTypes - Return true if the two specified vector types are
10731/// compatible.
10732static bool areCompatVectorTypes(const VectorType *LHS,
10733 const VectorType *RHS) {
10734 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10735 return LHS->getElementType() == RHS->getElementType() &&
10736 LHS->getNumElements() == RHS->getNumElements();
10737}
10738
10739/// areCompatMatrixTypes - Return true if the two specified matrix types are
10740/// compatible.
10742 const ConstantMatrixType *RHS) {
10743 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10744 return LHS->getElementType() == RHS->getElementType() &&
10745 LHS->getNumRows() == RHS->getNumRows() &&
10746 LHS->getNumColumns() == RHS->getNumColumns();
10747}
10748
10750 QualType SecondVec) {
10751 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10752 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10753
10754 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10755 return true;
10756
10757 // Treat Neon vector types and most AltiVec vector types as if they are the
10758 // equivalent GCC vector types.
10759 const auto *First = FirstVec->castAs<VectorType>();
10760 const auto *Second = SecondVec->castAs<VectorType>();
10761 if (First->getNumElements() == Second->getNumElements() &&
10762 hasSameType(First->getElementType(), Second->getElementType()) &&
10763 First->getVectorKind() != VectorKind::AltiVecPixel &&
10764 First->getVectorKind() != VectorKind::AltiVecBool &&
10767 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10768 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10771 !isRVVFixedLengthVectorKind(First->getVectorKind()) &&
10773 return true;
10774
10775 // In OpenCL, treat half and _Float16 vector types as compatible.
10776 if (getLangOpts().OpenCL &&
10777 First->getNumElements() == Second->getNumElements()) {
10778 QualType FirstElt = First->getElementType();
10779 QualType SecondElt = Second->getElementType();
10780
10781 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10782 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10783 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10784 First->getVectorKind() != VectorKind::AltiVecBool &&
10787 return true;
10788 }
10789 }
10790 return false;
10791}
10792
10798
10801 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10802 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10803
10804 if (!LHSOBT && !RHSOBT)
10806
10807 if (LHSOBT && RHSOBT) {
10808 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10811 }
10812
10813 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10814 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10815
10816 if (RHSOBT && !LHSOBT) {
10817 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10819 }
10820
10822}
10823
10824/// getRVVTypeSize - Return RVV vector register size.
10825static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10826 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10827 auto VScale = Context.getTargetInfo().getVScaleRange(
10828 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10829 if (!VScale)
10830 return 0;
10831
10832 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10833
10834 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10835 if (Info.ElementType == Context.BoolTy)
10836 EltSize = 1;
10837
10838 uint64_t MinElts = Info.EC.getKnownMinValue();
10839 return VScale->first * MinElts * EltSize;
10840}
10841
10843 QualType SecondType) {
10844 assert(
10845 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10846 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10847 "Expected RVV builtin type and vector type!");
10848
10849 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10850 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10851 if (const auto *VT = SecondType->getAs<VectorType>()) {
10852 if (isRVVFixedLengthMaskVectorKind(VT->getVectorKind())) {
10854 // A mask typedef converts to and from the vbool<R>_t type it was
10855 // written against: vbool<R>_t has RVVBitsPerBlock / R lanes at
10856 // vscale=1.
10857 return FirstType->isRVVVLSBuiltinType() &&
10858 Info.ElementType == BoolTy &&
10859 (llvm::RISCV::RVVBitsPerBlock >>
10860 getRVVFixedLengthMaskRatioLog2(VT->getVectorKind())) ==
10861 Info.EC.getKnownMinValue() &&
10862 VT->getRVVFixedLengthMaskLanes() == getRVVTypeSize(*this, BT);
10863 }
10864 if (isRVVFixedLengthDataVectorKind(VT->getVectorKind()) ||
10865 VT->getVectorKind() == VectorKind::Generic)
10866 return FirstType->isRVVVLSBuiltinType() &&
10867 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10868 hasSameType(VT->getElementType(),
10869 getBuiltinVectorTypeInfo(BT).ElementType);
10870 }
10871 }
10872 return false;
10873 };
10874
10875 return IsValidCast(FirstType, SecondType) ||
10876 IsValidCast(SecondType, FirstType);
10877}
10878
10880 QualType SecondType) {
10881 assert(
10882 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10883 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10884 "Expected RVV builtin type and vector type!");
10885
10886 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10887 const auto *BT = FirstType->getAs<BuiltinType>();
10888 if (!BT)
10889 return false;
10890
10891 if (!BT->isRVVVLSBuiltinType())
10892 return false;
10893
10894 const auto *VecTy = SecondType->getAs<VectorType>();
10895 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10897 getLangOpts().getLaxVectorConversions();
10898
10899 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10900 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10901 return false;
10902
10903 // If -flax-vector-conversions=all is specified, the types are
10904 // certainly compatible.
10906 return true;
10907
10908 // If -flax-vector-conversions=integer is specified, the types are
10909 // compatible if the elements are integer types.
10911 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10912 FirstType->getRVVEltType(*this)->isIntegerType();
10913 }
10914
10915 return false;
10916 };
10917
10918 return IsLaxCompatible(FirstType, SecondType) ||
10919 IsLaxCompatible(SecondType, FirstType);
10920}
10921
10923 while (true) {
10924 // __strong id
10925 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10926 if (Attr->getAttrKind() == attr::ObjCOwnership)
10927 return true;
10928
10929 Ty = Attr->getModifiedType();
10930
10931 // X *__strong (...)
10932 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10933 Ty = Paren->getInnerType();
10934
10935 // We do not want to look through typedefs, typeof(expr),
10936 // typeof(type), or any other way that the type is somehow
10937 // abstracted.
10938 } else {
10939 return false;
10940 }
10941 }
10942}
10943
10944//===----------------------------------------------------------------------===//
10945// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10946//===----------------------------------------------------------------------===//
10947
10948/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10949/// inheritance hierarchy of 'rProto'.
10950bool
10952 ObjCProtocolDecl *rProto) const {
10953 if (declaresSameEntity(lProto, rProto))
10954 return true;
10955 for (auto *PI : rProto->protocols())
10956 if (ProtocolCompatibleWithProtocol(lProto, PI))
10957 return true;
10958 return false;
10959}
10960
10961/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10962/// Class<pr1, ...>.
10964 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10965 for (auto *lhsProto : lhs->quals()) {
10966 bool match = false;
10967 for (auto *rhsProto : rhs->quals()) {
10968 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10969 match = true;
10970 break;
10971 }
10972 }
10973 if (!match)
10974 return false;
10975 }
10976 return true;
10977}
10978
10979/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10980/// ObjCQualifiedIDType.
10982 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10983 bool compare) {
10984 // Allow id<P..> and an 'id' in all cases.
10985 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10986 return true;
10987
10988 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10989 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10991 return false;
10992
10993 if (lhs->isObjCQualifiedIdType()) {
10994 if (rhs->qual_empty()) {
10995 // If the RHS is a unqualified interface pointer "NSString*",
10996 // make sure we check the class hierarchy.
10997 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10998 for (auto *I : lhs->quals()) {
10999 // when comparing an id<P> on lhs with a static type on rhs,
11000 // see if static class implements all of id's protocols, directly or
11001 // through its super class and categories.
11002 if (!rhsID->ClassImplementsProtocol(I, true))
11003 return false;
11004 }
11005 }
11006 // If there are no qualifiers and no interface, we have an 'id'.
11007 return true;
11008 }
11009 // Both the right and left sides have qualifiers.
11010 for (auto *lhsProto : lhs->quals()) {
11011 bool match = false;
11012
11013 // when comparing an id<P> on lhs with a static type on rhs,
11014 // see if static class implements all of id's protocols, directly or
11015 // through its super class and categories.
11016 for (auto *rhsProto : rhs->quals()) {
11017 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11018 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11019 match = true;
11020 break;
11021 }
11022 }
11023 // If the RHS is a qualified interface pointer "NSString<P>*",
11024 // make sure we check the class hierarchy.
11025 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11026 for (auto *I : lhs->quals()) {
11027 // when comparing an id<P> on lhs with a static type on rhs,
11028 // see if static class implements all of id's protocols, directly or
11029 // through its super class and categories.
11030 if (rhsID->ClassImplementsProtocol(I, true)) {
11031 match = true;
11032 break;
11033 }
11034 }
11035 }
11036 if (!match)
11037 return false;
11038 }
11039
11040 return true;
11041 }
11042
11043 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11044
11045 if (lhs->getInterfaceType()) {
11046 // If both the right and left sides have qualifiers.
11047 for (auto *lhsProto : lhs->quals()) {
11048 bool match = false;
11049
11050 // when comparing an id<P> on rhs with a static type on lhs,
11051 // see if static class implements all of id's protocols, directly or
11052 // through its super class and categories.
11053 // First, lhs protocols in the qualifier list must be found, direct
11054 // or indirect in rhs's qualifier list or it is a mismatch.
11055 for (auto *rhsProto : rhs->quals()) {
11056 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11057 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11058 match = true;
11059 break;
11060 }
11061 }
11062 if (!match)
11063 return false;
11064 }
11065
11066 // Static class's protocols, or its super class or category protocols
11067 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11068 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11069 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11070 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11071 // This is rather dubious but matches gcc's behavior. If lhs has
11072 // no type qualifier and its class has no static protocol(s)
11073 // assume that it is mismatch.
11074 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11075 return false;
11076 for (auto *lhsProto : LHSInheritedProtocols) {
11077 bool match = false;
11078 for (auto *rhsProto : rhs->quals()) {
11079 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11080 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11081 match = true;
11082 break;
11083 }
11084 }
11085 if (!match)
11086 return false;
11087 }
11088 }
11089 return true;
11090 }
11091 return false;
11092}
11093
11094/// canAssignObjCInterfaces - Return true if the two interface types are
11095/// compatible for assignment from RHS to LHS. This handles validation of any
11096/// protocol qualifiers on the LHS or RHS.
11098 const ObjCObjectPointerType *RHSOPT) {
11099 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11100 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11101
11102 // If either type represents the built-in 'id' type, return true.
11103 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11104 return true;
11105
11106 // Function object that propagates a successful result or handles
11107 // __kindof types.
11108 auto finish = [&](bool succeeded) -> bool {
11109 if (succeeded)
11110 return true;
11111
11112 if (!RHS->isKindOfType())
11113 return false;
11114
11115 // Strip off __kindof and protocol qualifiers, then check whether
11116 // we can assign the other way.
11118 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11119 };
11120
11121 // Casts from or to id<P> are allowed when the other side has compatible
11122 // protocols.
11123 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11124 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11125 }
11126
11127 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11128 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11129 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11130 }
11131
11132 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11133 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11134 return true;
11135 }
11136
11137 // If we have 2 user-defined types, fall into that path.
11138 if (LHS->getInterface() && RHS->getInterface()) {
11139 return finish(canAssignObjCInterfaces(LHS, RHS));
11140 }
11141
11142 return false;
11143}
11144
11145/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11146/// for providing type-safety for objective-c pointers used to pass/return
11147/// arguments in block literals. When passed as arguments, passing 'A*' where
11148/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11149/// not OK. For the return type, the opposite is not OK.
11151 const ObjCObjectPointerType *LHSOPT,
11152 const ObjCObjectPointerType *RHSOPT,
11153 bool BlockReturnType) {
11154
11155 // Function object that propagates a successful result or handles
11156 // __kindof types.
11157 auto finish = [&](bool succeeded) -> bool {
11158 if (succeeded)
11159 return true;
11160
11161 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11162 if (!Expected->isKindOfType())
11163 return false;
11164
11165 // Strip off __kindof and protocol qualifiers, then check whether
11166 // we can assign the other way.
11168 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11169 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11170 BlockReturnType);
11171 };
11172
11173 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11174 return true;
11175
11176 if (LHSOPT->isObjCBuiltinType()) {
11177 return finish(RHSOPT->isObjCBuiltinType() ||
11178 RHSOPT->isObjCQualifiedIdType());
11179 }
11180
11181 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11182 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11183 // Use for block parameters previous type checking for compatibility.
11184 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11185 // Or corrected type checking as in non-compat mode.
11186 (!BlockReturnType &&
11187 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11188 else
11190 (BlockReturnType ? LHSOPT : RHSOPT),
11191 (BlockReturnType ? RHSOPT : LHSOPT), false));
11192 }
11193
11194 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11195 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11196 if (LHS && RHS) { // We have 2 user-defined types.
11197 if (LHS != RHS) {
11198 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11199 return finish(BlockReturnType);
11200 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11201 return finish(!BlockReturnType);
11202 }
11203 else
11204 return true;
11205 }
11206 return false;
11207}
11208
11209/// Comparison routine for Objective-C protocols to be used with
11210/// llvm::array_pod_sort.
11212 ObjCProtocolDecl * const *rhs) {
11213 return (*lhs)->getName().compare((*rhs)->getName());
11214}
11215
11216/// getIntersectionOfProtocols - This routine finds the intersection of set
11217/// of protocols inherited from two distinct objective-c pointer objects with
11218/// the given common base.
11219/// It is used to build composite qualifier list of the composite type of
11220/// the conditional expression involving two objective-c pointer objects.
11221static
11223 const ObjCInterfaceDecl *CommonBase,
11224 const ObjCObjectPointerType *LHSOPT,
11225 const ObjCObjectPointerType *RHSOPT,
11226 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11227
11228 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11229 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11230 assert(LHS->getInterface() && "LHS must have an interface base");
11231 assert(RHS->getInterface() && "RHS must have an interface base");
11232
11233 // Add all of the protocols for the LHS.
11235
11236 // Start with the protocol qualifiers.
11237 for (auto *proto : LHS->quals()) {
11238 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11239 }
11240
11241 // Also add the protocols associated with the LHS interface.
11242 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11243
11244 // Add all of the protocols for the RHS.
11246
11247 // Start with the protocol qualifiers.
11248 for (auto *proto : RHS->quals()) {
11249 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11250 }
11251
11252 // Also add the protocols associated with the RHS interface.
11253 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11254
11255 // Compute the intersection of the collected protocol sets.
11256 for (auto *proto : LHSProtocolSet) {
11257 if (RHSProtocolSet.count(proto))
11258 IntersectionSet.push_back(proto);
11259 }
11260
11261 // Compute the set of protocols that is implied by either the common type or
11262 // the protocols within the intersection.
11264 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11265
11266 // Remove any implied protocols from the list of inherited protocols.
11267 if (!ImpliedProtocols.empty()) {
11268 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11269 return ImpliedProtocols.contains(proto);
11270 });
11271 }
11272
11273 // Sort the remaining protocols by name.
11274 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11276}
11277
11278/// Determine whether the first type is a subtype of the second.
11280 QualType rhs) {
11281 // Common case: two object pointers.
11282 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11283 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11284 if (lhsOPT && rhsOPT)
11285 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11286
11287 // Two block pointers.
11288 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11289 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11290 if (lhsBlock && rhsBlock)
11291 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11292
11293 // If either is an unqualified 'id' and the other is a block, it's
11294 // acceptable.
11295 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11296 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11297 return true;
11298
11299 return false;
11300}
11301
11302// Check that the given Objective-C type argument lists are equivalent.
11304 const ObjCInterfaceDecl *iface,
11305 ArrayRef<QualType> lhsArgs,
11306 ArrayRef<QualType> rhsArgs,
11307 bool stripKindOf) {
11308 if (lhsArgs.size() != rhsArgs.size())
11309 return false;
11310
11311 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11312 if (!typeParams)
11313 return false;
11314
11315 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11316 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11317 continue;
11318
11319 switch (typeParams->begin()[i]->getVariance()) {
11321 if (!stripKindOf ||
11322 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11323 rhsArgs[i].stripObjCKindOfType(ctx))) {
11324 return false;
11325 }
11326 break;
11327
11329 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11330 return false;
11331 break;
11332
11334 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11335 return false;
11336 break;
11337 }
11338 }
11339
11340 return true;
11341}
11342
11344 const ObjCObjectPointerType *Lptr,
11345 const ObjCObjectPointerType *Rptr) {
11346 const ObjCObjectType *LHS = Lptr->getObjectType();
11347 const ObjCObjectType *RHS = Rptr->getObjectType();
11348 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11349 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11350
11351 if (!LDecl || !RDecl)
11352 return {};
11353
11354 // When either LHS or RHS is a kindof type, we should return a kindof type.
11355 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11356 // kindof(A).
11357 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11358
11359 // Follow the left-hand side up the class hierarchy until we either hit a
11360 // root or find the RHS. Record the ancestors in case we don't find it.
11361 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11362 LHSAncestors;
11363 while (true) {
11364 // Record this ancestor. We'll need this if the common type isn't in the
11365 // path from the LHS to the root.
11366 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11367
11368 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11369 // Get the type arguments.
11370 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11371 bool anyChanges = false;
11372 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11373 // Both have type arguments, compare them.
11374 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11375 LHS->getTypeArgs(), RHS->getTypeArgs(),
11376 /*stripKindOf=*/true))
11377 return {};
11378 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11379 // If only one has type arguments, the result will not have type
11380 // arguments.
11381 LHSTypeArgs = {};
11382 anyChanges = true;
11383 }
11384
11385 // Compute the intersection of protocols.
11387 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11388 Protocols);
11389 if (!Protocols.empty())
11390 anyChanges = true;
11391
11392 // If anything in the LHS will have changed, build a new result type.
11393 // If we need to return a kindof type but LHS is not a kindof type, we
11394 // build a new result type.
11395 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11396 QualType Result = getObjCInterfaceType(LHS->getInterface());
11397 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11398 anyKindOf || LHS->isKindOfType());
11400 }
11401
11402 return getObjCObjectPointerType(QualType(LHS, 0));
11403 }
11404
11405 // Find the superclass.
11406 QualType LHSSuperType = LHS->getSuperClassType();
11407 if (LHSSuperType.isNull())
11408 break;
11409
11410 LHS = LHSSuperType->castAs<ObjCObjectType>();
11411 }
11412
11413 // We didn't find anything by following the LHS to its root; now check
11414 // the RHS against the cached set of ancestors.
11415 while (true) {
11416 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11417 if (KnownLHS != LHSAncestors.end()) {
11418 LHS = KnownLHS->second;
11419
11420 // Get the type arguments.
11421 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11422 bool anyChanges = false;
11423 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11424 // Both have type arguments, compare them.
11425 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11426 LHS->getTypeArgs(), RHS->getTypeArgs(),
11427 /*stripKindOf=*/true))
11428 return {};
11429 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11430 // If only one has type arguments, the result will not have type
11431 // arguments.
11432 RHSTypeArgs = {};
11433 anyChanges = true;
11434 }
11435
11436 // Compute the intersection of protocols.
11438 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11439 Protocols);
11440 if (!Protocols.empty())
11441 anyChanges = true;
11442
11443 // If we need to return a kindof type but RHS is not a kindof type, we
11444 // build a new result type.
11445 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11446 QualType Result = getObjCInterfaceType(RHS->getInterface());
11447 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11448 anyKindOf || RHS->isKindOfType());
11450 }
11451
11452 return getObjCObjectPointerType(QualType(RHS, 0));
11453 }
11454
11455 // Find the superclass of the RHS.
11456 QualType RHSSuperType = RHS->getSuperClassType();
11457 if (RHSSuperType.isNull())
11458 break;
11459
11460 RHS = RHSSuperType->castAs<ObjCObjectType>();
11461 }
11462
11463 return {};
11464}
11465
11467 const ObjCObjectType *RHS) {
11468 assert(LHS->getInterface() && "LHS is not an interface type");
11469 assert(RHS->getInterface() && "RHS is not an interface type");
11470
11471 // Verify that the base decls are compatible: the RHS must be a subclass of
11472 // the LHS.
11473 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11474 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11475 if (!IsSuperClass)
11476 return false;
11477
11478 // If the LHS has protocol qualifiers, determine whether all of them are
11479 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11480 // LHS).
11481 if (LHS->getNumProtocols() > 0) {
11482 // OK if conversion of LHS to SuperClass results in narrowing of types
11483 // ; i.e., SuperClass may implement at least one of the protocols
11484 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11485 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11486 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11487 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11488 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11489 // qualifiers.
11490 for (auto *RHSPI : RHS->quals())
11491 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11492 // If there is no protocols associated with RHS, it is not a match.
11493 if (SuperClassInheritedProtocols.empty())
11494 return false;
11495
11496 for (const auto *LHSProto : LHS->quals()) {
11497 bool SuperImplementsProtocol = false;
11498 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11499 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11500 SuperImplementsProtocol = true;
11501 break;
11502 }
11503 if (!SuperImplementsProtocol)
11504 return false;
11505 }
11506 }
11507
11508 // If the LHS is specialized, we may need to check type arguments.
11509 if (LHS->isSpecialized()) {
11510 // Follow the superclass chain until we've matched the LHS class in the
11511 // hierarchy. This substitutes type arguments through.
11512 const ObjCObjectType *RHSSuper = RHS;
11513 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11514 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11515
11516 // If the RHS is specializd, compare type arguments.
11517 if (RHSSuper->isSpecialized() &&
11518 !sameObjCTypeArgs(*this, LHS->getInterface(),
11519 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11520 /*stripKindOf=*/true)) {
11521 return false;
11522 }
11523 }
11524
11525 return true;
11526}
11527
11529 // get the "pointed to" types
11530 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11531 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11532
11533 if (!LHSOPT || !RHSOPT)
11534 return false;
11535
11536 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11537 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11538}
11539
11542 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11543 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11544}
11545
11546/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11547/// both shall have the identically qualified version of a compatible type.
11548/// C99 6.2.7p1: Two types have compatible types if their types are the
11549/// same. See 6.7.[2,3,5] for additional rules.
11551 bool CompareUnqualified) {
11552 if (getLangOpts().CPlusPlus)
11553 return hasSameType(LHS, RHS);
11554
11555 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11556}
11557
11559 return typesAreCompatible(LHS, RHS);
11560}
11561
11563 return !mergeTypes(LHS, RHS, true).isNull();
11564}
11565
11566/// mergeTransparentUnionType - if T is a transparent union type and a member
11567/// of T is compatible with SubType, return the merged type, else return
11568/// QualType()
11570 bool OfBlockPointer,
11571 bool Unqualified) {
11572 if (const RecordType *UT = T->getAsUnionType()) {
11573 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11574 if (UD->hasAttr<TransparentUnionAttr>()) {
11575 for (const auto *I : UD->fields()) {
11576 QualType ET = I->getType().getUnqualifiedType();
11577 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11578 if (!MT.isNull())
11579 return MT;
11580 }
11581 }
11582 }
11583
11584 return {};
11585}
11586
11587/// mergeFunctionParameterTypes - merge two types which appear as function
11588/// parameter types
11590 bool OfBlockPointer,
11591 bool Unqualified) {
11592 // GNU extension: two types are compatible if they appear as a function
11593 // argument, one of the types is a transparent union type and the other
11594 // type is compatible with a union member
11595 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11596 Unqualified);
11597 if (!lmerge.isNull())
11598 return lmerge;
11599
11600 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11601 Unqualified);
11602 if (!rmerge.isNull())
11603 return rmerge;
11604
11605 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11606}
11607
11609 bool OfBlockPointer, bool Unqualified,
11610 bool AllowCXX,
11611 bool IsConditionalOperator) {
11612 const auto *lbase = lhs->castAs<FunctionType>();
11613 const auto *rbase = rhs->castAs<FunctionType>();
11614 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11615 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11616 bool allLTypes = true;
11617 bool allRTypes = true;
11618
11619 // Check return type
11620 QualType retType;
11621 if (OfBlockPointer) {
11622 QualType RHS = rbase->getReturnType();
11623 QualType LHS = lbase->getReturnType();
11624 bool UnqualifiedResult = Unqualified;
11625 if (!UnqualifiedResult)
11626 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11627 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11628 }
11629 else
11630 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11631 Unqualified);
11632 if (retType.isNull())
11633 return {};
11634
11635 if (Unqualified)
11636 retType = retType.getUnqualifiedType();
11637
11638 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11639 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11640 if (Unqualified) {
11641 LRetType = LRetType.getUnqualifiedType();
11642 RRetType = RRetType.getUnqualifiedType();
11643 }
11644
11645 if (getCanonicalType(retType) != LRetType)
11646 allLTypes = false;
11647 if (getCanonicalType(retType) != RRetType)
11648 allRTypes = false;
11649
11650 // FIXME: double check this
11651 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11652 // rbase->getRegParmAttr() != 0 &&
11653 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11654 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11655 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11656
11657 // Compatible functions must have compatible calling conventions
11658 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11659 return {};
11660
11661 // Regparm is part of the calling convention.
11662 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11663 return {};
11664 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11665 return {};
11666
11667 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11668 return {};
11669 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11670 return {};
11671 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11672 return {};
11673
11674 // When merging declarations, it's common for supplemental information like
11675 // attributes to only be present in one of the declarations, and we generally
11676 // want type merging to preserve the union of information. So a merged
11677 // function type should be noreturn if it was noreturn in *either* operand
11678 // type.
11679 //
11680 // But for the conditional operator, this is backwards. The result of the
11681 // operator could be either operand, and its type should conservatively
11682 // reflect that. So a function type in a composite type is noreturn only
11683 // if it's noreturn in *both* operand types.
11684 //
11685 // Arguably, noreturn is a kind of subtype, and the conditional operator
11686 // ought to produce the most specific common supertype of its operand types.
11687 // That would differ from this rule in contravariant positions. However,
11688 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11689 // as a practical matter, it would only affect C code that does abstraction of
11690 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11691 // say the least. So we use the simpler rule.
11692 bool NoReturn = IsConditionalOperator
11693 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11694 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11695 if (lbaseInfo.getNoReturn() != NoReturn)
11696 allLTypes = false;
11697 if (rbaseInfo.getNoReturn() != NoReturn)
11698 allRTypes = false;
11699
11700 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11701
11702 std::optional<FunctionEffectSet> MergedFX;
11703
11704 if (lproto && rproto) { // two C99 style function prototypes
11705 assert((AllowCXX ||
11706 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11707 "C++ shouldn't be here");
11708 // Compatible functions must have the same number of parameters
11709 if (lproto->getNumParams() != rproto->getNumParams())
11710 return {};
11711
11712 // Variadic and non-variadic functions aren't compatible
11713 if (lproto->isVariadic() != rproto->isVariadic())
11714 return {};
11715
11716 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11717 return {};
11718
11719 // Function protos with different 'cfi_salt' values aren't compatible.
11720 if (lproto->getExtraAttributeInfo().CFISalt !=
11721 rproto->getExtraAttributeInfo().CFISalt)
11722 return {};
11723
11724 // Function effects are handled similarly to noreturn, see above.
11725 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11726 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11727 if (LHSFX != RHSFX) {
11728 if (IsConditionalOperator)
11729 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11730 else {
11732 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11733 // Here we're discarding a possible error due to conflicts in the effect
11734 // sets. But we're not in a context where we can report it. The
11735 // operation does however guarantee maintenance of invariants.
11736 }
11737 if (*MergedFX != LHSFX)
11738 allLTypes = false;
11739 if (*MergedFX != RHSFX)
11740 allRTypes = false;
11741 }
11742
11744 bool canUseLeft, canUseRight;
11745 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11746 newParamInfos))
11747 return {};
11748
11749 if (!canUseLeft)
11750 allLTypes = false;
11751 if (!canUseRight)
11752 allRTypes = false;
11753
11754 // Check parameter type compatibility
11756 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11757 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11758 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11760 lParamType, rParamType, OfBlockPointer, Unqualified);
11761 if (paramType.isNull())
11762 return {};
11763
11764 if (Unqualified)
11765 paramType = paramType.getUnqualifiedType();
11766
11767 types.push_back(paramType);
11768 if (Unqualified) {
11769 lParamType = lParamType.getUnqualifiedType();
11770 rParamType = rParamType.getUnqualifiedType();
11771 }
11772
11773 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11774 allLTypes = false;
11775 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11776 allRTypes = false;
11777 }
11778
11779 if (allLTypes) return lhs;
11780 if (allRTypes) return rhs;
11781
11782 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11783 EPI.ExtInfo = einfo;
11784 EPI.ExtParameterInfos =
11785 newParamInfos.empty() ? nullptr : newParamInfos.data();
11786 if (MergedFX)
11787 EPI.FunctionEffects = *MergedFX;
11788 return getFunctionType(retType, types, EPI);
11789 }
11790
11791 if (lproto) allRTypes = false;
11792 if (rproto) allLTypes = false;
11793
11794 const FunctionProtoType *proto = lproto ? lproto : rproto;
11795 if (proto) {
11796 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11797 if (proto->isVariadic())
11798 return {};
11799 // Check that the types are compatible with the types that
11800 // would result from default argument promotions (C99 6.7.5.3p15).
11801 // The only types actually affected are promotable integer
11802 // types and floats, which would be passed as a different
11803 // type depending on whether the prototype is visible.
11804 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11805 QualType paramTy = proto->getParamType(i);
11806
11807 // Look at the converted type of enum types, since that is the type used
11808 // to pass enum values.
11809 if (const auto *ED = paramTy->getAsEnumDecl()) {
11810 paramTy = ED->getIntegerType();
11811 if (paramTy.isNull())
11812 return {};
11813 }
11814
11815 if (isPromotableIntegerType(paramTy) ||
11816 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11817 return {};
11818 }
11819
11820 if (allLTypes) return lhs;
11821 if (allRTypes) return rhs;
11822
11824 EPI.ExtInfo = einfo;
11825 if (MergedFX)
11826 EPI.FunctionEffects = *MergedFX;
11827 return getFunctionType(retType, proto->getParamTypes(), EPI);
11828 }
11829
11830 if (allLTypes) return lhs;
11831 if (allRTypes) return rhs;
11832 return getFunctionNoProtoType(retType, einfo);
11833}
11834
11835/// Given that we have an enum type and a non-enum type, try to merge them.
11836static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11837 QualType other, bool isBlockReturnType) {
11838 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11839 // a signed integer type, or an unsigned integer type.
11840 // Compatibility is based on the underlying type, not the promotion
11841 // type.
11842 QualType underlyingType =
11843 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11844 if (underlyingType.isNull())
11845 return {};
11846 if (Context.hasSameType(underlyingType, other))
11847 return other;
11848
11849 // In block return types, we're more permissive and accept any
11850 // integral type of the same size.
11851 if (isBlockReturnType && other->isIntegerType() &&
11852 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11853 return other;
11854
11855 return {};
11856}
11857
11859 // C17 and earlier and C++ disallow two tag definitions within the same TU
11860 // from being compatible.
11861 if (LangOpts.CPlusPlus || !LangOpts.C23)
11862 return {};
11863
11864 // Nameless tags are comparable only within outer definitions. At the top
11865 // level they are not comparable.
11866 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11867 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11868 return {};
11869
11870 // C23, on the other hand, requires the members to be "the same enough", so
11871 // we use a structural equivalence check.
11874 getLangOpts(), *this, *this, NonEquivalentDecls,
11875 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11876 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11877 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11878}
11879
11881 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11882 bool BlockReturnType, bool IsConditionalOperator) {
11883 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11884 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11885
11886 if (!LHSOBT && !RHSOBT)
11887 return std::nullopt;
11888
11889 if (LHSOBT) {
11890 if (RHSOBT) {
11891 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11892 return QualType();
11893
11894 QualType MergedUnderlying = mergeTypes(
11895 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11896 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11897
11898 if (MergedUnderlying.isNull())
11899 return QualType();
11900
11901 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11902 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11903 return getCommonSugaredType(LHS, RHS);
11905 LHSOBT->getBehaviorKind(),
11906 getCanonicalType(LHSOBT->getUnderlyingType()));
11907 }
11908
11909 // For different underlying types that successfully merge, wrap the
11910 // merged underlying type with the common overflow behavior
11911 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11912 MergedUnderlying);
11913 }
11914 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11915 Unqualified, BlockReturnType, IsConditionalOperator);
11916 }
11917
11918 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11919 Unqualified, BlockReturnType, IsConditionalOperator);
11920}
11921
11922QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11923 bool Unqualified, bool BlockReturnType,
11924 bool IsConditionalOperator) {
11925 // For C++ we will not reach this code with reference types (see below),
11926 // for OpenMP variant call overloading we might.
11927 //
11928 // C++ [expr]: If an expression initially has the type "reference to T", the
11929 // type is adjusted to "T" prior to any further analysis, the expression
11930 // designates the object or function denoted by the reference, and the
11931 // expression is an lvalue unless the reference is an rvalue reference and
11932 // the expression is a function call (possibly inside parentheses).
11933 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11934 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11935 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11936 LHS->getTypeClass() == RHS->getTypeClass())
11937 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11938 OfBlockPointer, Unqualified, BlockReturnType);
11939 if (LHSRefTy || RHSRefTy)
11940 return {};
11941
11942 if (std::optional<QualType> MergedOBT =
11943 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11944 BlockReturnType, IsConditionalOperator))
11945 return *MergedOBT;
11946
11947 if (Unqualified) {
11948 LHS = LHS.getUnqualifiedType();
11949 RHS = RHS.getUnqualifiedType();
11950 }
11951
11952 QualType LHSCan = getCanonicalType(LHS),
11953 RHSCan = getCanonicalType(RHS);
11954
11955 // If two types are identical, they are compatible.
11956 if (LHSCan == RHSCan)
11957 return LHS;
11958
11959 // If the qualifiers are different, the types aren't compatible... mostly.
11960 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11961 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11962 if (LQuals != RQuals) {
11963 // If any of these qualifiers are different, we have a type
11964 // mismatch.
11965 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11966 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11967 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11968 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11969 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11970 return {};
11971
11972 // Exactly one GC qualifier difference is allowed: __strong is
11973 // okay if the other type has no GC qualifier but is an Objective
11974 // C object pointer (i.e. implicitly strong by default). We fix
11975 // this by pretending that the unqualified type was actually
11976 // qualified __strong.
11977 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11978 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11979 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11980
11981 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11982 return {};
11983
11984 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11986 }
11987 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11989 }
11990 return {};
11991 }
11992
11993 // Okay, qualifiers are equal.
11994
11995 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11996 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11997
11998 // We want to consider the two function types to be the same for these
11999 // comparisons, just force one to the other.
12000 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12001 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12002
12003 // Same as above for arrays
12004 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12005 LHSClass = Type::ConstantArray;
12006 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12007 RHSClass = Type::ConstantArray;
12008
12009 // ObjCInterfaces are just specialized ObjCObjects.
12010 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12011 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12012
12013 // Canonicalize ExtVector -> Vector.
12014 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12015 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12016
12017 // If the canonical type classes don't match.
12018 if (LHSClass != RHSClass) {
12019 // Note that we only have special rules for turning block enum
12020 // returns into block int returns, not vice-versa.
12021 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12022 return mergeEnumWithInteger(*this, ETy, RHS, false);
12023 }
12024 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12025 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12026 }
12027 // allow block pointer type to match an 'id' type.
12028 if (OfBlockPointer && !BlockReturnType) {
12029 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12030 return LHS;
12031 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12032 return RHS;
12033 }
12034 // Allow __auto_type to match anything; it merges to the type with more
12035 // information.
12036 if (const auto *AT = LHS->getAs<AutoType>()) {
12037 if (!AT->isDeduced() && AT->isGNUAutoType())
12038 return RHS;
12039 }
12040 if (const auto *AT = RHS->getAs<AutoType>()) {
12041 if (!AT->isDeduced() && AT->isGNUAutoType())
12042 return LHS;
12043 }
12044 return {};
12045 }
12046
12047 // The canonical type classes match.
12048 switch (LHSClass) {
12049#define TYPE(Class, Base)
12050#define ABSTRACT_TYPE(Class, Base)
12051#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12052#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12053#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12054#include "clang/AST/TypeNodes.inc"
12055 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12056
12057 case Type::Auto:
12058 case Type::DeducedTemplateSpecialization:
12059 case Type::LValueReference:
12060 case Type::RValueReference:
12061 case Type::MemberPointer:
12062 llvm_unreachable("C++ should never be in mergeTypes");
12063
12064 case Type::ObjCInterface:
12065 case Type::IncompleteArray:
12066 case Type::VariableArray:
12067 case Type::FunctionProto:
12068 case Type::ExtVector:
12069 case Type::OverflowBehavior:
12070 llvm_unreachable("Types are eliminated above");
12071
12072 case Type::Pointer:
12073 {
12074 // Merge two pointer types, while trying to preserve typedef info
12075 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12076 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12077 if (Unqualified) {
12078 LHSPointee = LHSPointee.getUnqualifiedType();
12079 RHSPointee = RHSPointee.getUnqualifiedType();
12080 }
12081 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12082 Unqualified);
12083 if (ResultType.isNull())
12084 return {};
12085 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12086 return LHS;
12087 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12088 return RHS;
12089 return getPointerType(ResultType);
12090 }
12091 case Type::BlockPointer:
12092 {
12093 // Merge two block pointer types, while trying to preserve typedef info
12094 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12095 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12096 if (Unqualified) {
12097 LHSPointee = LHSPointee.getUnqualifiedType();
12098 RHSPointee = RHSPointee.getUnqualifiedType();
12099 }
12100 if (getLangOpts().OpenCL) {
12101 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12102 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12103 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12104 // 6.12.5) thus the following check is asymmetric.
12105 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12106 return {};
12107 LHSPteeQual.removeAddressSpace();
12108 RHSPteeQual.removeAddressSpace();
12109 LHSPointee =
12110 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12111 RHSPointee =
12112 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12113 }
12114 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12115 Unqualified);
12116 if (ResultType.isNull())
12117 return {};
12118 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12119 return LHS;
12120 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12121 return RHS;
12122 return getBlockPointerType(ResultType);
12123 }
12124 case Type::Atomic:
12125 {
12126 // Merge two pointer types, while trying to preserve typedef info
12127 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12128 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12129 if (Unqualified) {
12130 LHSValue = LHSValue.getUnqualifiedType();
12131 RHSValue = RHSValue.getUnqualifiedType();
12132 }
12133 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12134 Unqualified);
12135 if (ResultType.isNull())
12136 return {};
12137 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12138 return LHS;
12139 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12140 return RHS;
12141 return getAtomicType(ResultType);
12142 }
12143 case Type::ConstantArray:
12144 {
12145 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12146 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12147 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12148 return {};
12149
12150 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12151 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12152 if (Unqualified) {
12153 LHSElem = LHSElem.getUnqualifiedType();
12154 RHSElem = RHSElem.getUnqualifiedType();
12155 }
12156
12157 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12158 if (ResultType.isNull())
12159 return {};
12160
12161 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12162 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12163
12164 // If either side is a variable array, and both are complete, check whether
12165 // the current dimension is definite.
12166 if (LVAT || RVAT) {
12167 auto SizeFetch = [this](const VariableArrayType* VAT,
12168 const ConstantArrayType* CAT)
12169 -> std::pair<bool,llvm::APInt> {
12170 if (VAT) {
12171 std::optional<llvm::APSInt> TheInt;
12172 Expr *E = VAT->getSizeExpr();
12173 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12174 return std::make_pair(true, *TheInt);
12175 return std::make_pair(false, llvm::APSInt());
12176 }
12177 if (CAT)
12178 return std::make_pair(true, CAT->getSize());
12179 return std::make_pair(false, llvm::APInt());
12180 };
12181
12182 bool HaveLSize, HaveRSize;
12183 llvm::APInt LSize, RSize;
12184 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12185 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12186 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12187 return {}; // Definite, but unequal, array dimension
12188 }
12189
12190 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12191 return LHS;
12192 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12193 return RHS;
12194 if (LCAT)
12195 return getConstantArrayType(ResultType, LCAT->getSize(),
12196 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12197 if (RCAT)
12198 return getConstantArrayType(ResultType, RCAT->getSize(),
12199 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12200 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12201 return LHS;
12202 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12203 return RHS;
12204 if (LVAT) {
12205 // FIXME: This isn't correct! But tricky to implement because
12206 // the array's size has to be the size of LHS, but the type
12207 // has to be different.
12208 return LHS;
12209 }
12210 if (RVAT) {
12211 // FIXME: This isn't correct! But tricky to implement because
12212 // the array's size has to be the size of RHS, but the type
12213 // has to be different.
12214 return RHS;
12215 }
12216 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12217 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12218 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12219 }
12220 case Type::FunctionNoProto:
12221 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12222 /*AllowCXX=*/false, IsConditionalOperator);
12223 case Type::Record:
12224 case Type::Enum:
12225 return mergeTagDefinitions(LHS, RHS);
12226 case Type::Builtin:
12227 // Only exactly equal builtin types are compatible, which is tested above.
12228 return {};
12229 case Type::Complex:
12230 // Distinct complex types are incompatible.
12231 return {};
12232 case Type::Vector:
12233 // FIXME: The merged type should be an ExtVector!
12234 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12235 RHSCan->castAs<VectorType>()))
12236 return LHS;
12237 return {};
12238 case Type::ConstantMatrix:
12240 RHSCan->castAs<ConstantMatrixType>()))
12241 return LHS;
12242 return {};
12243 case Type::ObjCObject: {
12244 // Check if the types are assignment compatible.
12245 // FIXME: This should be type compatibility, e.g. whether
12246 // "LHS x; RHS x;" at global scope is legal.
12248 RHS->castAs<ObjCObjectType>()))
12249 return LHS;
12250 return {};
12251 }
12252 case Type::ObjCObjectPointer:
12253 if (OfBlockPointer) {
12256 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12257 return LHS;
12258 return {};
12259 }
12262 return LHS;
12263 return {};
12264 case Type::Pipe:
12265 assert(LHS != RHS &&
12266 "Equivalent pipe types should have already been handled!");
12267 return {};
12268 case Type::ArrayParameter:
12269 assert(LHS != RHS &&
12270 "Equivalent ArrayParameter types should have already been handled!");
12271 return {};
12272 case Type::BitInt: {
12273 // Merge two bit-precise int types, while trying to preserve typedef info.
12274 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12275 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12276 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12277 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12278
12279 // Like unsigned/int, shouldn't have a type if they don't match.
12280 if (LHSUnsigned != RHSUnsigned)
12281 return {};
12282
12283 if (LHSBits != RHSBits)
12284 return {};
12285 return LHS;
12286 }
12287 case Type::HLSLAttributedResource: {
12288 const HLSLAttributedResourceType *LHSTy =
12289 LHS->castAs<HLSLAttributedResourceType>();
12290 const HLSLAttributedResourceType *RHSTy =
12291 RHS->castAs<HLSLAttributedResourceType>();
12292 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12293 LHSTy->getWrappedType()->isHLSLResourceType() &&
12294 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12295
12296 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12297 LHSTy->getContainedType() == RHSTy->getContainedType())
12298 return LHS;
12299 return {};
12300 }
12301 case Type::HLSLInlineSpirv:
12302 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12303 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12304
12305 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12306 LHSTy->getSize() == RHSTy->getSize() &&
12307 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12308 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12309 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12310 return {};
12311
12312 return LHS;
12313 }
12314 return {};
12315 }
12316
12317 llvm_unreachable("Invalid Type::Class!");
12318}
12319
12321 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12322 bool &CanUseFirst, bool &CanUseSecond,
12324 assert(NewParamInfos.empty() && "param info list not empty");
12325 CanUseFirst = CanUseSecond = true;
12326 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12327 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12328
12329 // Fast path: if the first type doesn't have ext parameter infos,
12330 // we match if and only if the second type also doesn't have them.
12331 if (!FirstHasInfo && !SecondHasInfo)
12332 return true;
12333
12334 bool NeedParamInfo = false;
12335 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12336 : SecondFnType->getExtParameterInfos().size();
12337
12338 for (size_t I = 0; I < E; ++I) {
12339 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12340 if (FirstHasInfo)
12341 FirstParam = FirstFnType->getExtParameterInfo(I);
12342 if (SecondHasInfo)
12343 SecondParam = SecondFnType->getExtParameterInfo(I);
12344
12345 // Cannot merge unless everything except the noescape flag matches.
12346 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12347 return false;
12348
12349 bool FirstNoEscape = FirstParam.isNoEscape();
12350 bool SecondNoEscape = SecondParam.isNoEscape();
12351 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12352 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12353 if (NewParamInfos.back().getOpaqueValue())
12354 NeedParamInfo = true;
12355 if (FirstNoEscape != IsNoEscape)
12356 CanUseFirst = false;
12357 if (SecondNoEscape != IsNoEscape)
12358 CanUseSecond = false;
12359 }
12360
12361 if (!NeedParamInfo)
12362 NewParamInfos.clear();
12363
12364 return true;
12365}
12366
12368 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12369 It->second = nullptr;
12370 for (auto *SubClass : ObjCSubClasses.lookup(D))
12371 ResetObjCLayout(SubClass);
12372 }
12373}
12374
12375/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12376/// 'RHS' attributes and returns the merged version; including for function
12377/// return types.
12379 QualType LHSCan = getCanonicalType(LHS),
12380 RHSCan = getCanonicalType(RHS);
12381 // If two types are identical, they are compatible.
12382 if (LHSCan == RHSCan)
12383 return LHS;
12384 if (RHSCan->isFunctionType()) {
12385 if (!LHSCan->isFunctionType())
12386 return {};
12387 QualType OldReturnType =
12388 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12389 QualType NewReturnType =
12390 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12391 QualType ResReturnType =
12392 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12393 if (ResReturnType.isNull())
12394 return {};
12395 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12396 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12397 // In either case, use OldReturnType to build the new function type.
12398 const auto *F = LHS->castAs<FunctionType>();
12399 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12400 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12401 EPI.ExtInfo = getFunctionExtInfo(LHS);
12402 QualType ResultType =
12403 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12404 return ResultType;
12405 }
12406 }
12407 return {};
12408 }
12409
12410 // If the qualifiers are different, the types can still be merged.
12411 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12412 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12413
12414 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12415 // Reject immediately, if anything but the GC qualifiers is different.
12416 return {};
12417 }
12418
12419 if (LQuals != RQuals) {
12420 // Exactly one GC qualifier difference is allowed: __strong is
12421 // okay if the other type has no GC qualifier but is an Objective
12422 // C object pointer (i.e. implicitly strong by default). We fix
12423 // this by pretending that the unqualified type was actually
12424 // qualified __strong.
12425 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12426 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12427 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12428
12429 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12430 return {};
12431
12432 if (GC_L == Qualifiers::Strong)
12433 return LHS;
12434 if (GC_R == Qualifiers::Strong)
12435 return RHS;
12436 return {};
12437 }
12438
12439 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12440 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12441 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12442 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12443 if (ResQT == LHSBaseQT)
12444 return LHS;
12445 if (ResQT == RHSBaseQT)
12446 return RHS;
12447 }
12448 return {};
12449}
12450
12451//===----------------------------------------------------------------------===//
12452// Integer Predicates
12453//===----------------------------------------------------------------------===//
12454
12456 if (const auto *ED = T->getAsEnumDecl())
12457 T = ED->getIntegerType();
12458 if (T->isBooleanType())
12459 return 1;
12460 if (const auto *EIT = T->getAs<BitIntType>())
12461 return EIT->getNumBits();
12462 // For builtin types, just use the standard type sizing method
12463 return (unsigned)getTypeSize(T);
12464}
12465
12467 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12468 T->isFixedPointType()) &&
12469 "Unexpected type");
12470
12471 // Turn <4 x signed int> -> <4 x unsigned int>
12472 if (const auto *VTy = T->getAs<VectorType>())
12473 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12474 VTy->getNumElements(), VTy->getVectorKind());
12475
12476 // For _BitInt, return an unsigned _BitInt with same width.
12477 if (const auto *EITy = T->getAs<BitIntType>())
12478 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12479
12480 // For the overflow behavior types, construct a new unsigned variant
12481 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12483 OBT->getBehaviorKind(),
12484 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12485
12486 // For enums, get the underlying integer type of the enum, and let the general
12487 // integer type signchanging code handle it.
12488 if (const auto *ED = T->getAsEnumDecl())
12489 T = ED->getIntegerType();
12490
12491 switch (T->castAs<BuiltinType>()->getKind()) {
12492 case BuiltinType::Char_U:
12493 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12494 case BuiltinType::Char_S:
12495 case BuiltinType::SChar:
12496 case BuiltinType::Char8:
12497 return UnsignedCharTy;
12498 case BuiltinType::Short:
12499 return UnsignedShortTy;
12500 case BuiltinType::Int:
12501 return UnsignedIntTy;
12502 case BuiltinType::Long:
12503 return UnsignedLongTy;
12504 case BuiltinType::LongLong:
12505 return UnsignedLongLongTy;
12506 case BuiltinType::Int128:
12507 return UnsignedInt128Ty;
12508 // wchar_t is special. It is either signed or not, but when it's signed,
12509 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12510 // version of its underlying type instead.
12511 case BuiltinType::WChar_S:
12512 return getUnsignedWCharType();
12513
12514 case BuiltinType::ShortAccum:
12515 return UnsignedShortAccumTy;
12516 case BuiltinType::Accum:
12517 return UnsignedAccumTy;
12518 case BuiltinType::LongAccum:
12519 return UnsignedLongAccumTy;
12520 case BuiltinType::SatShortAccum:
12522 case BuiltinType::SatAccum:
12523 return SatUnsignedAccumTy;
12524 case BuiltinType::SatLongAccum:
12526 case BuiltinType::ShortFract:
12527 return UnsignedShortFractTy;
12528 case BuiltinType::Fract:
12529 return UnsignedFractTy;
12530 case BuiltinType::LongFract:
12531 return UnsignedLongFractTy;
12532 case BuiltinType::SatShortFract:
12534 case BuiltinType::SatFract:
12535 return SatUnsignedFractTy;
12536 case BuiltinType::SatLongFract:
12538 default:
12539 assert((T->hasUnsignedIntegerRepresentation() ||
12540 T->isUnsignedFixedPointType()) &&
12541 "Unexpected signed integer or fixed point type");
12542 return T;
12543 }
12544}
12545
12547 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12548 T->isFixedPointType()) &&
12549 "Unexpected type");
12550
12551 // Turn <4 x unsigned int> -> <4 x signed int>
12552 if (const auto *VTy = T->getAs<VectorType>())
12553 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12554 VTy->getNumElements(), VTy->getVectorKind());
12555
12556 // For _BitInt, return a signed _BitInt with same width.
12557 if (const auto *EITy = T->getAs<BitIntType>())
12558 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12559
12560 // For enums, get the underlying integer type of the enum, and let the general
12561 // integer type signchanging code handle it.
12562 if (const auto *ED = T->getAsEnumDecl())
12563 T = ED->getIntegerType();
12564
12565 switch (T->castAs<BuiltinType>()->getKind()) {
12566 case BuiltinType::Char_S:
12567 // Plain `char` is mapped to `signed char` even if it's already signed
12568 case BuiltinType::Char_U:
12569 case BuiltinType::UChar:
12570 case BuiltinType::Char8:
12571 return SignedCharTy;
12572 case BuiltinType::UShort:
12573 return ShortTy;
12574 case BuiltinType::UInt:
12575 return IntTy;
12576 case BuiltinType::ULong:
12577 return LongTy;
12578 case BuiltinType::ULongLong:
12579 return LongLongTy;
12580 case BuiltinType::UInt128:
12581 return Int128Ty;
12582 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12583 // there's no matching "signed wchar_t". Therefore we return the signed
12584 // version of its underlying type instead.
12585 case BuiltinType::WChar_U:
12586 return getSignedWCharType();
12587
12588 case BuiltinType::UShortAccum:
12589 return ShortAccumTy;
12590 case BuiltinType::UAccum:
12591 return AccumTy;
12592 case BuiltinType::ULongAccum:
12593 return LongAccumTy;
12594 case BuiltinType::SatUShortAccum:
12595 return SatShortAccumTy;
12596 case BuiltinType::SatUAccum:
12597 return SatAccumTy;
12598 case BuiltinType::SatULongAccum:
12599 return SatLongAccumTy;
12600 case BuiltinType::UShortFract:
12601 return ShortFractTy;
12602 case BuiltinType::UFract:
12603 return FractTy;
12604 case BuiltinType::ULongFract:
12605 return LongFractTy;
12606 case BuiltinType::SatUShortFract:
12607 return SatShortFractTy;
12608 case BuiltinType::SatUFract:
12609 return SatFractTy;
12610 case BuiltinType::SatULongFract:
12611 return SatLongFractTy;
12612 default:
12613 assert(
12614 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12615 "Unexpected signed integer or fixed point type");
12616 return T;
12617 }
12618}
12619
12621
12624
12625//===----------------------------------------------------------------------===//
12626// Builtin Type Computation
12627//===----------------------------------------------------------------------===//
12628
12629/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12630/// pointer over the consumed characters. This returns the resultant type. If
12631/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12632/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12633/// a vector of "i*".
12634///
12635/// RequiresICE is filled in on return to indicate whether the value is required
12636/// to be an Integer Constant Expression.
12637static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12639 bool &RequiresICE,
12640 bool AllowTypeModifiers) {
12641 // Modifiers.
12642 int HowLong = 0;
12643 bool Signed = false, Unsigned = false;
12644 bool IsChar = false, IsShort = false;
12645 bool IsLeast = false;
12646 RequiresICE = false;
12647
12648 // Read the prefixed modifiers first.
12649 bool Done = false;
12650 #ifndef NDEBUG
12651 bool IsSpecial = false;
12652 #endif
12653 while (!Done) {
12654 switch (*Str++) {
12655 default: Done = true; --Str; break;
12656 case 'I':
12657 RequiresICE = true;
12658 break;
12659 case 'S':
12660 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12661 assert(!Signed && "Can't use 'S' modifier multiple times!");
12662 Signed = true;
12663 break;
12664 case 'U':
12665 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12666 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12667 Unsigned = true;
12668 break;
12669 case 'l':
12670 // This modifier represents the least-width type (e.g. uint_least8_t).
12671 assert(!IsLeast && "Can't use 'l' modifier multiple times!");
12672 IsLeast = true;
12673 break;
12674 case 'B':
12675 // This modifier represents int8 type (byte-width).
12676 assert(!IsSpecial &&
12677 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12678 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12679#ifndef NDEBUG
12680 IsSpecial = true;
12681#endif
12682 IsChar = true;
12683 break;
12684 case 'T':
12685 // This modifier represents int16 type (short-width).
12686 assert(!IsSpecial &&
12687 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12688 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12689#ifndef NDEBUG
12690 IsSpecial = true;
12691#endif
12692 IsShort = true;
12693 break;
12694 case 'L':
12695 assert(!IsSpecial &&
12696 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12697 assert(HowLong <= 2 && "Can't have LLLL modifier");
12698 ++HowLong;
12699 break;
12700 case 'N':
12701 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12702 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12703 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12704 #ifndef NDEBUG
12705 IsSpecial = true;
12706 #endif
12707 if (Context.getTargetInfo().getLongWidth() == 32)
12708 ++HowLong;
12709 break;
12710 case 'W':
12711 // This modifier represents int64 type.
12712 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12713 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12714 #ifndef NDEBUG
12715 IsSpecial = true;
12716 #endif
12717 switch (Context.getTargetInfo().getInt64Type()) {
12718 default:
12719 llvm_unreachable("Unexpected integer type");
12721 HowLong = 1;
12722 break;
12724 HowLong = 2;
12725 break;
12726 }
12727 break;
12728 case 'Z':
12729 // This modifier represents int32 type.
12730 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12731 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12732 #ifndef NDEBUG
12733 IsSpecial = true;
12734 #endif
12735 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12736 default:
12737 llvm_unreachable("Unexpected integer type");
12739 HowLong = 0;
12740 break;
12742 HowLong = 1;
12743 break;
12745 HowLong = 2;
12746 break;
12747 }
12748 break;
12749 case 'O':
12750 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12751 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12752 #ifndef NDEBUG
12753 IsSpecial = true;
12754 #endif
12755 if (Context.getLangOpts().OpenCL)
12756 HowLong = 1;
12757 else
12758 HowLong = 2;
12759 break;
12760 }
12761 }
12762
12763 QualType Type;
12764
12765 // Read the base type.
12766 switch (*Str++) {
12767 default:
12768 llvm_unreachable("Unknown builtin type letter!");
12769 case 'x':
12770 assert(HowLong == 0 && !Signed && !Unsigned &&
12771 "Bad modifiers used with 'x'!");
12772 Type = Context.Float16Ty;
12773 break;
12774 case 'y':
12775 assert(HowLong == 0 && !Signed && !Unsigned &&
12776 "Bad modifiers used with 'y'!");
12777 Type = Context.BFloat16Ty;
12778 break;
12779 case 'v':
12780 assert(HowLong == 0 && !Signed && !Unsigned &&
12781 "Bad modifiers used with 'v'!");
12782 Type = Context.VoidTy;
12783 break;
12784 case 'h':
12785 assert(HowLong == 0 && !Signed && !Unsigned &&
12786 "Bad modifiers used with 'h'!");
12787 Type = Context.HalfTy;
12788 break;
12789 case 'f':
12790 assert(HowLong == 0 && !Signed && !Unsigned &&
12791 "Bad modifiers used with 'f'!");
12792 Type = Context.FloatTy;
12793 break;
12794 case 'd':
12795 assert(HowLong < 3 && !Signed && !Unsigned &&
12796 "Bad modifiers used with 'd'!");
12797 if (HowLong == 1)
12798 Type = Context.LongDoubleTy;
12799 else if (HowLong == 2)
12800 Type = Context.Float128Ty;
12801 else
12802 Type = Context.DoubleTy;
12803 break;
12804 case 's':
12805 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12806 if (Unsigned)
12807 Type = Context.UnsignedShortTy;
12808 else
12809 Type = Context.ShortTy;
12810 break;
12811 case 'i':
12812 if (IsChar)
12813 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12814 else if (IsShort)
12815 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12816 else if (HowLong == 3)
12817 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12818 else if (HowLong == 2)
12819 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12820 else if (HowLong == 1)
12821 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12822 else
12823 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12824 if (IsLeast)
12825 Type = Context.getLeastIntTypeForBitwidth(Context.getIntWidth(Type),
12826 /*Signed=*/!Unsigned);
12827 break;
12828 case 'c':
12829 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12830 if (Signed)
12831 Type = Context.SignedCharTy;
12832 else if (Unsigned)
12833 Type = Context.UnsignedCharTy;
12834 else
12835 Type = Context.CharTy;
12836 break;
12837 case 'b': // boolean
12838 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12839 Type = Context.BoolTy;
12840 break;
12841 case 'z': // size_t.
12842 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12843 Type = Context.getSizeType();
12844 break;
12845 case 'w': // wchar_t.
12846 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12847 Type = Context.getWideCharType();
12848 break;
12849 case 'F':
12850 Type = Context.getCFConstantStringType();
12851 break;
12852 case 'G':
12853 Type = Context.getObjCIdType();
12854 break;
12855 case 'H':
12856 Type = Context.getObjCSelType();
12857 break;
12858 case 'M':
12859 Type = Context.getObjCSuperType();
12860 break;
12861 case 'r':
12862 Type = Context.MetaInfoTy;
12863 break;
12864 case 'a':
12865 Type = Context.getBuiltinVaListType();
12866 assert(!Type.isNull() && "builtin va list type not initialized!");
12867 break;
12868 case 'A':
12869 // This is a "reference" to a va_list; however, what exactly
12870 // this means depends on how va_list is defined. There are two
12871 // different kinds of va_list: ones passed by value, and ones
12872 // passed by reference. An example of a by-value va_list is
12873 // x86, where va_list is a char*. An example of by-ref va_list
12874 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12875 // we want this argument to be a char*&; for x86-64, we want
12876 // it to be a __va_list_tag*.
12877 Type = Context.getBuiltinVaListType();
12878 assert(!Type.isNull() && "builtin va list type not initialized!");
12879 if (Type->isArrayType())
12880 Type = Context.getArrayDecayedType(Type);
12881 else
12882 Type = Context.getLValueReferenceType(Type);
12883 break;
12884 case 'q': {
12885 char *End;
12886 unsigned NumElements = strtoul(Str, &End, 10);
12887 assert(End != Str && "Missing vector size");
12888 Str = End;
12889
12890 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12891 RequiresICE, false);
12892 assert(!RequiresICE && "Can't require vector ICE");
12893
12894 Type = Context.getScalableVectorType(ElementType, NumElements);
12895 break;
12896 }
12897 case 'Q': {
12898 switch (*Str++) {
12899 case 'a': {
12900 Type = Context.SveCountTy;
12901 break;
12902 }
12903 case 'b': {
12904 Type = Context.AMDGPUBufferRsrcTy;
12905 break;
12906 }
12907 case 'c': {
12908 Type = Context.AMDGPUFeaturePredicateTy;
12909 break;
12910 }
12911 case 't': {
12912 Type = Context.AMDGPUTextureTy;
12913 break;
12914 }
12915 case 'r': {
12916 Type = Context.HLSLResourceTy;
12917 break;
12918 }
12919 default:
12920 llvm_unreachable("Unexpected target builtin type");
12921 }
12922 break;
12923 }
12924 case 'V': {
12925 char *End;
12926 unsigned NumElements = strtoul(Str, &End, 10);
12927 assert(End != Str && "Missing vector size");
12928 Str = End;
12929
12930 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12931 RequiresICE, false);
12932 assert(!RequiresICE && "Can't require vector ICE");
12933
12934 // TODO: No way to make AltiVec vectors in builtins yet.
12935 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12936 break;
12937 }
12938 case 'E': {
12939 char *End;
12940
12941 unsigned NumElements = strtoul(Str, &End, 10);
12942 assert(End != Str && "Missing vector size");
12943
12944 Str = End;
12945
12946 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12947 false);
12948 Type = Context.getExtVectorType(ElementType, NumElements);
12949 break;
12950 }
12951 case 'X': {
12952 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12953 false);
12954 assert(!RequiresICE && "Can't require complex ICE");
12955 Type = Context.getComplexType(ElementType);
12956 break;
12957 }
12958 case 'Y':
12959 Type = Context.getPointerDiffType();
12960 break;
12961 case 'P':
12962 Type = Context.getFILEType();
12963 if (Type.isNull()) {
12965 return {};
12966 }
12967 break;
12968 case 'J':
12969 if (Signed)
12970 Type = Context.getsigjmp_bufType();
12971 else
12972 Type = Context.getjmp_bufType();
12973
12974 if (Type.isNull()) {
12976 return {};
12977 }
12978 break;
12979 case 'K':
12980 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12981 Type = Context.getucontext_tType();
12982
12983 if (Type.isNull()) {
12985 return {};
12986 }
12987 break;
12988 case 'p':
12989 Type = Context.getProcessIDType();
12990 break;
12991 case 'm':
12992 Type = Context.MFloat8Ty;
12993 break;
12994 }
12995
12996 // If there are modifiers and if we're allowed to parse them, go for it.
12997 Done = !AllowTypeModifiers;
12998 while (!Done) {
12999 switch (char c = *Str++) {
13000 default: Done = true; --Str; break;
13001 case '*':
13002 case '&': {
13003 // Both pointers and references can have their pointee types
13004 // qualified with an address space.
13005 char *End;
13006 unsigned AddrSpace = strtoul(Str, &End, 10);
13007 if (End != Str) {
13008 // Note AddrSpace == 0 is not the same as an unspecified address space.
13009 Type = Context.getAddrSpaceQualType(
13010 Type,
13011 Context.getLangASForBuiltinAddressSpace(AddrSpace));
13012 Str = End;
13013 }
13014 if (c == '*')
13015 Type = Context.getPointerType(Type);
13016 else
13017 Type = Context.getLValueReferenceType(Type);
13018 break;
13019 }
13020 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13021 case 'C':
13022 Type = Type.withConst();
13023 break;
13024 case 'D':
13025 Type = Context.getVolatileType(Type);
13026 break;
13027 case 'R':
13028 Type = Type.withRestrict();
13029 break;
13030 }
13031 }
13032
13033 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13034 "Integer constant 'I' type must be an integer");
13035
13036 return Type;
13037}
13038
13039// On some targets such as PowerPC, some of the builtins are defined with custom
13040// type descriptors for target-dependent types. These descriptors are decoded in
13041// other functions, but it may be useful to be able to fall back to default
13042// descriptor decoding to define builtins mixing target-dependent and target-
13043// independent types. This function allows decoding one type descriptor with
13044// default decoding.
13045QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13046 GetBuiltinTypeError &Error, bool &RequireICE,
13047 bool AllowTypeModifiers) const {
13048 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13049}
13050
13051/// GetBuiltinType - Return the type for the specified builtin.
13054 unsigned *IntegerConstantArgs) const {
13055 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13056 if (TypeStr[0] == '\0') {
13058 return {};
13059 }
13060
13061 SmallVector<QualType, 8> ArgTypes;
13062
13063 bool RequiresICE = false;
13064 Error = GE_None;
13065 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13066 RequiresICE, true);
13067 if (Error != GE_None)
13068 return {};
13069
13070 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13071
13072 while (TypeStr[0] && TypeStr[0] != '.') {
13073 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13074 if (Error != GE_None)
13075 return {};
13076
13077 // If this argument is required to be an IntegerConstantExpression and the
13078 // caller cares, fill in the bitmask we return.
13079 if (RequiresICE && IntegerConstantArgs)
13080 *IntegerConstantArgs |= 1 << ArgTypes.size();
13081
13082 // Do array -> pointer decay. The builtin should use the decayed type.
13083 if (Ty->isArrayType())
13084 Ty = getArrayDecayedType(Ty);
13085
13086 ArgTypes.push_back(Ty);
13087 }
13088
13089 if (Id == Builtin::BI__GetExceptionInfo)
13090 return {};
13091
13092 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13093 "'.' should only occur at end of builtin type list!");
13094
13095 bool Variadic = (TypeStr[0] == '.');
13096
13097 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13098 if (BuiltinInfo.isNoReturn(Id))
13099 EI = EI.withNoReturn(true);
13100
13101 // We really shouldn't be making a no-proto type here.
13102 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13103 return getFunctionNoProtoType(ResType, EI);
13104
13106 EPI.ExtInfo = EI;
13107 EPI.Variadic = Variadic;
13108 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13109 EPI.ExceptionSpec.Type =
13111
13112 return getFunctionType(ResType, ArgTypes, EPI);
13113}
13114
13116 const FunctionDecl *FD) {
13117 if (!FD->isExternallyVisible())
13118 return GVA_Internal;
13119
13120 // Non-user-provided functions get emitted as weak definitions with every
13121 // use, no matter whether they've been explicitly instantiated etc.
13122 if (!FD->isUserProvided())
13123 return GVA_DiscardableODR;
13124
13126 switch (FD->getTemplateSpecializationKind()) {
13127 case TSK_Undeclared:
13130 break;
13131
13133 return GVA_StrongODR;
13134
13135 // C++11 [temp.explicit]p10:
13136 // [ Note: The intent is that an inline function that is the subject of
13137 // an explicit instantiation declaration will still be implicitly
13138 // instantiated when used so that the body can be considered for
13139 // inlining, but that no out-of-line copy of the inline function would be
13140 // generated in the translation unit. -- end note ]
13143
13146 break;
13147 }
13148
13149 if (!FD->isInlined())
13150 return External;
13151
13152 if ((!Context.getLangOpts().CPlusPlus &&
13153 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13154 !FD->hasAttr<DLLExportAttr>()) ||
13155 FD->hasAttr<GNUInlineAttr>()) {
13156 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13157
13158 // GNU or C99 inline semantics. Determine whether this symbol should be
13159 // externally visible.
13160 if (auto *Def = FD->getDefinition();
13162 return External;
13163
13164 // C99 inline semantics, where the symbol is not externally visible.
13166 }
13167
13168 // Functions specified with extern and inline in -fms-compatibility mode
13169 // forcibly get emitted. While the body of the function cannot be later
13170 // replaced, the function definition cannot be discarded.
13171 if (FD->isMSExternInline())
13172 return GVA_StrongODR;
13173
13174 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13176 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13177 !FD->hasAttr<DLLExportAttr>()) {
13178 // Both Clang and MSVC implement inherited constructors as forwarding
13179 // thunks that delegate to the base constructor. Keep non-dllexport
13180 // inheriting constructor thunks internal since they are not needed
13181 // outside the translation unit.
13182 //
13183 // dllexport inherited constructors are exempted so they are externally
13184 // visible, matching MSVC's export behavior. Inherited constructors
13185 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13186 // cleanup types) are excluded from export in Sema to avoid silent
13187 // runtime mismatches.
13188 return GVA_Internal;
13189 }
13190
13191 return GVA_DiscardableODR;
13192}
13193
13195 const Decl *D, GVALinkage L) {
13196 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13197 // dllexport/dllimport on inline functions.
13198 if (D->hasAttr<DLLImportAttr>()) {
13199 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13201 } else if (D->hasAttr<DLLExportAttr>()) {
13202 if (L == GVA_DiscardableODR)
13203 return GVA_StrongODR;
13204 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13205 // Device-side functions with __global__ attribute must always be
13206 // visible externally so they can be launched from host.
13207 if (D->hasAttr<CUDAGlobalAttr>() &&
13208 (L == GVA_DiscardableODR || L == GVA_Internal))
13209 return GVA_StrongODR;
13210 // Single source offloading languages like CUDA/HIP need to be able to
13211 // access static device variables from host code of the same compilation
13212 // unit. This is done by externalizing the static variable with a shared
13213 // name between the host and device compilation which is the same for the
13214 // same compilation unit whereas different among different compilation
13215 // units.
13216 if (Context.shouldExternalize(D))
13217 return GVA_StrongExternal;
13218 }
13219 return L;
13220}
13221
13222/// Adjust the GVALinkage for a declaration based on what an external AST source
13223/// knows about whether there can be other definitions of this declaration.
13224static GVALinkage
13226 GVALinkage L) {
13227 ExternalASTSource *Source = Ctx.getExternalSource();
13228 if (!Source)
13229 return L;
13230
13231 switch (Source->hasExternalDefinitions(D)) {
13233 // Other translation units rely on us to provide the definition.
13234 if (L == GVA_DiscardableODR)
13235 return GVA_StrongODR;
13236 break;
13237
13240
13242 break;
13243 }
13244 return L;
13245}
13246
13252
13254 const VarDecl *VD) {
13255 // As an extension for interactive REPLs, make sure constant variables are
13256 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13257 // marking them as internal.
13258 if (Context.getLangOpts().CPlusPlus &&
13259 Context.getLangOpts().IncrementalExtensions &&
13260 VD->getType().isConstQualified() &&
13261 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13263 return GVA_DiscardableODR;
13264
13265 if (!VD->isExternallyVisible())
13266 return GVA_Internal;
13267
13268 if (VD->isStaticLocal()) {
13269 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13270 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13271 LexicalContext = LexicalContext->getLexicalParent();
13272
13273 // ObjC Blocks can create local variables that don't have a FunctionDecl
13274 // LexicalContext.
13275 if (!LexicalContext)
13276 return GVA_DiscardableODR;
13277
13278 // Otherwise, let the static local variable inherit its linkage from the
13279 // nearest enclosing function.
13280 auto StaticLocalLinkage =
13281 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13282
13283 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13284 // be emitted in any object with references to the symbol for the object it
13285 // contains, whether inline or out-of-line."
13286 // Similar behavior is observed with MSVC. An alternative ABI could use
13287 // StrongODR/AvailableExternally to match the function, but none are
13288 // known/supported currently.
13289 if (StaticLocalLinkage == GVA_StrongODR ||
13290 StaticLocalLinkage == GVA_AvailableExternally)
13291 return GVA_DiscardableODR;
13292 return StaticLocalLinkage;
13293 }
13294
13295 // MSVC treats in-class initialized static data members as definitions.
13296 // By giving them non-strong linkage, out-of-line definitions won't
13297 // cause link errors.
13298 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13299 return GVA_DiscardableODR;
13300
13301 // Most non-template variables have strong linkage; inline variables are
13302 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13303 GVALinkage StrongLinkage;
13304 switch (Context.getInlineVariableDefinitionKind(VD)) {
13306 StrongLinkage = GVA_StrongExternal;
13307 break;
13310 StrongLinkage = GVA_DiscardableODR;
13311 break;
13313 StrongLinkage = GVA_StrongODR;
13314 break;
13315 }
13316
13317 switch (VD->getTemplateSpecializationKind()) {
13318 case TSK_Undeclared:
13319 return StrongLinkage;
13320
13322 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13323 VD->isStaticDataMember()
13325 : StrongLinkage;
13326
13328 return GVA_StrongODR;
13329
13332
13334 return GVA_DiscardableODR;
13335 }
13336
13337 llvm_unreachable("Invalid Linkage!");
13338}
13339
13345
13347 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13348 if (!VD->isFileVarDecl())
13349 return false;
13350 // Global named register variables (GNU extension) are never emitted.
13351 if (VD->getStorageClass() == SC_Register)
13352 return false;
13353 if (VD->getDescribedVarTemplate() ||
13355 return false;
13356 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13357 // We never need to emit an uninstantiated function template.
13358 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13359 return false;
13360 } else if (isa<PragmaCommentDecl>(D))
13361 return true;
13363 return true;
13364 else if (isa<OMPRequiresDecl>(D))
13365 return true;
13366 else if (isa<OMPThreadPrivateDecl>(D))
13367 return !D->getDeclContext()->isDependentContext();
13368 else if (isa<OMPAllocateDecl>(D))
13369 return !D->getDeclContext()->isDependentContext();
13371 return !D->getDeclContext()->isDependentContext();
13372 else if (isa<ImportDecl>(D))
13373 return true;
13374 else
13375 return false;
13376
13377 // If this is a member of a class template, we do not need to emit it.
13379 return false;
13380
13381 // Weak references don't produce any output by themselves.
13382 if (D->hasAttr<WeakRefAttr>())
13383 return false;
13384
13385 // SYCL device compilation requires that functions defined with the
13386 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13387 // other entities are emitted only if they are used by a function
13388 // defined with one of those attributes.
13389 if (LangOpts.SYCLIsDevice)
13390 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13391 D->hasAttr<SYCLExternalAttr>());
13392
13393 // Aliases and used decls are required.
13394 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13395 return true;
13396
13397 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13398 // Forward declarations aren't required.
13399 if (!FD->doesThisDeclarationHaveABody())
13400 return FD->doesDeclarationForceExternallyVisibleDefinition();
13401
13402 // Constructors and destructors are required.
13403 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13404 return true;
13405
13406 // The key function for a class is required. This rule only comes
13407 // into play when inline functions can be key functions, though.
13408 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13409 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13410 const CXXRecordDecl *RD = MD->getParent();
13411 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13412 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13413 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13414 return true;
13415 }
13416 }
13417 }
13418
13420
13421 // static, static inline, always_inline, and extern inline functions can
13422 // always be deferred. Normal inline functions can be deferred in C99/C++.
13423 // Implicit template instantiations can also be deferred in C++.
13425 }
13426
13427 const auto *VD = cast<VarDecl>(D);
13428 assert(VD->isFileVarDecl() && "Expected file scoped var");
13429
13430 // If the decl is marked as `declare target to`, it should be emitted for the
13431 // host and for the device.
13432 if (LangOpts.OpenMP &&
13433 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13434 return true;
13435
13436 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13438 return false;
13439
13440 if (VD->shouldEmitInExternalSource())
13441 return false;
13442
13443 // Variables that can be needed in other TUs are required.
13446 return true;
13447
13448 // We never need to emit a variable that is available in another TU.
13450 return false;
13451
13452 // Variables that have destruction with side-effects are required.
13453 if (VD->needsDestruction(*this))
13454 return true;
13455
13456 // Variables that have initialization with side-effects are required.
13457 if (VD->hasInitWithSideEffects())
13458 return true;
13459
13460 // Likewise, variables with tuple-like bindings are required if their
13461 // bindings have side-effects.
13462 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13463 for (const auto *BD : DD->flat_bindings())
13464 if (const auto *BindingVD = BD->getHoldingVar())
13465 if (DeclMustBeEmitted(BindingVD))
13466 return true;
13467 }
13468
13469 return false;
13470}
13471
13472template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
13473 if (auto *A = D->getAttr<AttrT>())
13474 return A->isImplicit();
13475 return D->isImplicit();
13476}
13477
13479 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
13480 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
13481 "Expected Variable or Function");
13482
13483 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13484 // We need to emit host-side 'shadows' for all global device-side variables
13485 // because the CUDA runtime needs their size and host-side address in order
13486 // to provide access to their device-side incarnations.
13487 return !LangOpts.CUDAIsDevice || VD->hasAttr<CUDADeviceAttr>() ||
13488 VD->hasAttr<CUDAConstantAttr>() || VD->hasAttr<CUDASharedAttr>() ||
13489 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
13490 VD->getType()->isCUDADeviceBuiltinTextureType();
13491 }
13492
13493 const auto *FD = cast<FunctionDecl>(D);
13494 // Device-only functions are the only things we skip on the host.
13495 if (!LangOpts.CUDAIsDevice)
13496 return FD->hasAttr<CUDAHostAttr>() || !FD->hasAttr<CUDADeviceAttr>();
13497
13498 // Non-constexpr non-lambda implicit host device functions are not emitted
13499 // unless they are used on device side.
13500 return (FD->hasAttr<CUDADeviceAttr>() &&
13501 !(LangOpts.OffloadImplicitHostDeviceTemplates &&
13503 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
13504 !isLambdaCallOperator(FD) &&
13506 FD->hasAttr<CUDAGlobalAttr>() ||
13507 (LangOpts.HIPStdPar && !FD->hasAttr<CUDAHostAttr>());
13508}
13509
13511 const FunctionDecl *FD,
13512 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13513 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13514 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13515 FD = FD->getMostRecentDecl();
13516 // FIXME: The order of traversal here matters and depends on the order of
13517 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13518 // shouldn't rely on that.
13519 for (auto *CurDecl :
13521 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13522 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13523 SeenDecls.insert(CurFD).second) {
13524 Pred(CurFD);
13525 }
13526 }
13527}
13528
13530 bool IsCXXMethod) const {
13531 // Pass through to the C++ ABI object
13532 if (IsCXXMethod)
13533 return ABI->getDefaultMethodCallConv(IsVariadic);
13534
13535 switch (LangOpts.getDefaultCallingConv()) {
13537 break;
13539 return CC_C;
13541 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13542 return CC_X86FastCall;
13543 break;
13545 if (!IsVariadic)
13546 return CC_X86StdCall;
13547 break;
13549 // __vectorcall cannot be applied to variadic functions.
13550 if (!IsVariadic)
13551 return CC_X86VectorCall;
13552 break;
13554 // __regcall cannot be applied to variadic functions.
13555 if (!IsVariadic)
13556 return CC_X86RegCall;
13557 break;
13559 if (!IsVariadic)
13560 return CC_M68kRTD;
13561 break;
13562 }
13563 return Target->getDefaultCallingConv();
13564}
13565
13567 // Pass through to the C++ ABI object
13568 return ABI->isNearlyEmpty(RD);
13569}
13570
13572 if (!VTContext) {
13573 auto ABI = Target->getCXXABI();
13574 if (ABI.isMicrosoft())
13575 VTContext.reset(new MicrosoftVTableContext(*this));
13576 else {
13577 VTContext.reset(new ItaniumVTableContext(*this));
13578 }
13579 }
13580 return VTContext.get();
13581}
13582
13584 if (!T)
13585 T = Target;
13586 switch (T->getCXXABI().getKind()) {
13587 case TargetCXXABI::AppleARM64:
13588 case TargetCXXABI::Fuchsia:
13589 case TargetCXXABI::GenericAArch64:
13590 case TargetCXXABI::GenericItanium:
13591 case TargetCXXABI::GenericARM:
13592 case TargetCXXABI::GenericMIPS:
13593 case TargetCXXABI::iOS:
13594 case TargetCXXABI::WebAssembly:
13595 case TargetCXXABI::WatchOS:
13596 case TargetCXXABI::XL:
13598 case TargetCXXABI::Microsoft:
13600 }
13601 llvm_unreachable("Unsupported ABI");
13602}
13603
13605 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13606 "Device mangle context does not support Microsoft mangling.");
13607 switch (T.getCXXABI().getKind()) {
13608 case TargetCXXABI::AppleARM64:
13609 case TargetCXXABI::Fuchsia:
13610 case TargetCXXABI::GenericAArch64:
13611 case TargetCXXABI::GenericItanium:
13612 case TargetCXXABI::GenericARM:
13613 case TargetCXXABI::GenericMIPS:
13614 case TargetCXXABI::iOS:
13615 case TargetCXXABI::WebAssembly:
13616 case TargetCXXABI::WatchOS:
13617 case TargetCXXABI::XL:
13619 *this, getDiagnostics(),
13620 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13621 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13622 return RD->getDeviceLambdaManglingNumber();
13623 return std::nullopt;
13624 },
13625 /*IsAux=*/true);
13626 case TargetCXXABI::Microsoft:
13628 /*IsAux=*/true);
13629 }
13630 llvm_unreachable("Unsupported ABI");
13631}
13632
13634 // If the host and device have different C++ ABIs, mark it as the device
13635 // mangle context so that the mangling needs to retrieve the additional
13636 // device lambda mangling number instead of the regular host one.
13637 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13638 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13640 }
13641
13643}
13644
13645CXXABI::~CXXABI() = default;
13646
13648 return ASTRecordLayouts.getMemorySize() +
13649 llvm::capacity_in_bytes(ObjCLayouts) +
13650 llvm::capacity_in_bytes(KeyFunctions) +
13651 llvm::capacity_in_bytes(ObjCImpls) +
13652 llvm::capacity_in_bytes(BlockVarCopyInits) +
13653 DeclAttrAllocator.getTotalMemory() +
13654 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13655 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13656 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13657 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13658 llvm::capacity_in_bytes(OverriddenMethods) +
13659 llvm::capacity_in_bytes(Types) +
13660 llvm::capacity_in_bytes(VariableArrayTypes);
13661}
13662
13663/// getIntTypeForBitwidth -
13664/// sets integer QualTy according to specified details:
13665/// bitwidth, signed/unsigned.
13666/// Returns empty type if there is no appropriate target types.
13668 unsigned Signed) const {
13670 CanQualType QualTy = getFromTargetType(Ty);
13671 if (!QualTy && DestWidth == 128)
13672 return Signed ? Int128Ty : UnsignedInt128Ty;
13673 return QualTy;
13674}
13675
13677 unsigned Signed) const {
13678 return getFromTargetType(
13679 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13680}
13681
13682/// getRealTypeForBitwidth -
13683/// sets floating point QualTy according to specified bitwidth.
13684/// Returns empty type if there is no appropriate target types.
13686 FloatModeKind ExplicitType) const {
13687 FloatModeKind Ty =
13688 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13689 switch (Ty) {
13691 return HalfTy;
13693 return FloatTy;
13695 return DoubleTy;
13697 return LongDoubleTy;
13699 return Float128Ty;
13701 return Ibm128Ty;
13703 return {};
13704 }
13705
13706 llvm_unreachable("Unhandled TargetInfo::RealType value");
13707}
13708
13709void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13710 if (Number <= 1)
13711 return;
13712
13713 MangleNumbers[ND] = Number;
13714
13715 if (Listener)
13716 Listener->AddedManglingNumber(ND, Number);
13717}
13718
13720 bool ForAuxTarget) const {
13721 auto I = MangleNumbers.find(ND);
13722 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13723 // CUDA/HIP host compilation encodes host and device mangling numbers
13724 // as lower and upper half of 32 bit integer.
13725 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13726 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13727 } else {
13728 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13729 "number for aux target");
13730 }
13731 return Res > 1 ? Res : 1;
13732}
13733
13734void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13735 if (Number <= 1)
13736 return;
13737
13738 StaticLocalNumbers[VD] = Number;
13739
13740 if (Listener)
13741 Listener->AddedStaticLocalNumbers(VD, Number);
13742}
13743
13745 auto I = StaticLocalNumbers.find(VD);
13746 return I != StaticLocalNumbers.end() ? I->second : 1;
13747}
13748
13750 bool IsDestroying) {
13751 if (!IsDestroying) {
13752 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13753 return;
13754 }
13755 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13756}
13757
13759 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13760}
13761
13763 bool IsTypeAware) {
13764 if (!IsTypeAware) {
13765 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13766 return;
13767 }
13768 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13769}
13770
13772 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13773}
13774
13776 FunctionDecl *OperatorDelete,
13777 OperatorDeleteKind K) const {
13778 switch (K) {
13780 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13781 break;
13783 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13784 OperatorDelete;
13785 break;
13787 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13788 OperatorDelete;
13789 break;
13791 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13792 OperatorDelete;
13793 break;
13794 }
13795}
13796
13798 OperatorDeleteKind K) const {
13799 switch (K) {
13801 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13803 return GlobalOperatorDeletesForVirtualDtor.contains(
13804 Dtor->getCanonicalDecl());
13806 return ArrayOperatorDeletesForVirtualDtor.contains(
13807 Dtor->getCanonicalDecl());
13809 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13810 Dtor->getCanonicalDecl());
13811 }
13812 return false;
13813}
13814
13817 OperatorDeleteKind K) const {
13818 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13819 switch (K) {
13821 if (OperatorDeletesForVirtualDtor.contains(Canon))
13822 return OperatorDeletesForVirtualDtor[Canon];
13823 return nullptr;
13825 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13826 return GlobalOperatorDeletesForVirtualDtor[Canon];
13827 return nullptr;
13829 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13830 return ArrayOperatorDeletesForVirtualDtor[Canon];
13831 return nullptr;
13833 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13834 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13835 return nullptr;
13836 }
13837 return nullptr;
13838}
13839
13841 const CXXRecordDecl *RD) {
13842 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13843 return false;
13844
13845 return MaybeRequireVectorDeletingDtor.count(RD);
13846}
13847
13849 const CXXRecordDecl *RD) {
13850 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13851 return;
13852
13853 MaybeRequireVectorDeletingDtor.insert(RD);
13854}
13855
13858 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13859 // Reopened namespaces share a mangling context so that declarations in
13860 // different namespace blocks do not receive duplicate mangling numbers.
13861 DC = DC->getPrimaryContext();
13862 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13863 if (!MCtx)
13865 return *MCtx;
13866}
13867
13870 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13871 std::unique_ptr<MangleNumberingContext> &MCtx =
13872 ExtraMangleNumberingContexts[D];
13873 if (!MCtx)
13875 return *MCtx;
13876}
13877
13878std::unique_ptr<MangleNumberingContext>
13880 return ABI->createMangleNumberingContext();
13881}
13882
13883const CXXConstructorDecl *
13885 return ABI->getCopyConstructorForExceptionObject(
13887}
13888
13890 CXXConstructorDecl *CD) {
13891 return ABI->addCopyConstructorForExceptionObject(
13894}
13895
13897 TypedefNameDecl *DD) {
13898 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13899}
13900
13903 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13904}
13905
13907 DeclaratorDecl *DD) {
13908 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13909}
13910
13912 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13913}
13914
13916 ParamIndices[D] = index;
13917}
13918
13920 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13921 assert(I != ParamIndices.end() &&
13922 "ParmIndices lacks entry set by ParmVarDecl");
13923 return I->second;
13924}
13925
13927 unsigned Length) const {
13928 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13929 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13930 EltTy = EltTy.withConst();
13931
13932 EltTy = adjustStringLiteralBaseType(EltTy);
13933
13934 // Get an array type for the string, according to C99 6.4.5. This includes
13935 // the null terminator character.
13936 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13937 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13938}
13939
13942 StringLiteral *&Result = StringLiteralCache[Key];
13943 if (!Result)
13945 *this, Key, StringLiteralKind::Ordinary,
13946 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13947 SourceLocation());
13948 return Result;
13949}
13950
13951MSGuidDecl *
13953 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13954
13955 llvm::FoldingSetNodeID ID;
13956 MSGuidDecl::Profile(ID, Parts);
13957
13958 llvm::FoldingSetInsertToken Token;
13959 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13960 return Existing;
13961
13962 QualType GUIDType = getMSGuidType().withConst();
13963 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13964 MSGuidDecls.insert(New, Token);
13965 return New;
13966}
13967
13970 const APValue &APVal) const {
13971 llvm::FoldingSetNodeID ID;
13973
13974 llvm::FoldingSetInsertToken Token;
13975 if (UnnamedGlobalConstantDecl *Existing =
13976 UnnamedGlobalConstantDecls.lookup(ID, Token))
13977 return Existing;
13978
13980 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13981 UnnamedGlobalConstantDecls.insert(New, Token);
13982 return New;
13983}
13984
13987 assert(T->isRecordType() && "template param object of unexpected type");
13988
13989 // C++ [temp.param]p8:
13990 // [...] a static storage duration object of type 'const T' [...]
13991 T.addConst();
13992
13993 llvm::FoldingSetNodeID ID;
13995
13996 llvm::FoldingSetInsertToken Token;
13997 if (TemplateParamObjectDecl *Existing =
13998 TemplateParamObjectDecls.lookup(ID, Token))
13999 return Existing;
14000
14001 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
14002 TemplateParamObjectDecls.insert(New, Token);
14003 return New;
14004}
14005
14007 const llvm::Triple &T = getTargetInfo().getTriple();
14008 if (!T.isOSDarwin())
14009 return false;
14010
14011 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
14012 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
14013 return false;
14014
14015 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14016 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
14017 uint64_t Size = sizeChars.getQuantity();
14018 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
14019 unsigned Align = alignChars.getQuantity();
14020 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14021 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
14022}
14023
14024bool
14026 const ObjCMethodDecl *MethodImpl) {
14027 // No point trying to match an unavailable/deprecated mothod.
14028 if (MethodDecl->hasAttr<UnavailableAttr>()
14029 || MethodDecl->hasAttr<DeprecatedAttr>())
14030 return false;
14031 if (MethodDecl->getObjCDeclQualifier() !=
14032 MethodImpl->getObjCDeclQualifier())
14033 return false;
14034 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
14035 return false;
14036
14037 if (MethodDecl->param_size() != MethodImpl->param_size())
14038 return false;
14039
14040 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14041 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14042 EF = MethodDecl->param_end();
14043 IM != EM && IF != EF; ++IM, ++IF) {
14044 const ParmVarDecl *DeclVar = (*IF);
14045 const ParmVarDecl *ImplVar = (*IM);
14046 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14047 return false;
14048 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
14049 return false;
14050 }
14051
14052 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14053}
14054
14056 LangAS AS;
14058 AS = LangAS::Default;
14059 else
14060 AS = QT->getPointeeType().getAddressSpace();
14061
14063}
14064
14067}
14068
14069bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14070 if (X == Y)
14071 return true;
14072 if (!X || !Y)
14073 return false;
14074 llvm::FoldingSetNodeID IDX, IDY;
14075 X->Profile(IDX, *this, /*Canonical=*/true);
14076 Y->Profile(IDY, *this, /*Canonical=*/true);
14077 return IDX == IDY;
14078}
14079
14080// The getCommon* helpers return, for given 'same' X and Y entities given as
14081// inputs, another entity which is also the 'same' as the inputs, but which
14082// is closer to the canonical form of the inputs, each according to a given
14083// criteria.
14084// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14085// the regular ones.
14086
14088 if (!declaresSameEntity(X, Y))
14089 return nullptr;
14090 for (const Decl *DX : X->redecls()) {
14091 // If we reach Y before reaching the first decl, that means X is older.
14092 if (DX == Y)
14093 return X;
14094 // If we reach the first decl, then Y is older.
14095 if (DX->isFirstDecl())
14096 return Y;
14097 }
14098 llvm_unreachable("Corrupt redecls chain");
14099}
14100
14101template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14102static T *getCommonDecl(T *X, T *Y) {
14103 return cast_or_null<T>(
14104 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14105 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14106}
14107
14108template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14109static T *getCommonDeclChecked(T *X, T *Y) {
14110 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14111 const_cast<Decl *>(cast<Decl>(Y))));
14112}
14113
14115 TemplateName Y,
14116 bool IgnoreDeduced = false) {
14117 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14118 return X;
14119 // FIXME: There are cases here where we could find a common template name
14120 // with more sugar. For example one could be a SubstTemplateTemplate*
14121 // replacing the other.
14122 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14123 if (CX.getAsVoidPointer() !=
14125 return TemplateName();
14126 return CX;
14127}
14128
14131 bool IgnoreDeduced) {
14132 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14133 assert(R.getAsVoidPointer() != nullptr);
14134 return R;
14135}
14136
14138 ArrayRef<QualType> Ys, bool Unqualified = false) {
14139 assert(Xs.size() == Ys.size());
14140 SmallVector<QualType, 8> Rs(Xs.size());
14141 for (size_t I = 0; I < Rs.size(); ++I)
14142 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14143 return Rs;
14144}
14145
14146template <class T>
14147static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14148 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14149 : SourceLocation();
14150}
14151
14153 const TemplateArgument &X,
14154 const TemplateArgument &Y) {
14155 if (X.getKind() != Y.getKind())
14156 return TemplateArgument();
14157
14158 switch (X.getKind()) {
14160 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14161 return TemplateArgument();
14162 return TemplateArgument(
14163 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14165 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14166 return TemplateArgument();
14167 return TemplateArgument(
14168 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14169 /*Unqualified=*/true);
14171 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14172 return TemplateArgument();
14173 // FIXME: Try to keep the common sugar.
14174 return X;
14176 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14177 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14178 if (!CTN.getAsVoidPointer())
14179 return TemplateArgument();
14180 return TemplateArgument(CTN);
14181 }
14183 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14185 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14186 if (!CTN.getAsVoidPointer())
14187 return TemplateName();
14188 auto NExpX = X.getNumTemplateExpansions();
14189 assert(NExpX == Y.getNumTemplateExpansions());
14190 return TemplateArgument(CTN, NExpX);
14191 }
14192 default:
14193 // FIXME: Handle the other argument kinds.
14194 return X;
14195 }
14196}
14197
14202 if (Xs.size() != Ys.size())
14203 return true;
14204 R.resize(Xs.size());
14205 for (size_t I = 0; I < R.size(); ++I) {
14206 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14207 if (R[I].isNull())
14208 return true;
14209 }
14210 return false;
14211}
14212
14217 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14218 assert(!Different);
14219 (void)Different;
14220 return R;
14221}
14222
14223template <class T>
14225 bool IsSame) {
14226 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14227 if (KX == KY)
14228 return KX;
14230 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14231 return KX;
14232}
14233
14234/// Returns a NestedNameSpecifier which has only the common sugar
14235/// present in both NNS1 and NNS2.
14238 NestedNameSpecifier NNS2, bool IsSame) {
14239 // If they are identical, all sugar is common.
14240 if (NNS1 == NNS2)
14241 return NNS1;
14242
14243 // IsSame implies both Qualifiers are equivalent.
14244 NestedNameSpecifier Canon = NNS1.getCanonical();
14245 if (Canon != NNS2.getCanonical()) {
14246 assert(!IsSame && "Should be the same NestedNameSpecifier");
14247 // If they are not the same, there is nothing to unify.
14248 return std::nullopt;
14249 }
14250
14251 NestedNameSpecifier R = std::nullopt;
14252 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14253 assert(Kind == NNS2.getKind());
14254 switch (Kind) {
14256 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14257 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14258 auto Kind = Namespace1->getKind();
14259 if (Kind != Namespace2->getKind() ||
14260 (Kind == Decl::NamespaceAlias &&
14261 !declaresSameEntity(Namespace1, Namespace2))) {
14263 Ctx,
14264 ::getCommonDeclChecked(Namespace1->getNamespace(),
14265 Namespace2->getNamespace()),
14266 /*Prefix=*/std::nullopt);
14267 break;
14268 }
14269 // The prefixes for namespaces are not significant, its declaration
14270 // identifies it uniquely.
14271 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14272 /*IsSame=*/false);
14273 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14274 Prefix);
14275 break;
14276 }
14278 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14279 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14280 /*Unqualified=*/true)
14281 .getTypePtr();
14283 break;
14284 }
14286 // FIXME: Can __super even be used with data members?
14287 // If it's only usable in functions, we will never see it here,
14288 // unless we save the qualifiers used in function types.
14289 // In that case, it might be possible NNS2 is a type,
14290 // in which case we should degrade the result to
14291 // a CXXRecordType.
14293 NNS2.getAsMicrosoftSuper()));
14294 break;
14295 }
14298 // These are singletons.
14299 llvm_unreachable("singletons did not compare equal");
14300 }
14301 assert(R.getCanonical() == Canon);
14302 return R;
14303}
14304
14305template <class T>
14307 const T *Y, bool IsSame) {
14308 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14309}
14310
14311template <class T>
14312static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14313 const T *Y) {
14314 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14315}
14316
14318 QualType X, QualType Y,
14319 Qualifiers &QX,
14320 Qualifiers &QY) {
14321 QualType R = Ctx.getCommonSugaredType(X, Y,
14322 /*Unqualified=*/true);
14323 // Qualifiers common to both element types.
14324 Qualifiers RQ = R.getQualifiers();
14325 // For each side, move to the top level any qualifiers which are not common to
14326 // both element types. The caller must assume top level qualifiers might
14327 // be different, even if they are the same type, and can be treated as sugar.
14328 QX += X.getQualifiers() - RQ;
14329 QY += Y.getQualifiers() - RQ;
14330 return R;
14331}
14332
14333template <class T>
14335 Qualifiers &QX, const T *Y,
14336 Qualifiers &QY) {
14337 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14338 Y->getElementType(), QX, QY);
14339}
14340
14341template <class T>
14342static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14343 const T *Y) {
14344 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14345}
14346
14347template <class T>
14348static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14349 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14350 return X->getSizeExpr();
14351}
14352
14353static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14354 assert(X->getSizeModifier() == Y->getSizeModifier());
14355 return X->getSizeModifier();
14356}
14357
14359 const ArrayType *Y) {
14360 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14361 return X->getIndexTypeCVRQualifiers();
14362}
14363
14364// Merges two type lists such that the resulting vector will contain
14365// each type (in a canonical sense) only once, in the order they appear
14366// from X to Y. If they occur in both X and Y, the result will contain
14367// the common sugared type between them.
14368static void mergeTypeLists(const ASTContext &Ctx,
14371 llvm::DenseMap<QualType, unsigned> Found;
14372 for (auto Ts : {X, Y}) {
14373 for (QualType T : Ts) {
14374 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14375 if (!Res.second) {
14376 QualType &U = Out[Res.first->second];
14377 U = Ctx.getCommonSugaredType(U, T);
14378 } else {
14379 Out.emplace_back(T);
14380 }
14381 }
14382 }
14383}
14384
14385FunctionProtoType::ExceptionSpecInfo
14388 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14389 bool AcceptDependent) const {
14390 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14391
14392 // If either of them can throw anything, that is the result.
14393 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14394 if (EST1 == I)
14395 return ESI1;
14396 if (EST2 == I)
14397 return ESI2;
14398 }
14399
14400 // If either of them is non-throwing, the result is the other.
14401 for (auto I :
14403 if (EST1 == I)
14404 return ESI2;
14405 if (EST2 == I)
14406 return ESI1;
14407 }
14408
14409 // If we're left with value-dependent computed noexcept expressions, we're
14410 // stuck. Before C++17, we can just drop the exception specification entirely,
14411 // since it's not actually part of the canonical type. And this should never
14412 // happen in C++17, because it would mean we were computing the composite
14413 // pointer type of dependent types, which should never happen.
14414 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14415 assert(AcceptDependent &&
14416 "computing composite pointer type of dependent types");
14418 }
14419
14420 // Switch over the possibilities so that people adding new values know to
14421 // update this function.
14422 switch (EST1) {
14423 case EST_None:
14424 case EST_DynamicNone:
14425 case EST_MSAny:
14426 case EST_BasicNoexcept:
14428 case EST_NoexceptFalse:
14429 case EST_NoexceptTrue:
14430 case EST_NoThrow:
14431 llvm_unreachable("These ESTs should be handled above");
14432
14433 case EST_Dynamic: {
14434 // This is the fun case: both exception specifications are dynamic. Form
14435 // the union of the two lists.
14436 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14437 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14438 ESI2.Exceptions);
14440 Result.Exceptions = ExceptionTypeStorage;
14441 return Result;
14442 }
14443
14444 case EST_Unevaluated:
14445 case EST_Uninstantiated:
14446 case EST_Unparsed:
14447 llvm_unreachable("shouldn't see unresolved exception specifications here");
14448 }
14449
14450 llvm_unreachable("invalid ExceptionSpecificationType");
14451}
14452
14454 Qualifiers &QX, const Type *Y,
14455 Qualifiers &QY) {
14456 Type::TypeClass TC = X->getTypeClass();
14457 assert(TC == Y->getTypeClass());
14458 switch (TC) {
14459#define UNEXPECTED_TYPE(Class, Kind) \
14460 case Type::Class: \
14461 llvm_unreachable("Unexpected " Kind ": " #Class);
14462
14463#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14464#define TYPE(Class, Base)
14465#include "clang/AST/TypeNodes.inc"
14466
14467#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14469 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14470 SUGAR_FREE_TYPE(DependentBitInt)
14472 SUGAR_FREE_TYPE(ObjCInterface)
14473 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14474 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14475 SUGAR_FREE_TYPE(UnresolvedUsing)
14476 SUGAR_FREE_TYPE(HLSLAttributedResource)
14477 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14478#undef SUGAR_FREE_TYPE
14479#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14480 NON_UNIQUE_TYPE(TypeOfExpr)
14481 NON_UNIQUE_TYPE(VariableArray)
14482#undef NON_UNIQUE_TYPE
14483
14484 UNEXPECTED_TYPE(TypeOf, "sugar")
14485
14486#undef UNEXPECTED_TYPE
14487
14488 case Type::Auto: {
14489 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14490 assert(AX->getDeducedKind() == AY->getDeducedKind());
14491 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14492 assert(AX->getKeyword() == AY->getKeyword());
14493 TemplateDecl *CD =
14494 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14495 AY->getTypeConstraintConcept().getAsTemplateDecl());
14497 if (CD &&
14498 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14499 AY->getTypeConstraintArguments())) {
14500 CD = nullptr; // The arguments differ, so make it unconstrained.
14501 As.clear();
14502 }
14503 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14504 TemplateName(CD), As);
14505 }
14506 case Type::IncompleteArray: {
14507 const auto *AX = cast<IncompleteArrayType>(X),
14509 return Ctx.getIncompleteArrayType(
14510 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14512 }
14513 case Type::DependentSizedArray: {
14514 const auto *AX = cast<DependentSizedArrayType>(X),
14516 return Ctx.getDependentSizedArrayType(
14517 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14518 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14520 }
14521 case Type::ConstantArray: {
14522 const auto *AX = cast<ConstantArrayType>(X),
14523 *AY = cast<ConstantArrayType>(Y);
14524 assert(AX->getSize() == AY->getSize());
14525 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14526 ? AX->getSizeExpr()
14527 : nullptr;
14528 return Ctx.getConstantArrayType(
14529 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14531 }
14532 case Type::ArrayParameter: {
14533 const auto *AX = cast<ArrayParameterType>(X),
14534 *AY = cast<ArrayParameterType>(Y);
14535 assert(AX->getSize() == AY->getSize());
14536 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14537 ? AX->getSizeExpr()
14538 : nullptr;
14539 auto ArrayTy = Ctx.getConstantArrayType(
14540 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14542 return Ctx.getArrayParameterType(ArrayTy);
14543 }
14544 case Type::Atomic: {
14545 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14546 return Ctx.getAtomicType(
14547 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14548 }
14549 case Type::Complex: {
14550 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14551 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14552 }
14553 case Type::Pointer: {
14554 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14555 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14556 }
14557 case Type::BlockPointer: {
14558 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14559 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14560 }
14561 case Type::ObjCObjectPointer: {
14562 const auto *PX = cast<ObjCObjectPointerType>(X),
14564 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14565 }
14566 case Type::MemberPointer: {
14567 const auto *PX = cast<MemberPointerType>(X),
14568 *PY = cast<MemberPointerType>(Y);
14569 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14570 PY->getMostRecentCXXRecordDecl()));
14571 return Ctx.getMemberPointerType(
14572 getCommonPointeeType(Ctx, PX, PY),
14573 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14574 PX->getMostRecentCXXRecordDecl());
14575 }
14576 case Type::LValueReference: {
14577 const auto *PX = cast<LValueReferenceType>(X),
14579 // FIXME: Preserve PointeeTypeAsWritten.
14580 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14581 PX->isSpelledAsLValue() ||
14582 PY->isSpelledAsLValue());
14583 }
14584 case Type::RValueReference: {
14585 const auto *PX = cast<RValueReferenceType>(X),
14587 // FIXME: Preserve PointeeTypeAsWritten.
14588 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14589 }
14590 case Type::DependentAddressSpace: {
14591 const auto *PX = cast<DependentAddressSpaceType>(X),
14593 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14594 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14595 PX->getAddrSpaceExpr(),
14596 getCommonAttrLoc(PX, PY));
14597 }
14598 case Type::FunctionNoProto: {
14599 const auto *FX = cast<FunctionNoProtoType>(X),
14601 assert(FX->getExtInfo() == FY->getExtInfo());
14602 return Ctx.getFunctionNoProtoType(
14603 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14604 FX->getExtInfo());
14605 }
14606 case Type::FunctionProto: {
14607 const auto *FX = cast<FunctionProtoType>(X),
14608 *FY = cast<FunctionProtoType>(Y);
14609 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14610 EPIY = FY->getExtProtoInfo();
14611 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14612 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14613 assert(!EPIX.ExtParameterInfos ||
14614 llvm::equal(
14615 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14616 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14617 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14618 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14619 assert(EPIX.Variadic == EPIY.Variadic);
14620
14621 // FIXME: Can we handle an empty EllipsisLoc?
14622 // Use emtpy EllipsisLoc if X and Y differ.
14623
14624 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14625
14626 QualType R =
14627 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14628 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14629 /*Unqualified=*/true);
14630
14631 SmallVector<QualType, 8> Exceptions;
14633 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14634 return Ctx.getFunctionType(R, P, EPIX);
14635 }
14636 case Type::ObjCObject: {
14637 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14638 assert(
14639 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14640 OY->getProtocols().begin(), OY->getProtocols().end(),
14641 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14642 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14643 }) &&
14644 "protocol lists must be the same");
14645 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14646 OY->getTypeArgsAsWritten());
14647 return Ctx.getObjCObjectType(
14648 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14649 OX->getProtocols(),
14650 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14651 }
14652 case Type::ConstantMatrix: {
14653 const auto *MX = cast<ConstantMatrixType>(X),
14654 *MY = cast<ConstantMatrixType>(Y);
14655 assert(MX->getNumRows() == MY->getNumRows());
14656 assert(MX->getNumColumns() == MY->getNumColumns());
14657 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14658 MX->getNumRows(), MX->getNumColumns());
14659 }
14660 case Type::DependentSizedMatrix: {
14661 const auto *MX = cast<DependentSizedMatrixType>(X),
14663 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14664 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14665 return Ctx.getDependentSizedMatrixType(
14666 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14667 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14668 }
14669 case Type::Vector: {
14670 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14671 assert(VX->getNumElements() == VY->getNumElements());
14672 assert(VX->getVectorKind() == VY->getVectorKind());
14673 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14674 VX->getNumElements(), VX->getVectorKind());
14675 }
14676 case Type::ExtVector: {
14677 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14678 assert(VX->getNumElements() == VY->getNumElements());
14679 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14680 VX->getNumElements());
14681 }
14682 case Type::DependentSizedExtVector: {
14683 const auto *VX = cast<DependentSizedExtVectorType>(X),
14686 getCommonSizeExpr(Ctx, VX, VY),
14687 getCommonAttrLoc(VX, VY));
14688 }
14689 case Type::DependentVector: {
14690 const auto *VX = cast<DependentVectorType>(X),
14692 assert(VX->getVectorKind() == VY->getVectorKind());
14693 return Ctx.getDependentVectorType(
14694 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14695 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14696 }
14697 case Type::Enum:
14698 case Type::Record:
14699 case Type::InjectedClassName: {
14700 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14701 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14702 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14703 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14704 /*OwnedTag=*/false);
14705 }
14706 case Type::TemplateSpecialization: {
14707 const auto *TX = cast<TemplateSpecializationType>(X),
14709 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14710 TY->template_arguments());
14712 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14713 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14714 TY->getTemplateName(),
14715 /*IgnoreDeduced=*/true),
14716 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14717 }
14718 case Type::Decltype: {
14719 const auto *DX = cast<DecltypeType>(X);
14720 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14721 assert(DX->isDependentType());
14722 assert(DY->isDependentType());
14723 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14724 // As Decltype is not uniqued, building a common type would be wasteful.
14725 return QualType(DX, 0);
14726 }
14727 case Type::PackIndexing: {
14728 const auto *DX = cast<PackIndexingType>(X);
14729 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14730 assert(DX->isDependentType());
14731 assert(DY->isDependentType());
14732 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14733 return QualType(DX, 0);
14734 }
14735 case Type::DependentName: {
14736 const auto *NX = cast<DependentNameType>(X),
14737 *NY = cast<DependentNameType>(Y);
14738 assert(NX->getIdentifier() == NY->getIdentifier());
14739 return Ctx.getDependentNameType(
14740 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14741 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14742 }
14743 case Type::OverflowBehavior: {
14744 const auto *NX = cast<OverflowBehaviorType>(X),
14746 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14747 return Ctx.getOverflowBehaviorType(
14748 NX->getBehaviorKind(),
14749 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14750 NY->getUnderlyingType(), QX, QY));
14751 }
14752 case Type::UnaryTransform: {
14753 const auto *TX = cast<UnaryTransformType>(X),
14754 *TY = cast<UnaryTransformType>(Y);
14755 assert(TX->getUTTKind() == TY->getUTTKind());
14756 return Ctx.getUnaryTransformType(
14757 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14758 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14759 TY->getUnderlyingType()),
14760 TX->getUTTKind());
14761 }
14762 case Type::PackExpansion: {
14763 const auto *PX = cast<PackExpansionType>(X),
14764 *PY = cast<PackExpansionType>(Y);
14765 assert(PX->getNumExpansions() == PY->getNumExpansions());
14766 return Ctx.getPackExpansionType(
14767 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14768 PX->getNumExpansions(), false);
14769 }
14770 case Type::Pipe: {
14771 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14772 assert(PX->isReadOnly() == PY->isReadOnly());
14773 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14775 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14776 }
14777 case Type::TemplateTypeParm: {
14778 const auto *TX = cast<TemplateTypeParmType>(X),
14780 assert(TX->getDepth() == TY->getDepth());
14781 assert(TX->getIndex() == TY->getIndex());
14782 assert(TX->isParameterPack() == TY->isParameterPack());
14783 return Ctx.getTemplateTypeParmType(
14784 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14785 getCommonDecl(TX->getDecl(), TY->getDecl()));
14786 }
14787 }
14788 llvm_unreachable("Unknown Type Class");
14789}
14790
14792 const Type *Y,
14793 SplitQualType Underlying) {
14794 Type::TypeClass TC = X->getTypeClass();
14795 if (TC != Y->getTypeClass())
14796 return QualType();
14797 switch (TC) {
14798#define UNEXPECTED_TYPE(Class, Kind) \
14799 case Type::Class: \
14800 llvm_unreachable("Unexpected " Kind ": " #Class);
14801#define TYPE(Class, Base)
14802#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14803#include "clang/AST/TypeNodes.inc"
14804
14805#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14808 CANONICAL_TYPE(BlockPointer)
14811 CANONICAL_TYPE(ConstantArray)
14812 CANONICAL_TYPE(ArrayParameter)
14813 CANONICAL_TYPE(ConstantMatrix)
14815 CANONICAL_TYPE(ExtVector)
14816 CANONICAL_TYPE(FunctionNoProto)
14817 CANONICAL_TYPE(FunctionProto)
14818 CANONICAL_TYPE(IncompleteArray)
14819 CANONICAL_TYPE(HLSLAttributedResource)
14820 CANONICAL_TYPE(HLSLInlineSpirv)
14821 CANONICAL_TYPE(LValueReference)
14822 CANONICAL_TYPE(ObjCInterface)
14823 CANONICAL_TYPE(ObjCObject)
14824 CANONICAL_TYPE(ObjCObjectPointer)
14825 CANONICAL_TYPE(OverflowBehavior)
14829 CANONICAL_TYPE(RValueReference)
14830 CANONICAL_TYPE(VariableArray)
14832#undef CANONICAL_TYPE
14833
14834#undef UNEXPECTED_TYPE
14835
14836 case Type::Adjusted: {
14837 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14838 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14839 if (!Ctx.hasSameType(OX, OY))
14840 return QualType();
14841 // FIXME: It's inefficient to have to unify the original types.
14842 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14843 Ctx.getQualifiedType(Underlying));
14844 }
14845 case Type::Decayed: {
14846 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14847 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14848 if (!Ctx.hasSameType(OX, OY))
14849 return QualType();
14850 // FIXME: It's inefficient to have to unify the original types.
14851 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14852 Ctx.getQualifiedType(Underlying));
14853 }
14854 case Type::Attributed: {
14855 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14856 AttributedType::Kind Kind = AX->getAttrKind();
14857 if (Kind != AY->getAttrKind())
14858 return QualType();
14859 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14860 if (!Ctx.hasSameType(MX, MY))
14861 return QualType();
14862 // FIXME: It's inefficient to have to unify the modified types.
14863 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14864 Ctx.getQualifiedType(Underlying),
14865 AX->getAttr());
14866 }
14867 case Type::BTFTagAttributed: {
14868 const auto *BX = cast<BTFTagAttributedType>(X);
14869 const BTFTypeTagAttr *AX = BX->getAttr();
14870 // The attribute is not uniqued, so just compare the tag.
14871 if (AX->getBTFTypeTag() !=
14872 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14873 return QualType();
14874 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14875 }
14876 case Type::Auto: {
14877 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14878 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14879 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14880
14881 AutoTypeKeyword KW = AX->getKeyword();
14882 if (KW != AY->getKeyword())
14883 return QualType();
14884
14885 TemplateDecl *CD =
14886 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14887 AY->getTypeConstraintConcept().getAsTemplateDecl());
14889 if (CD &&
14890 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14891 AY->getTypeConstraintArguments())) {
14892 CD = nullptr; // The arguments differ, so make it unconstrained.
14893 As.clear();
14894 }
14895
14896 // Both auto types can't be dependent, otherwise they wouldn't have been
14897 // sugar. This implies they can't contain unexpanded packs either.
14899 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14900 TemplateName(CD), As);
14901 }
14902 case Type::PackIndexing:
14903 case Type::Decltype:
14904 return QualType();
14905 case Type::DeducedTemplateSpecialization:
14906 // FIXME: Try to merge these.
14907 return QualType();
14908 case Type::MacroQualified: {
14909 const auto *MX = cast<MacroQualifiedType>(X),
14910 *MY = cast<MacroQualifiedType>(Y);
14911 const IdentifierInfo *IX = MX->getMacroIdentifier();
14912 if (IX != MY->getMacroIdentifier())
14913 return QualType();
14914 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14915 }
14916 case Type::SubstTemplateTypeParm: {
14917 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14919 Decl *CD =
14920 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14921 if (!CD)
14922 return QualType();
14923 unsigned Index = SX->getIndex();
14924 if (Index != SY->getIndex())
14925 return QualType();
14926 auto PackIndex = SX->getPackIndex();
14927 if (PackIndex != SY->getPackIndex())
14928 return QualType();
14929 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14930 CD, Index, PackIndex,
14931 SX->getFinal() && SY->getFinal());
14932 }
14933 case Type::ObjCTypeParam:
14934 // FIXME: Try to merge these.
14935 return QualType();
14936 case Type::Paren:
14937 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14938
14939 case Type::TemplateSpecialization: {
14940 const auto *TX = cast<TemplateSpecializationType>(X),
14942 TemplateName CTN =
14943 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14944 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14945 if (!CTN.getAsVoidPointer())
14946 return QualType();
14948 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14949 TY->template_arguments()))
14950 return QualType();
14952 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14953 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14954 }
14955 case Type::Typedef: {
14956 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14957 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14958 if (!CD)
14959 return QualType();
14960 return Ctx.getTypedefType(
14961 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14962 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14963 Ctx.getQualifiedType(Underlying));
14964 }
14965 case Type::TypeOf: {
14966 // The common sugar between two typeof expressions, where one is
14967 // potentially a typeof_unqual and the other is not, we unify to the
14968 // qualified type as that retains the most information along with the type.
14969 // We only return a typeof_unqual type when both types are unqual types.
14974 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14975 }
14976 case Type::TypeOfExpr:
14977 return QualType();
14978
14979 case Type::UnaryTransform: {
14980 const auto *UX = cast<UnaryTransformType>(X),
14981 *UY = cast<UnaryTransformType>(Y);
14982 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14983 if (KX != UY->getUTTKind())
14984 return QualType();
14985 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14986 if (!Ctx.hasSameType(BX, BY))
14987 return QualType();
14988 // FIXME: It's inefficient to have to unify the base types.
14989 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14990 Ctx.getQualifiedType(Underlying), KX);
14991 }
14992 case Type::Using: {
14993 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14994 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14995 if (!CD)
14996 return QualType();
14997 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14998 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14999 CD, Ctx.getQualifiedType(Underlying));
15000 }
15001 case Type::MemberPointer: {
15002 const auto *PX = cast<MemberPointerType>(X),
15003 *PY = cast<MemberPointerType>(Y);
15004 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
15005 assert(Cls == PY->getMostRecentCXXRecordDecl());
15006 return Ctx.getMemberPointerType(
15007 ::getCommonPointeeType(Ctx, PX, PY),
15008 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
15009 }
15010 case Type::CountAttributed: {
15011 const auto *DX = cast<CountAttributedType>(X),
15013 if (DX->isCountInBytes() != DY->isCountInBytes())
15014 return QualType();
15015 if (DX->isOrNull() != DY->isOrNull())
15016 return QualType();
15017 Expr *CEX = DX->getCountExpr();
15018 Expr *CEY = DY->getCountExpr();
15019 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15020 if (Ctx.hasSameExpr(CEX, CEY))
15021 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15022 DX->isCountInBytes(), DX->isOrNull(),
15023 CDX);
15024 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15025 return QualType();
15026 // Two declarations with the same integer constant may still differ in their
15027 // expression pointers, so we need to evaluate them.
15028 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15029 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15030 if (VX != VY)
15031 return QualType();
15032 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15033 DX->isCountInBytes(), DX->isOrNull(),
15034 CDX);
15035 }
15036
15037 case Type::LateParsedAttr:
15038 return QualType();
15039
15040 case Type::PredefinedSugar:
15041 assert(cast<PredefinedSugarType>(X)->getKind() !=
15043 return QualType();
15044 }
15045 llvm_unreachable("Unhandled Type Class");
15046}
15047
15048static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15050 while (true) {
15051 QTotal.addConsistentQualifiers(T.Quals);
15052 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15053 if (NT == QualType(T.Ty, 0))
15054 break;
15055 R.push_back(T);
15056 T = NT.split();
15057 }
15058 return R;
15059}
15060
15062 bool Unqualified) const {
15063 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15064 if (X == Y)
15065 return X;
15066 if (!Unqualified) {
15067 if (X.isCanonical())
15068 return X;
15069 if (Y.isCanonical())
15070 return Y;
15071 }
15072
15073 SplitQualType SX = X.split(), SY = Y.split();
15074 Qualifiers QX, QY;
15075 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15076 // until we reach their underlying "canonical nodes". Note these are not
15077 // necessarily canonical types, as they may still have sugared properties.
15078 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15079 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15080
15081 // If this is an ArrayType, the element qualifiers are interchangeable with
15082 // the top level qualifiers.
15083 // * In case the canonical nodes are the same, the elements types are already
15084 // the same.
15085 // * Otherwise, the element types will be made the same, and any different
15086 // element qualifiers will be moved up to the top level qualifiers, per
15087 // 'getCommonArrayElementType'.
15088 // In both cases, this means there may be top level qualifiers which differ
15089 // between X and Y. If so, these differing qualifiers are redundant with the
15090 // element qualifiers, and can be removed without changing the canonical type.
15091 // The desired behaviour is the same as for the 'Unqualified' case here:
15092 // treat the redundant qualifiers as sugar, remove the ones which are not
15093 // common to both sides.
15094 bool KeepCommonQualifiers =
15096
15097 if (SX.Ty != SY.Ty) {
15098 // The canonical nodes differ. Build a common canonical node out of the two,
15099 // unifying their sugar. This may recurse back here.
15100 SX.Ty =
15101 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15102 } else {
15103 // The canonical nodes were identical: We may have desugared too much.
15104 // Add any common sugar back in.
15105 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15106 QX -= SX.Quals;
15107 QY -= SY.Quals;
15108 SX = Xs.pop_back_val();
15109 SY = Ys.pop_back_val();
15110 }
15111 }
15112 if (KeepCommonQualifiers)
15114 else
15115 assert(QX == QY);
15116
15117 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15118 // related. Walk up these nodes, unifying them and adding the result.
15119 while (!Xs.empty() && !Ys.empty()) {
15120 auto Underlying = SplitQualType(
15121 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15122 SX = Xs.pop_back_val();
15123 SY = Ys.pop_back_val();
15124 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15126 // Stop at the first pair which is unrelated.
15127 if (!SX.Ty) {
15128 SX.Ty = Underlying.Ty;
15129 break;
15130 }
15131 QX -= Underlying.Quals;
15132 };
15133
15134 // Add back the missing accumulated qualifiers, which were stripped off
15135 // with the sugar nodes we could not unify.
15136 QualType R = getQualifiedType(SX.Ty, QX);
15137 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15138 return R;
15139}
15140
15142 assert(Ty->isFixedPointType());
15143
15145 return Ty;
15146
15147 switch (Ty->castAs<BuiltinType>()->getKind()) {
15148 default:
15149 llvm_unreachable("Not a saturated fixed point type!");
15150 case BuiltinType::SatShortAccum:
15151 return ShortAccumTy;
15152 case BuiltinType::SatAccum:
15153 return AccumTy;
15154 case BuiltinType::SatLongAccum:
15155 return LongAccumTy;
15156 case BuiltinType::SatUShortAccum:
15157 return UnsignedShortAccumTy;
15158 case BuiltinType::SatUAccum:
15159 return UnsignedAccumTy;
15160 case BuiltinType::SatULongAccum:
15161 return UnsignedLongAccumTy;
15162 case BuiltinType::SatShortFract:
15163 return ShortFractTy;
15164 case BuiltinType::SatFract:
15165 return FractTy;
15166 case BuiltinType::SatLongFract:
15167 return LongFractTy;
15168 case BuiltinType::SatUShortFract:
15169 return UnsignedShortFractTy;
15170 case BuiltinType::SatUFract:
15171 return UnsignedFractTy;
15172 case BuiltinType::SatULongFract:
15173 return UnsignedLongFractTy;
15174 }
15175}
15176
15178 assert(Ty->isFixedPointType());
15179
15180 if (Ty->isSaturatedFixedPointType()) return Ty;
15181
15182 switch (Ty->castAs<BuiltinType>()->getKind()) {
15183 default:
15184 llvm_unreachable("Not a fixed point type!");
15185 case BuiltinType::ShortAccum:
15186 return SatShortAccumTy;
15187 case BuiltinType::Accum:
15188 return SatAccumTy;
15189 case BuiltinType::LongAccum:
15190 return SatLongAccumTy;
15191 case BuiltinType::UShortAccum:
15193 case BuiltinType::UAccum:
15194 return SatUnsignedAccumTy;
15195 case BuiltinType::ULongAccum:
15197 case BuiltinType::ShortFract:
15198 return SatShortFractTy;
15199 case BuiltinType::Fract:
15200 return SatFractTy;
15201 case BuiltinType::LongFract:
15202 return SatLongFractTy;
15203 case BuiltinType::UShortFract:
15205 case BuiltinType::UFract:
15206 return SatUnsignedFractTy;
15207 case BuiltinType::ULongFract:
15209 }
15210}
15211
15213 if (LangOpts.OpenCL)
15215
15216 if (LangOpts.CUDA)
15218
15219 return getLangASFromTargetAS(AS);
15220}
15221
15223 assert(Ty->isFixedPointType());
15224
15225 const TargetInfo &Target = getTargetInfo();
15226 switch (Ty->castAs<BuiltinType>()->getKind()) {
15227 default:
15228 llvm_unreachable("Not a fixed point type!");
15229 case BuiltinType::ShortAccum:
15230 case BuiltinType::SatShortAccum:
15231 return Target.getShortAccumScale();
15232 case BuiltinType::Accum:
15233 case BuiltinType::SatAccum:
15234 return Target.getAccumScale();
15235 case BuiltinType::LongAccum:
15236 case BuiltinType::SatLongAccum:
15237 return Target.getLongAccumScale();
15238 case BuiltinType::UShortAccum:
15239 case BuiltinType::SatUShortAccum:
15240 return Target.getUnsignedShortAccumScale();
15241 case BuiltinType::UAccum:
15242 case BuiltinType::SatUAccum:
15243 return Target.getUnsignedAccumScale();
15244 case BuiltinType::ULongAccum:
15245 case BuiltinType::SatULongAccum:
15246 return Target.getUnsignedLongAccumScale();
15247 case BuiltinType::ShortFract:
15248 case BuiltinType::SatShortFract:
15249 return Target.getShortFractScale();
15250 case BuiltinType::Fract:
15251 case BuiltinType::SatFract:
15252 return Target.getFractScale();
15253 case BuiltinType::LongFract:
15254 case BuiltinType::SatLongFract:
15255 return Target.getLongFractScale();
15256 case BuiltinType::UShortFract:
15257 case BuiltinType::SatUShortFract:
15258 return Target.getUnsignedShortFractScale();
15259 case BuiltinType::UFract:
15260 case BuiltinType::SatUFract:
15261 return Target.getUnsignedFractScale();
15262 case BuiltinType::ULongFract:
15263 case BuiltinType::SatULongFract:
15264 return Target.getUnsignedLongFractScale();
15265 }
15266}
15267
15269 assert(Ty->isFixedPointType());
15270
15271 const TargetInfo &Target = getTargetInfo();
15272 switch (Ty->castAs<BuiltinType>()->getKind()) {
15273 default:
15274 llvm_unreachable("Not a fixed point type!");
15275 case BuiltinType::ShortAccum:
15276 case BuiltinType::SatShortAccum:
15277 return Target.getShortAccumIBits();
15278 case BuiltinType::Accum:
15279 case BuiltinType::SatAccum:
15280 return Target.getAccumIBits();
15281 case BuiltinType::LongAccum:
15282 case BuiltinType::SatLongAccum:
15283 return Target.getLongAccumIBits();
15284 case BuiltinType::UShortAccum:
15285 case BuiltinType::SatUShortAccum:
15286 return Target.getUnsignedShortAccumIBits();
15287 case BuiltinType::UAccum:
15288 case BuiltinType::SatUAccum:
15289 return Target.getUnsignedAccumIBits();
15290 case BuiltinType::ULongAccum:
15291 case BuiltinType::SatULongAccum:
15292 return Target.getUnsignedLongAccumIBits();
15293 case BuiltinType::ShortFract:
15294 case BuiltinType::SatShortFract:
15295 case BuiltinType::Fract:
15296 case BuiltinType::SatFract:
15297 case BuiltinType::LongFract:
15298 case BuiltinType::SatLongFract:
15299 case BuiltinType::UShortFract:
15300 case BuiltinType::SatUShortFract:
15301 case BuiltinType::UFract:
15302 case BuiltinType::SatUFract:
15303 case BuiltinType::ULongFract:
15304 case BuiltinType::SatULongFract:
15305 return 0;
15306 }
15307}
15308
15309llvm::FixedPointSemantics
15311 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15312 "Can only get the fixed point semantics for a "
15313 "fixed point or integer type.");
15314 if (Ty->isIntegerType())
15315 return llvm::FixedPointSemantics::GetIntegerSemantics(
15316 getIntWidth(Ty), Ty->isSignedIntegerType());
15317
15318 bool isSigned = Ty->isSignedFixedPointType();
15319 return llvm::FixedPointSemantics(
15320 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15322 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15323}
15324
15325llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15326 assert(Ty->isFixedPointType());
15327 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15328}
15329
15330llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15331 assert(Ty->isFixedPointType());
15332 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15333}
15334
15336 assert(Ty->isUnsignedFixedPointType() &&
15337 "Expected unsigned fixed point type");
15338
15339 switch (Ty->castAs<BuiltinType>()->getKind()) {
15340 case BuiltinType::UShortAccum:
15341 return ShortAccumTy;
15342 case BuiltinType::UAccum:
15343 return AccumTy;
15344 case BuiltinType::ULongAccum:
15345 return LongAccumTy;
15346 case BuiltinType::SatUShortAccum:
15347 return SatShortAccumTy;
15348 case BuiltinType::SatUAccum:
15349 return SatAccumTy;
15350 case BuiltinType::SatULongAccum:
15351 return SatLongAccumTy;
15352 case BuiltinType::UShortFract:
15353 return ShortFractTy;
15354 case BuiltinType::UFract:
15355 return FractTy;
15356 case BuiltinType::ULongFract:
15357 return LongFractTy;
15358 case BuiltinType::SatUShortFract:
15359 return SatShortFractTy;
15360 case BuiltinType::SatUFract:
15361 return SatFractTy;
15362 case BuiltinType::SatULongFract:
15363 return SatLongFractTy;
15364 default:
15365 llvm_unreachable("Unexpected unsigned fixed point type");
15366 }
15367}
15368
15369// Given a list of FMV features, return a concatenated list of the
15370// corresponding backend features (which may contain duplicates).
15371static std::vector<std::string> getFMVBackendFeaturesFor(
15372 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15373 std::vector<std::string> BackendFeats;
15374 llvm::AArch64::ExtensionSet FeatureBits;
15375 for (StringRef F : FMVFeatStrings)
15376 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15377 if (FMVExt->ID)
15378 FeatureBits.enable(*FMVExt->ID);
15379 FeatureBits.toLLVMFeatureList(BackendFeats);
15380 return BackendFeats;
15381}
15382
15383ParsedTargetAttr
15384ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15385 assert(TD != nullptr);
15386 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15387
15388 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15389 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15390 });
15391 return ParsedAttr;
15392}
15393
15394void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15395 const FunctionDecl *FD) const {
15396 if (FD)
15397 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15398 else
15399 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15400 Target->getTargetOpts().CPU,
15401 Target->getTargetOpts().Features);
15402}
15403
15404// Fills in the supplied string map with the set of target features for the
15405// passed in function.
15406void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15407 GlobalDecl GD) const {
15408 StringRef TargetCPU = Target->getTargetOpts().CPU;
15409 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15410 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15412
15413 // Make a copy of the features as passed on the command line into the
15414 // beginning of the additional features from the function to override.
15415 // AArch64 handles command line option features in parseTargetAttr().
15416 if (!Target->getTriple().isAArch64())
15417 ParsedAttr.Features.insert(
15418 ParsedAttr.Features.begin(),
15419 Target->getTargetOpts().FeaturesAsWritten.begin(),
15420 Target->getTargetOpts().FeaturesAsWritten.end());
15421
15422 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15423 TargetCPU = ParsedAttr.CPU;
15424
15425 // Now populate the feature map, first with the TargetCPU which is either
15426 // the default or a new one from the target attribute string. Then we'll use
15427 // the passed in features (FeaturesAsWritten) along with the new ones from
15428 // the attribute.
15429 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15430 ParsedAttr.Features);
15431 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15433 Target->getCPUSpecificCPUDispatchFeatures(
15434 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15435 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15436 Features.insert(Features.begin(),
15437 Target->getTargetOpts().FeaturesAsWritten.begin(),
15438 Target->getTargetOpts().FeaturesAsWritten.end());
15439 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15440 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15441 if (Target->getTriple().isAArch64()) {
15443 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15444 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15445 Features.insert(Features.begin(),
15446 Target->getTargetOpts().FeaturesAsWritten.begin(),
15447 Target->getTargetOpts().FeaturesAsWritten.end());
15448 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15449 } else if (Target->getTriple().isRISCV()) {
15450 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15451 std::vector<std::string> Features;
15452 if (VersionStr != "default") {
15453 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15454 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15455 ParsedAttr.Features.end());
15456 }
15457 Features.insert(Features.begin(),
15458 Target->getTargetOpts().FeaturesAsWritten.begin(),
15459 Target->getTargetOpts().FeaturesAsWritten.end());
15460 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15461 } else if (Target->getTriple().isOSAIX()) {
15462 std::vector<std::string> Features;
15463 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15464 if (VersionStr.starts_with("cpu="))
15465 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15466 else if (VersionStr != "default")
15467 Features = Target->parseTargetAttr(VersionStr).Features;
15468 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15469 } else {
15470 std::vector<std::string> Features;
15471 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15472 if (VersionStr.starts_with("arch="))
15473 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15474 else if (VersionStr != "default")
15475 Features.push_back((StringRef{"+"} + VersionStr).str());
15476 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15477 }
15478 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15479 std::vector<std::string> Features;
15480 if (Target->getTriple().isRISCV()) {
15481 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15482 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15483 ParsedAttr.Features.end());
15484 } else {
15485 assert(Target->getTriple().isAArch64());
15487 TV->getFeatures(Feats);
15488 Features = getFMVBackendFeaturesFor(Feats);
15489 }
15490 Features.insert(Features.begin(),
15491 Target->getTargetOpts().FeaturesAsWritten.begin(),
15492 Target->getTargetOpts().FeaturesAsWritten.end());
15493 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15494 } else {
15495 FeatureMap = Target->getTargetOpts().FeatureMap;
15496 }
15497}
15498
15500 CanQualType KernelNameType,
15501 const FunctionDecl *FD) {
15502 // Host and device compilation may use different ABIs and different ABIs
15503 // may allocate name mangling discriminators differently. A discriminator
15504 // override is used to ensure consistent discriminator allocation across
15505 // host and device compilation.
15506 auto DeviceDiscriminatorOverrider =
15507 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15508 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15509 if (RD->isLambda())
15510 return RD->getDeviceLambdaManglingNumber();
15511 return std::nullopt;
15512 };
15513 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15514 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15515
15516 // Construct a mangled name for the SYCL kernel caller offload entry point.
15517 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15518 // name the SYCL kernel caller offload entry point function. This mangling
15519 // does not suffice to clearly identify symbols that correspond to SYCL
15520 // kernel caller functions, nor is this mangling natural for targets that
15521 // use a non-Itanium ABI.
15522 std::string Buffer;
15523 Buffer.reserve(128);
15524 llvm::raw_string_ostream Out(Buffer);
15525 MC->mangleCanonicalTypeName(KernelNameType, Out);
15526 std::string KernelName = Out.str();
15527
15528 return {KernelNameType, FD, KernelName};
15529}
15530
15532 // If the function declaration to register is invalid or dependent, the
15533 // registration attempt is ignored.
15534 if (FD->isInvalidDecl() || FD->isTemplated())
15535 return;
15536
15537 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15538 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15539
15540 // Be tolerant of multiple registration attempts so long as each attempt
15541 // is for the same entity. Callers are obligated to detect and diagnose
15542 // conflicting kernel names prior to calling this function.
15543 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15544 auto IT = SYCLKernels.find(KernelNameType);
15545 assert((IT == SYCLKernels.end() ||
15546 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15547 "SYCL kernel name conflict");
15548 (void)IT;
15549 SYCLKernels.insert(std::make_pair(
15550 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15551}
15552
15554 CanQualType KernelNameType = getCanonicalType(T);
15555 return SYCLKernels.at(KernelNameType);
15556}
15557
15559 CanQualType KernelNameType = getCanonicalType(T);
15560 auto IT = SYCLKernels.find(KernelNameType);
15561 if (IT != SYCLKernels.end())
15562 return &IT->second;
15563 return nullptr;
15564}
15565
15567 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15568 return *OMPTraitInfoVector.back();
15569}
15570
15573 const ASTContext::SectionInfo &Section) {
15574 if (Section.Decl)
15575 return DB << Section.Decl;
15576 return DB << "a prior #pragma section";
15577}
15578
15579bool ASTContext::mayExternalize(const Decl *D) const {
15580 bool IsInternalVar =
15581 isa<VarDecl>(D) &&
15583 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15584 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15585 (D->hasAttr<CUDAConstantAttr>() &&
15586 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15587 // CUDA/HIP: managed variables need to be externalized since it is
15588 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15589 // anonymous name space needs to be externalized to avoid duplicate symbols.
15590 return (IsInternalVar &&
15591 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15592 (D->hasAttr<CUDAGlobalAttr>() &&
15594 GVA_Internal);
15595}
15596
15598 return mayExternalize(D) &&
15599 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15601}
15602
15603StringRef ASTContext::getCUIDHash() const {
15604 if (!CUIDHash.empty())
15605 return CUIDHash;
15606 if (LangOpts.CUID.empty())
15607 return StringRef();
15608 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15609 return CUIDHash;
15610}
15611
15612const CXXRecordDecl *
15614 assert(ThisClass);
15615 assert(ThisClass->isPolymorphic());
15616 const CXXRecordDecl *PrimaryBase = ThisClass;
15617 while (1) {
15618 assert(PrimaryBase);
15619 assert(PrimaryBase->isPolymorphic());
15620 auto &Layout = getASTRecordLayout(PrimaryBase);
15621 auto Base = Layout.getPrimaryBase();
15622 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15623 break;
15624 PrimaryBase = Base;
15625 }
15626 return PrimaryBase;
15627}
15628
15630 StringRef MangledName) {
15631 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15632 assert(Method->isVirtual());
15633 bool DefaultIncludesPointerAuth =
15634 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15635
15636 if (!DefaultIncludesPointerAuth)
15637 return true;
15638
15639 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15640 if (Existing != ThunksToBeAbbreviated.end())
15641 return Existing->second.contains(MangledName.str());
15642
15643 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15644 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15645 auto VtableContext = getVTableContext();
15646 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15647 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15648 for (const auto &Thunk : *ThunkInfos) {
15649 SmallString<256> ElidedName;
15650 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15651 if (Destructor)
15652 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15653 Thunk, /* elideOverrideInfo */ true,
15654 ElidedNameStream);
15655 else
15656 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15657 ElidedNameStream);
15658 SmallString<256> MangledName;
15659 llvm::raw_svector_ostream mangledNameStream(MangledName);
15660 if (Destructor)
15661 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15662 Thunk, /* elideOverrideInfo */ false,
15663 mangledNameStream);
15664 else
15665 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15666 mangledNameStream);
15667
15668 Thunks[ElidedName].push_back(std::string(MangledName));
15669 }
15670 }
15671 llvm::StringSet<> SimplifiedThunkNames;
15672 for (auto &ThunkList : Thunks) {
15673 llvm::sort(ThunkList.second);
15674 SimplifiedThunkNames.insert(ThunkList.second[0]);
15675 }
15676 bool Result = SimplifiedThunkNames.contains(MangledName);
15677 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15678 return Result;
15679}
15680
15682 // Check for trivially-destructible here because non-trivially-destructible
15683 // types will always cause the type and any types derived from it to be
15684 // considered non-trivially-copyable. The same cannot be said for
15685 // trivially-copyable because deleting special members of a type derived from
15686 // a non-trivially-copyable type can cause the derived type to be considered
15687 // trivially copyable.
15688 if (getLangOpts().PointerFieldProtectionTagged)
15689 return !isa<CXXRecordDecl>(RD) ||
15690 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15691 return true;
15692}
15693
15694static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15695 std::vector<PFPField> &Fields, bool IncludeVBases) {
15696 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15697 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15698 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15699 for (unsigned i = 0; i != AT->getSize(); ++i)
15700 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15701 Fields, true);
15702 }
15703 }
15704 auto *Decl = Ty->getAsCXXRecordDecl();
15705 // isPFPType() is inherited from bases and members (including via arrays), so
15706 // we can early exit if it is false. Unions are excluded per the API
15707 // documentation.
15708 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15709 return;
15710 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15711 for (FieldDecl *Field : Decl->fields()) {
15712 CharUnits FieldOffset =
15713 Offset +
15714 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15715 if (Ctx.isPFPField(Field))
15716 Fields.push_back({FieldOffset, Field});
15717 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15718 /*IncludeVBases=*/true);
15719 }
15720 // Pass false for IncludeVBases below because vbases are only included in
15721 // layout for top-level types, i.e. not bases or vbases.
15722 for (CXXBaseSpecifier &Base : Decl->bases()) {
15723 if (Base.isVirtual())
15724 continue;
15725 CharUnits BaseOffset =
15726 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15727 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15728 /*IncludeVBases=*/false);
15729 }
15730 if (IncludeVBases) {
15731 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15732 CharUnits BaseOffset =
15733 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15734 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15735 /*IncludeVBases=*/false);
15736 }
15737 }
15738}
15739
15740std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15741 std::vector<PFPField> PFPFields;
15742 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15743 return PFPFields;
15744}
15745
15747 return !findPFPFields(Ty).empty();
15748}
15749
15751 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15752 return RD->isPFPType() && FD->getType()->isPointerType() &&
15753 !FD->hasAttr<NoFieldProtectionAttr>();
15754 return false;
15755}
15756
15758 auto *FD = dyn_cast<FieldDecl>(VD);
15759 if (!FD)
15760 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15761 if (isPFPField(FD))
15763}
15764
15766 if (E->getNumComponents() == 0)
15767 return;
15768 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15769 if (Comp.getKind() != OffsetOfNode::Field)
15770 return;
15771 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15773}
15774
15775namespace {
15776// PaddingCalculator is a utility class that calculates the padding bits in a
15777// c/c++ type. It traverses the type recursively, collecting occupied
15778// bit intervals, and then computes the padding intervals.
15779// If a byte only contains some padding bits, it gets intervals for only those
15780// bits. This is the case for bit-fields.
15781struct PaddingCalculator {
15782 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15783
15784 void run(QualType Ty) {
15785 OccuppiedIntervals.clear();
15786 Stack.clear();
15787
15788 TySizeInBits = Ctx.getTypeSize(Ty);
15789
15790 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15791 while (!Stack.empty()) {
15792 Data Current = Stack.back();
15793 Stack.pop_back();
15794 Visit(Current);
15795 }
15796 MergeOccuppiedIntervals();
15797 }
15798
15799 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15800 llvm::SmallVector<ASTContext::BitInterval> Results;
15801 if (OccuppiedIntervals.size() == 1 &&
15802 OccuppiedIntervals.front().First == 0 &&
15803 OccuppiedIntervals.front().Last == TySizeInBits) {
15804 return Results;
15805 }
15806 Results.reserve(OccuppiedIntervals.size() + 1);
15807 uint64_t CurrentPos = 0;
15808 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15809 if (OccupiedInterval.First > CurrentPos) {
15810 Results.push_back(
15811 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15812 }
15813 CurrentPos = OccupiedInterval.Last;
15814 }
15815 if (TySizeInBits > CurrentPos) {
15816 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15817 }
15818 return Results;
15819 }
15820
15821private:
15822 struct Data {
15823 uint64_t StartBitOffset;
15824 QualType Ty;
15825 bool VisitVirtualBase;
15826 };
15827
15828 // Return the number of non padding bits of a scalar type.
15829 //
15830 // The property that we specifically care about here is whether the scalar
15831 // type has padding bits, i.e. are there bits in the type which are not
15832 // specified by the ABI.
15833 //
15834 // We currently don't care about this anywhere else in clang: layout cares
15835 // about the ABI size, calling convention code cares about specific types,
15836 // but nothing cares about padding specifically. And it's not something we can
15837 // easily query from LLVM due to the type system mismatches.
15838 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15839 // DataLayout methods aren't really designed for this usage.
15840 //
15841 // Therefore, it is better to explicitly list all the scalar types
15842 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15843 // double.
15844 //
15845 // FIXME: There are likely other scalar types we need to think about here, as
15846 // brought up in review for #215823:
15847 // - bool
15848 // - enums(both with/without fixed underlying type)
15849 // - nullptr_t
15850 // - more?
15851 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15852 if (const auto *BIT = Ty->getAs<BitIntType>())
15853 return BIT->getNumBits();
15854
15855 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15856 if (BT->getKind() == BuiltinType::LongDouble &&
15858 &llvm::APFloat::x87DoubleExtended())
15859 return llvm::APFloat::getSizeInBits(
15861 }
15862
15863 return Ctx.getTypeSize(Ty);
15864 }
15865
15866 void Visit(const Data &D) {
15867 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15868 VisitArray(AT, D.StartBitOffset);
15869 return;
15870 }
15871
15872 if (auto *Record = D.Ty->getAsRecordDecl()) {
15873 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15874 return;
15875 }
15876
15877 if (D.Ty->isAtomicType()) {
15878 auto Unwrapped = D;
15879 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15880 Stack.push_back(Unwrapped);
15881 return;
15882 }
15883
15884 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15885 VisitComplex(Complex, D.StartBitOffset);
15886 return;
15887 }
15888
15889 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15890 VisitVector(VT, D.StartBitOffset);
15891 return;
15892 }
15893
15894 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15895 VisitBitInt(BITy, D.StartBitOffset);
15896 return;
15897 }
15898
15899 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15900 OccuppiedIntervals.push_back(
15901 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15902 }
15903
15904 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15905 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15906 ++ArrIndex) {
15907
15908 QualType ElementQualType = AT->getElementType();
15909 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15910 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15911 auto Offset = ElementSize.alignTo(ElementAlign);
15912
15913 Stack.push_back(Data{
15914 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15915 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15916 }
15917 }
15918
15919 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15920 bool VisitVirtualBase) {
15921 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15922 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15923
15924 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15925
15926 if (CXXRecord) {
15927 if (ASTLayout.hasOwnVFPtr()) {
15928 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15929 StartBitOffset, StartBitOffset + PointerSizeInBits});
15930 }
15931
15932 if (ASTLayout.hasOwnVBPtr()) {
15933 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15934 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15935 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15936 StartVBPtr, StartVBPtr + PointerSizeInBits});
15937 }
15938
15939 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15940 const CXXBaseSpecifier &Base, auto GetOffset) {
15941 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15942 if (!BaseRecord) {
15943 return;
15944 }
15945 auto BaseOffset =
15946 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15947
15948 Stack.push_back(
15949 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15950 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15951 false});
15952 };
15953
15954 for (auto Base : CXXRecord->bases()) {
15955 if (!Base.isVirtual()) {
15956 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15957 }
15958 }
15959
15960 if (VisitVirtualBase) {
15961 for (auto VBase : CXXRecord->vbases()) {
15962 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15963 }
15964 }
15965 }
15966
15967 for (auto *Field : R->fields()) {
15968 // Treat unnamed bitfields as padding.
15969 if (Field->isUnnamedBitField())
15970 continue;
15971
15972 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
15973 if (Field->isBitField()) {
15974 VisitBitfield(Field, StartBitOffset + FieldOffset);
15975 } else {
15976 Stack.push_back(Data{StartBitOffset + FieldOffset,
15977 Field->getType().getCanonicalType(),
15978 /*VisitVirtualBase*/ true});
15979 }
15980 }
15981 }
15982
15983 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
15984 assert(Field->isBitField() && !Field->isUnnamedBitField());
15985 if (Field->isZeroLengthBitField())
15986 return;
15987
15988 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
15989
15990 // Oversized bit-fields (declared width larger than the field type) occupy
15991 // only the type's width. The extra declared bits are padding and follow
15992 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
15993 // In case where the bitfield can only have values with a range smaller than
15994 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
15995 // within the bitfield are for sign or zero extension. These are considered
15996 // occupied as well.
15997 const uint64_t OccupiedSizeInBits =
15998 std::min(DeclaredSizeInBits, Ctx.getTypeSize(Field->getType()));
15999
16000 if (Ctx.getTargetInfo().isLittleEndian()) {
16001 OccuppiedIntervals.push_back(
16002 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16003 return;
16004 }
16005
16006 // In big endian mode, the sequence of occupied bits traverses bytes in
16007 // increasing address order, just like in little endian. However, within
16008 // each byte, the traversal starts from the most significant bit. This is
16009 // where it differs from little endian.
16010 //
16011 // If the interval contains whole bytes in the middle, then for these
16012 // nothing changes, and they constitute a contiguous interval. However for
16013 // the partially occupied bytes in either end, if present, their bit
16014 // intervals need to be adjusted so that they count from the MSB instead.
16015 //
16016 // Occupied bits are allocated first, and any padding follows them.
16017 const uint64_t Start = StartBitOffset;
16018 const uint64_t End = Start + OccupiedSizeInBits;
16019 const uint64_t CharWidth = Ctx.getCharWidth();
16020
16021 // Special case: all the occupied bits are contained within a single byte.
16022 const uint64_t ByteStart = llvm::alignDown(Start, CharWidth);
16023 const uint64_t ByteEnd = llvm::alignTo(End, CharWidth);
16024 if (ByteStart == ByteEnd - CharWidth) {
16025 const uint64_t Length = End - Start;
16026 const uint64_t Offset = Start - ByteStart;
16027 OccuppiedIntervals.push_back(
16028 {ByteEnd - Offset - Length, ByteEnd - Offset});
16029 return;
16030 }
16031
16032 // Compute the contiguous interval in the middle, comprised of whole bytes,
16033 // if any.
16034 const uint64_t MiddleIntervalStart = llvm::alignTo(Start, CharWidth);
16035 const uint64_t MiddleIntervalEnd = llvm::alignDown(End, CharWidth);
16036 if (MiddleIntervalStart != MiddleIntervalEnd)
16037 OccuppiedIntervals.push_back({MiddleIntervalStart, MiddleIntervalEnd});
16038
16039 // Compute the partially occupied first byte's interval, if any, counting
16040 // from the MSB.
16041 if (Start != MiddleIntervalStart) {
16042 const uint64_t Length = MiddleIntervalStart - Start;
16043 OccuppiedIntervals.push_back({ByteStart, ByteStart + Length});
16044 }
16045
16046 // Compute the partially occupied last byte's interval, if any, counting
16047 // from the MSB.
16048 if (End != MiddleIntervalEnd) {
16049 const uint64_t Length = End - MiddleIntervalEnd;
16050 OccuppiedIntervals.push_back({ByteEnd - Length, ByteEnd});
16051 }
16052 }
16053
16054 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16055 QualType ElementQualType = CT->getElementType().getCanonicalType();
16056 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
16057 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
16058 auto ImgOffset = ElementSize.alignTo(ElementAlign);
16059
16060 Stack.push_back(
16061 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
16062 Stack.push_back(
16063 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16064 ElementQualType, /*VisitVirtualBase*/ true});
16065 }
16066
16067 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16068 if (VT->isPackedVectorBoolType(Ctx)) {
16069 VisitPackedBooleanVector(VT, StartBitOffset);
16070 return;
16071 }
16072
16073 uint64_t SizeBit = getScalarOccupiedSizeInBits(VT->getElementType()) *
16074 VT->getNumElements();
16075 OccuppiedIntervals.push_back(
16076 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
16077 }
16078
16079 /// Compute the occupied bit intervals for a BitInt.
16080 ///
16081 /// In the case of little endian, the occupied bits are always contiguous so a
16082 /// single interval is sufficient. However in big endian, the intervals can be
16083 /// disjoint.
16084 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16085 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16086
16087 if (Ctx.getTargetInfo().isLittleEndian()) {
16088 OccuppiedIntervals.push_back(
16089 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16090 return;
16091 }
16092
16093 // In big endian mode, the layout of a BitInt in memory has its bytes in
16094 // reverse order, and is pictured in this order:
16095 // 1. Fully padding bytes.
16096 // 2. One partially occupied byte, with padding at the most significant
16097 // bits. ("remaining occupied bits")
16098 // 3. A sequence of fully occupied bytes up until the end of the storage.
16099 const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
16100 const uint64_t CharWidth = Ctx.getCharWidth();
16101 const uint64_t NumFullyPaddingBytes =
16102 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16103 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16104 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16105
16106 // Partially occupied byte
16107 if (NumRemainingOccupiedBits > 0)
16108 OccuppiedIntervals.push_back(
16109 {StartBitOffset + NumFullyPaddingBytes * CharWidth,
16110 StartBitOffset + NumFullyPaddingBytes * CharWidth +
16111 NumRemainingOccupiedBits});
16112
16113 // Fully occupied bytes
16114 if (NumFullyOccupiedBytes > 0)
16115 OccuppiedIntervals.push_back({StartBitOffset + StorageSizeInBits -
16116 NumFullyOccupiedBytes * CharWidth,
16117 StartBitOffset + StorageSizeInBits});
16118 }
16119
16120 void VisitPackedBooleanVector(const VectorType *VTy,
16121 uint64_t StartBitOffset) {
16122 const uint64_t CharWidth = Ctx.getCharWidth();
16123 assert(StartBitOffset % CharWidth == 0 &&
16124 "Expected aligned packed boolean vector");
16125 assert(VTy->isPackedVectorBoolType(Ctx));
16126 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16127
16128 if (Ctx.getTargetInfo().isLittleEndian()) {
16129 OccuppiedIntervals.push_back(
16130 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16131 return;
16132 }
16133
16134 // Only the sequence of bytes containing occupied bits has its order
16135 // reversed, but the bits within each byte are still counted from the least
16136 // significant bit. So if there are fully padding bytes, they reside at the
16137 // higher addresses in both endiannesses.
16138 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16139 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16140
16141 uint64_t Start = StartBitOffset;
16142 // Partially occupied byte at the beginning
16143 if (NumRemainingOccupiedBits > 0) {
16144 const uint64_t ByteEnd = Start + CharWidth;
16145 OccuppiedIntervals.push_back({Start, Start + NumRemainingOccupiedBits});
16146 Start = ByteEnd;
16147 }
16148
16149 // The remaining fully occupied bytes form a contiguous interval
16150 if (NumFullyOccupiedBytes > 0) {
16151 OccuppiedIntervals.push_back(
16152 {Start, Start + NumFullyOccupiedBytes * CharWidth});
16153 }
16154 }
16155
16156 void MergeOccuppiedIntervals() {
16157 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
16158 [](const ASTContext::BitInterval &lhs,
16159 const ASTContext::BitInterval &rhs) {
16160 return std::tie(lhs.First, lhs.Last) <
16161 std::tie(rhs.First, rhs.Last);
16162 });
16163
16164 llvm::SmallVector<ASTContext::BitInterval> Merged;
16165 Merged.reserve(OccuppiedIntervals.size());
16166
16167 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16168 if (Merged.empty()) {
16169 Merged.push_back(NextInterval);
16170 continue;
16171 }
16172 auto &LastInterval = Merged.back();
16173
16174 if (NextInterval.First > LastInterval.Last) {
16175 Merged.push_back(NextInterval);
16176 } else {
16177 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
16178 }
16179 }
16180
16181 OccuppiedIntervals = Merged;
16182 }
16183
16184 const ASTContext &Ctx;
16185 // unsigned PointerSizeInBits;
16186 uint64_t TySizeInBits = 0;
16187 llvm::SmallVector<Data> Stack;
16188 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16189};
16190} // namespace
16191
16192llvm::ArrayRef<ASTContext::BitInterval>
16194 Ty = Ty.getCanonicalType();
16195 auto cached = PaddingIntervalCache.find(Ty);
16196 if (cached != PaddingIntervalCache.end())
16197 return cached->second;
16198
16199 PaddingCalculator pc{*this};
16200 pc.run(Ty);
16201
16202 auto [itr, res] =
16203 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
16204 assert(res && "Failed to insert?");
16205
16206 return itr->second;
16207}
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 QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static bool hasImplicitAttr(const ValueDecl *D)
#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 SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static TypedefDecl * CreateZOSVaListDecl(const ASTContext *Context)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static std::string charUnitsToString(CharUnits CU)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static 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:504
This file provides some common utility functions for processing Lambda related AST Constructs.
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:2854
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::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
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:96
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
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>
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1216
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1223
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns, std::optional< MatrixType::LayoutKind > Layout=std::nullopt) const
Return the unique reference to the matrix type of the specified element type and size.
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 getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:856
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.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
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
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs(const CXXConstructorDecl *CD)
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.
TemplateName getPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< TemplateName > Expansions={}) const
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.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
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:857
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool 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...
void completeCountAttributedType(CountAttributedType *CATy, Expr *CountExpr, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
Supply the count expression and coupled declarations for a type created by getIncompleteCountAttribut...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
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
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:852
Builtin::Context & BuiltinInfo
Definition ASTContext.h:854
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
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:853
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.
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 getLateParsedAttrType(QualType Wrapped, LateParsedTypeAttribute *LateParsedAttr) const
Return a placeholder type for a late-parsed type attribute.
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...
llvm::ArrayRef< BitInterval > getPaddingIntervals(QualType Ty) const
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.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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 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.
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
CanQualType MetaInfoTy
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:972
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:615
CanQualType UnsignedLongTy
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
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:855
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
CountAttributedType * getIncompleteCountAttributedType(QualType WrappedTy, bool CountInBytes, bool OrNull) const
Return a CountAttributedType whose count expression has not been parsed yet, for use by a late-parsed...
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
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.
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
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:246
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:858
CanQualType ObjCBuiltinBoolTy
TypeInfoChars getTypeInfoInChars(const Type *T) const
QualType getPredefinedSugarType(PredefinedSugarType::Kind KD) const
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
TemplateParamObjectDecl * getTemplateParamObjectDecl(QualType T, const APValue &V) const
Return the template parameter object of the given type with the given value.
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CanQualType OverloadTy
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
TemplateTemplateParmDecl * getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const
Canonicalize the given TemplateTemplateParmDecl.
CanQualType OCLClkEventTy
void adjustExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, bool AsWritten=false)
Change the exception specification on a function once it is delay-parsed, instantiated,...
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
bool hasPFPFields(QualType Ty) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:905
void ResetObjCLayout(const ObjCInterfaceDecl *D)
ArrayRef< Module * > getModulesWithMergedDefinition(const NamedDecl *Def)
Get the additional modules in which the definition Def has been merged.
void setCtorClosureDefaultArgs(const CXXConstructorDecl *CD, ArrayRef< CXXDefaultArgExpr * > Args)
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CanQualType SatUnsignedShortAccumTy
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
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:607
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getObjCIdType() const
Represents the Objective-CC id type.
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
QualType getUnsignedWCharType() const
Return the type of "unsigned wchar_t".
QualType getFunctionTypeWithoutParamABIs(QualType T) const
Get or construct a function type that is equivalent to the input type except that the parameter ABI a...
QualType getCorrespondingUnsaturatedType(QualType Ty) const
comments::FullComment * getCommentForDecl(const Decl *D, const Preprocessor *PP) const
Return parsed documentation comment attached to a given declaration.
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
unsigned getTargetDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::DenseMap< CanQualType, SYCLKernelInfo > SYCLKernels
Map of SYCL kernels indexed by the unique type used to name the kernel.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType BuiltinFnTy
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
unsigned NumImplicitDefaultConstructors
The number of implicitly-declared default constructors.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::iterator_range< overridden_cxx_method_iterator > overridden_method_range
unsigned NumImplicitMoveAssignmentOperatorsDeclared
The number of implicitly-declared move assignment operators for which declarations were built.
void setManglingNumber(const NamedDecl *ND, unsigned Number)
CanQualType OCLSamplerTy
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:926
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
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...
static bool isPFPField(const FieldDecl *Field)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
AttrVec * allocateAttrVec()
Allocate an empty attribute vector with the lifetime of this context.
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.
llvm::DenseMap< RawCommentLookupKey, const RawComment * > RawComments
Mapping from declaration or macro to directly attached comment.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
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 classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
QualType getTemplateTypeParmType(int Depth, int Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
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.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE)
Return number of elements initialized in a (potentially nested) ArrayInitLoopExpr.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
bool shouldEmitCUDADecl(const ValueDecl *D) const
Determines if the global variable or function D is emitted on the side of the CUDA/HIP compilation,...
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.
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.
unsigned getTargetAddressSpace(LangAS AS) const
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition ASTContext.h:878
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
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
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD, bool IsVTTEntry)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers using the ...
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
QualType getMatrixTypeWithLayout(QualType T, MatrixType::LayoutKind Layout) const
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
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.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
CXXMethodVector::const_iterator overridden_cxx_method_iterator
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)
TypedefDecl * getBuiltinZOSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_zos_va_list type.
void recordMemberDataPointerEvaluation(const ValueDecl *VD)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
unsigned NumImplicitMoveAssignmentOperators
The number of implicitly-declared move assignment operators.
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
virtual void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType)
A function's return type has been deduced.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
bool hasOwnVFPtr() const
hasOwnVFPtr - Does this class provide its own virtual-function table pointer, rather than inheriting ...
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
const CXXRecordDecl * getBaseSharingVBPtr() const
bool hasOwnVBPtr() const
hasOwnVBPtr - Does this class provide its own virtual-base table pointer, rather than inheriting one ...
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 getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
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:3605
Represents a loop initializing the elements of an array.
Definition Expr.h:6054
llvm::APInt getArraySize() const
Definition Expr.h:6076
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3990
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3838
QualType getElementType() const
Definition TypeBase.h:3832
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3842
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:7014
Expr * getPtr() const
Definition Expr.h:7045
Attr - This represents one attribute.
Definition Attr.h:47
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8436
unsigned getNumBits() const
Definition TypeBase.h:8448
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
Pointer to a block type.
Definition TypeBase.h:3653
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:3245
Kind getKind() const
Definition TypeBase.h:3299
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:238
Implements C++ ABI-specific semantic analysis functions.
Definition CXXABI.h:29
virtual ~CXXABI()
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2915
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2266
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:133
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
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.
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
Test whether the quantity is greater than zero.
Definition CharUnits.h:107
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:206
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:200
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3954
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3973
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4692
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4641
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3509
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3554
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool isFileContext() const
Definition DeclBase.h:2199
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2124
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.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Decl::Kind getDeclKind() const
Definition DeclBase.h:2101
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
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:344
bool isModuleLocal() const
Whether this declaration was a local declaration to a C++20 named module.
T * getAttr() const
Definition DeclBase.h:582
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:872
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1002
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:855
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:597
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
void setImplicit(bool I=true)
Definition DeclBase.h:603
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1067
DeclContext * getDeclContext()
Definition DeclBase.h:457
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
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:782
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
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:4159
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4181
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8475
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4109
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4138
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4199
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4224
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4714
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4734
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:6492
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6497
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4457
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4482
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4192
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4410
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4424
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4308
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4365
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:114
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:3134
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
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:4110
QualType getType() const
Definition Expr.h:146
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:1736
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1783
ExtVectorType - Extended vector type.
Definition TypeBase.h:4497
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:249
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5656
Abstract interface for external sources of AST nodes.
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4854
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
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:4802
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:2082
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2862
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3835
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3098
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3969
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3820
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2438
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4492
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2579
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:4153
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5516
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:6055
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6093
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5348
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5382
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:5126
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5142
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:6052
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5855
unsigned getNumParams() const
Definition TypeBase.h:5826
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4237
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5861
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:6021
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:6017
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4855
CallingConv getCC() const
Definition TypeBase.h:4914
unsigned getRegParm() const
Definition TypeBase.h:4907
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4903
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4926
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4770
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4810
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
ExtInfo getExtInfo() const
Definition TypeBase.h:5100
QualType getReturnType() const
Definition TypeBase.h:5084
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:134
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
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:5237
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4024
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
@ PostDecrInWhile
while (count–)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
Represents a placeholder type for late-parsed type attributes.
Definition TypeBase.h:3577
A global _GUID constant.
Definition DeclCXX.h:4459
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4496
MSGuidDeclParts Parts
Definition DeclCXX.h:4461
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6426
MangleContext - Context for tracking state which persists across multiple calls to the C++ name mangl...
Definition Mangle.h:56
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4593
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4586
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3794
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:340
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
This represents a decl that may have a name.
Definition Decl.h:276
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:489
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
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:319
bool isExternallyVisible() const
Definition Decl.h:435
Represent a C++ namespace.
Definition Decl.h:594
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
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
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, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2551
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
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:1534
ivar_range ivars() const
Definition DeclObjC.h:1457
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:1816
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8163
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:1084
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
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:350
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
bool isVariadic() const
Definition DeclObjC.h:434
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
QualType getReturnType() const
Definition DeclObjC.h:332
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8300
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:1091
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8294
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8256
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8277
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8231
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8271
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2011
qual_range quals() const
Definition TypeBase.h:8338
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8283
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
Definition DeclObjC.h:844
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:922
SetterKind getSetterKind() const
getSetterKind - Return the method used for doing assignment in the property setter.
Definition DeclObjC.h:879
Selector getSetterName() const
Definition DeclObjC.h:899
QualType getType() const
Definition DeclObjC.h:810
Selector getGetterName() const
Definition DeclObjC.h:891
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2811
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:2885
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2090
protocol_range protocols() const
Definition DeclObjC.h:2167
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:581
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:626
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:665
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2596
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
unsigned getNumComponents() const
Definition Expr.h:2651
Helper class for OffsetOfExpr.
Definition Expr.h:2490
@ Field
A field.
Definition Expr.h:2497
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:4417
A structure for storing a pack-index-template-name ([temp.names]).
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
ArrayRef< TemplateName > getExpansions() const
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3383
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1832
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1896
QualType getOriginalType() const
Definition Decl.cpp:2972
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PredefinedSugarKind Kind
Definition TypeBase.h:8489
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasAddressDiscriminatedPointerAuth() const
Definition TypeBase.h:1473
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3092
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8709
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8667
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
QualType withConst() const
Definition TypeBase.h:1175
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition TypeBase.h:1065
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8599
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8635
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8582
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
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:3235
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8610
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:8518
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8525
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:385
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:639
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:690
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:625
bool hasUnaligned() const
Definition TypeBase.h:512
bool hasAddressSpace() const
Definition TypeBase.h:571
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:709
unsigned getFastQualifiers() const
Definition TypeBase.h:620
void removeAddressSpace()
Definition TypeBase.h:597
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:456
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:529
bool empty() const
Definition TypeBase.h:648
void addObjCGCAttr(GC type)
Definition TypeBase.h:525
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
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:4506
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5354
bool hasFlexibleArrayMember() const
Definition Decl.h:4539
field_range fields() const
Definition Decl.h:4709
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5340
RecordDecl * getMostRecentDecl()
Definition Decl.h:4532
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5399
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4690
bool field_empty() const
Definition Decl.h:4717
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:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
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:1844
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:1198
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:3898
TagTypeKind TagKind
Definition Decl.h:3903
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4135
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5014
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:5007
bool isUnion() const
Definition Decl.h:4109
TagKind getTagKind() const
Definition Decl.h:4098
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:228
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:854
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:747
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:341
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:350
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:355
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:364
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:343
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:346
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:359
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:513
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:415
bool isLittleEndian() const
IntType getSizeType() const
Definition TargetInfo.h:396
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:974
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:755
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:397
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:805
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...
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.
bool isNull() const
Determine whether this template name is NULL.
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.
@ PackIndexingTemplate
A pack-index-template-name.
@ 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.
PackIndexingTemplateStorage * getAsPackIndexingTemplate() const
Retrieve the pack-index-template-name storage, if any.
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.
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Token - This structure provides full information about a lexed token.
Definition Token.h:36
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:224
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:241
TemplateName getNamedConcept() const
Definition ASTConcept.h:251
ConceptReference * getConceptReference() const
Definition ASTConcept.h:245
Represents a declaration of a type.
Definition Decl.h:3694
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
static unsigned getFullDataSizeForType(QualType Ty)
Returns the size of type source info data block for the given type.
Definition TypeLoc.cpp:95
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6458
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isObjCBuiltinType() const
Definition TypeBase.h:9045
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2897
bool isIncompleteArrayType() const
Definition TypeBase.h:8922
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isFloat16Type() const
Definition TypeBase.h:9213
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:8918
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:2645
bool isArrayType() const
Definition TypeBase.h:8914
bool isCharType() const
Definition Type.cpp:2319
bool isPointerType() const
Definition TypeBase.h:8815
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8930
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
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:9292
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isObjCQualifiedIdType() const
Definition TypeBase.h:9015
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isBitIntType() const
Definition TypeBase.h:9090
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
bool isHalfType() const
Definition TypeBase.h:9208
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9280
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2344
@ SizeT
The "size_t" type.
Definition TypeBase.h:2338
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2341
bool isObjCIdType() const
Definition TypeBase.h:9027
bool isOverflowBehaviorType() const
Definition TypeBase.h:8986
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9288
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
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:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
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:9306
bool isVectorType() const
Definition TypeBase.h:8954
bool isObjCClassType() const
Definition TypeBase.h:9033
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2879
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2816
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
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:2460
bool isAnyPointerType() const
Definition TypeBase.h:8823
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5609
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3848
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5874
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3743
QualType getUnderlyingType() const
Definition Decl.h:3798
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6402
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Opcode getOpcode() const
Definition Expr.h:2349
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4516
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4544
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6263
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6300
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4075
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4140
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3830
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3437
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3501
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition DeclCXX.cpp:3487
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType)
Definition TypeBase.h:6340
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void setType(QualType newType)
Definition Decl.h:726
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5689
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:934
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2802
bool hasInit() const
Definition Decl.cpp:2400
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:2463
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
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:1216
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1588
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1320
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2377
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:2771
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4429
VectorKind getVectorKind() const
Definition TypeBase.h:4418
QualType getElementType() const
Definition TypeBase.h:4412
A full comment attached to a declaration, contains block content.
Definition Comment.h:1097
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1135
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1129
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1125
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
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,...
Top level wrappers for InstallAPI frontend operations.
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:1838
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:214
@ OCLTK_ReserveID
Definition TargetInfo.h:221
@ OCLTK_Sampler
Definition TargetInfo.h:222
@ OCLTK_Pipe
Definition TargetInfo.h:219
@ OCLTK_ClkEvent
Definition TargetInfo.h:216
@ OCLTK_Event
Definition TargetInfo.h:217
@ OCLTK_Default
Definition TargetInfo.h:215
@ OCLTK_Queue
Definition TargetInfo.h:220
bool isRVVFixedLengthDataVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length data vector kinds, i.e.
Definition TypeBase.h:4316
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8713
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:359
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ 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:919
@ AS_public
Definition Specifiers.h:128
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
unsigned getRVVFixedLengthMaskRatioLog2(VectorKind VK)
Return log2 of the R of the vbool<R>_t type recorded in an RVV fixed-length mask vector kind: Ratio1 ...
Definition TypeBase.h:4345
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:261
@ SC_Static
Definition Specifiers.h:256
bool isRVVFixedLengthVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length data or mask vector kinds.
Definition TypeBase.h:4352
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3817
OptionalUnsigned< unsigned > UnsignedOrNone
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:6176
@ Struct
The "struct" keyword.
Definition TypeBase.h:6173
@ Class
The "class" keyword.
Definition TypeBase.h:6182
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:498
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:555
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1811
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:76
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1306
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ConceptReference *C)
Insertion operator for diagnostics.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_M68kRTD
Definition Specifiers.h:302
@ CC_X86RegCall
Definition Specifiers.h:291
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:558
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:566
@ 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:562
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4243
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4240
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ ResistPragmaPack
The type's natural alignment is preserved under pragma pack in MSVC record layout (e....
Definition ASTContext.h:189
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:185
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:179
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:182
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:844
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6146
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6151
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6148
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6154
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6164
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)
bool isRVVFixedLengthMaskVectorKind(VectorKind VK)
True if VK is one of the RVV fixed-length mask vector kinds, i.e.
Definition TypeBase.h:4338
unsigned long uint64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 int64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:90
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:91
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6804
Expr * getCopyExpr() const
Definition Expr.h:6811
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:5605
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5610
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5613
Extra information about a function prototype.
Definition TypeBase.h:5633
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5679
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5638
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5683
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5672
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:3518
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:238
constexpr underlying_type toInternalRepresentation() const
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:59
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
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:148
AlignRequirementKind AlignRequirement
Definition ASTContext.h:210
bool isAlignRequired()
Definition ASTContext.h:201
AlignRequirementKind AlignRequirement
Definition ASTContext.h:195
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:974
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1000
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:977