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"
21#include "clang/AST/Attr.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/Comment.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/DeclBase.h"
27#include "clang/AST/DeclCXX.h"
29#include "clang/AST/DeclObjC.h"
34#include "clang/AST/Expr.h"
35#include "clang/AST/ExprCXX.h"
37#include "clang/AST/Mangle.h"
43#include "clang/AST/Stmt.h"
46#include "clang/AST/Type.h"
47#include "clang/AST/TypeLoc.h"
56#include "clang/Basic/LLVM.h"
58#include "clang/Basic/Linkage.h"
59#include "clang/Basic/Module.h"
69#include "clang/Lex/MacroInfo.h"
70#include "llvm/ADT/APFixedPoint.h"
71#include "llvm/ADT/APInt.h"
72#include "llvm/ADT/APSInt.h"
73#include "llvm/ADT/ArrayRef.h"
74#include "llvm/ADT/DenseMap.h"
75#include "llvm/ADT/DenseSet.h"
76#include "llvm/ADT/FoldingSet.h"
77#include "llvm/ADT/PointerUnion.h"
78#include "llvm/ADT/STLExtras.h"
79#include "llvm/ADT/SmallPtrSet.h"
80#include "llvm/ADT/SmallVector.h"
81#include "llvm/ADT/StringExtras.h"
82#include "llvm/ADT/StringRef.h"
83#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
84#include "llvm/Support/Capacity.h"
85#include "llvm/Support/Casting.h"
86#include "llvm/Support/Compiler.h"
87#include "llvm/Support/ErrorHandling.h"
88#include "llvm/Support/MD5.h"
89#include "llvm/Support/MathExtras.h"
90#include "llvm/Support/SipHash.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/TargetParser/AArch64TargetParser.h"
93#include "llvm/TargetParser/Triple.h"
94#include <algorithm>
95#include <cassert>
96#include <cstddef>
97#include <cstdint>
98#include <cstdlib>
99#include <map>
100#include <memory>
101#include <optional>
102#include <string>
103#include <tuple>
104#include <utility>
105
106using namespace clang;
107
118
119/// \returns The locations that are relevant when searching for Doc comments
120/// related to \p Key.
123 SourceManager &SourceMgr) {
124 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
125 SourceLocation DefLoc = MI->getDefinitionLoc();
126 if (DefLoc.isInvalid() || !DefLoc.isFileID())
127 return {};
128
129 // The macro's definition location points at its name (e.g. FOO in
130 // `#define FOO 1`). The text between a preceding documentation comment
131 // and the name contains the `#define` directive itself, which would be
132 // rejected by the preprocessor-directive guard in
133 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
134 // the guard only fires when something *else* sits between the comment
135 // and our directive.
136 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
137 bool Invalid = false;
138 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
139 if (Invalid)
140 return {};
141 unsigned Offset = Decomposed.second;
142 if (size_t Found = Buffer.find_last_of("#\n", Offset);
143 Found != StringRef::npos)
144 Offset = Found;
145 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
146 .getLocWithOffset(Offset)};
147 }
148
149 const auto *D = cast<const Decl *>(Key);
150 assert(D);
151
152 // User can not attach documentation to implicit declarations.
153 if (D->isImplicit())
154 return {};
155
156 // User can not attach documentation to implicit instantiations.
157 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
158 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
159 return {};
160 }
161
162 if (const auto *VD = dyn_cast<VarDecl>(D)) {
163 if (VD->isStaticDataMember() &&
164 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
165 return {};
166 }
167
168 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
169 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
170 return {};
171 }
172
173 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
174 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
175 if (TSK == TSK_ImplicitInstantiation ||
176 TSK == TSK_Undeclared)
177 return {};
178 }
179
180 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
181 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
182 return {};
183 }
184 if (const auto *TD = dyn_cast<TagDecl>(D)) {
185 // When tag declaration (but not definition!) is part of the
186 // decl-specifier-seq of some other declaration, it doesn't get comment
187 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
188 return {};
189 }
190 // TODO: handle comments for function parameters properly.
191 if (isa<ParmVarDecl>(D))
192 return {};
193
194 // TODO: we could look up template parameter documentation in the template
195 // documentation.
199 return {};
200
202 // Find declaration location.
203 // For Objective-C declarations we generally don't expect to have multiple
204 // declarators, thus use declaration starting location as the "declaration
205 // location".
206 // For all other declarations multiple declarators are used quite frequently,
207 // so we use the location of the identifier as the "declaration location".
208 SourceLocation BaseLocation;
212 // Allow association with Y across {} in `typedef struct X {} Y`.
214 BaseLocation = D->getBeginLoc();
215 else
216 BaseLocation = D->getLocation();
217
218 if (!D->getLocation().isMacroID()) {
219 Locations.emplace_back(BaseLocation);
220 } else {
221 const auto *DeclCtx = D->getDeclContext();
222
223 // When encountering definitions generated from a macro (that are not
224 // contained by another declaration in the macro) we need to try and find
225 // the comment at the location of the expansion but if there is no comment
226 // there we should retry to see if there is a comment inside the macro as
227 // well. To this end we return first BaseLocation to first look at the
228 // expansion site, the second value is the spelling location of the
229 // beginning of the declaration defined inside the macro.
230 if (!(DeclCtx &&
231 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
232 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
233 }
234
235 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
236 // we don't refer to the macro argument location at the expansion site (this
237 // can happen if the name's spelling is provided via macro argument), and
238 // always to the declaration itself.
239 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
240 }
241
242 return Locations;
243}
244
246 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
247 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
248 // If the declaration doesn't map directly to a location in a file, we
249 // can't find the comment.
250 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
251 return nullptr;
252
253 // If there are no comments anywhere, we won't find anything.
254 if (CommentsInTheFile.empty())
255 return nullptr;
256
257 const auto *D = dyn_cast<const Decl *>(Key);
258 const bool IsMacro = isa<const MacroInfo *>(Key);
259
260 // Decompose the location for the declaration and find the beginning of the
261 // file buffer.
262 const FileIDAndOffset LocDecomp =
263 SourceMgr.getDecomposedLoc(RepresentativeLoc);
264
265 // Slow path.
266 auto OffsetCommentBehindDecl =
267 CommentsInTheFile.lower_bound(LocDecomp.second);
268
269 // First check whether we have a trailing comment.
270 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
271 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
272 if ((CommentBehindDecl->isDocumentation() ||
273 LangOpts.CommentOpts.ParseAllComments) &&
274 CommentBehindDecl->isTrailingComment() &&
275 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
277 isa<ObjCPropertyDecl>(D))))) {
278
279 // Check that Doxygen trailing comment comes after the declaration, starts
280 // on the same line and in the same file as the declaration.
281 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
282 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
283 OffsetCommentBehindDecl->first)) {
284 return CommentBehindDecl;
285 }
286 }
287 }
288
289 // The comment just after the declaration was not a trailing comment.
290 // Let's look at the previous comment.
291 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
292 return nullptr;
293
294 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
295 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
296
297 // Check that we actually have a non-member Doxygen comment.
298 if (!(CommentBeforeDecl->isDocumentation() ||
299 LangOpts.CommentOpts.ParseAllComments) ||
300 CommentBeforeDecl->isTrailingComment())
301 return nullptr;
302
303 // Decompose the end of the comment.
304 const unsigned CommentEndOffset =
305 Comments.getCommentEndOffset(CommentBeforeDecl);
306
307 // Get the corresponding buffer.
308 bool Invalid = false;
309 const char *Buffer =
310 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
311 if (Invalid)
312 return nullptr;
313
314 // Extract text between the comment and declaration.
315 StringRef Text(Buffer + CommentEndOffset,
316 LocDecomp.second - CommentEndOffset);
317
318 // There should be no other declarations or preprocessor directives between
319 // comment and declaration.
320 if (Text.find_last_of(";{}#@") != StringRef::npos)
321 return nullptr;
322
323 return CommentBeforeDecl;
324}
325
327 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
328
329 for (const auto Loc : Locs) {
330 // If the declaration or macro doesn't map directly to a location in a file,
331 // we can't find the comment.
332 if (Loc.isInvalid() || !Loc.isFileID())
333 continue;
334
336 ExternalSource->ReadComments();
337 CommentsLoaded = true;
338 }
339
340 if (Comments.empty())
341 continue;
342
343 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
344 if (!File.isValid())
345 continue;
346
347 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
348 if (!CommentsInThisFile || CommentsInThisFile->empty())
349 continue;
350
351 if (RawComment *Comment =
352 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
353 return Comment;
354 }
355
356 return nullptr;
357}
358
360 assert(LangOpts.RetainCommentsFromSystemHeaders ||
361 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
362 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
363}
364
365const RawComment *
367 const Decl **OriginalDecl) const {
368 if (Key.isNull()) {
369 if (OriginalDecl)
370 *OriginalDecl = nullptr;
371 return nullptr;
372 }
373
374 // Macros have no redeclaration chain: look up directly, populate the cache,
375 // and return.
376 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
377 if (OriginalDecl)
378 *OriginalDecl = nullptr;
379 auto Existing = RawComments.find(Key);
380 if (Existing != RawComments.end())
381 return Existing->second;
382 if (const RawComment *RC = getRawCommentNoCache(Key)) {
383 cacheRawComment(MI, *RC);
384 return RC;
385 }
386 return nullptr;
387 }
388
389 const Decl *D = cast<const Decl *>(Key);
390 D = &adjustDeclToTemplate(*D);
391
392 // Any comment directly attached to D?
393 {
394 auto DeclComment = RawComments.find(D);
395 if (DeclComment != RawComments.end()) {
396 if (OriginalDecl)
397 *OriginalDecl = D;
398 return DeclComment->second;
399 }
400 }
401
402 // Any comment attached to any redeclaration of D?
403 const Decl *CanonicalD = D->getCanonicalDecl();
404 if (!CanonicalD)
405 return nullptr;
406
407 {
408 auto RedeclComment = RedeclChainComments.find(CanonicalD);
409 if (RedeclComment != RedeclChainComments.end()) {
410 if (OriginalDecl)
411 *OriginalDecl = RedeclComment->second;
412 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
413 assert(CommentAtRedecl != RawComments.end() &&
414 "This decl is supposed to have comment attached.");
415 return CommentAtRedecl->second;
416 }
417 }
418
419 // Any redeclarations of D that we haven't checked for comments yet?
420 const Decl *LastCheckedRedecl = [&]() {
421 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
422 bool CanUseCommentlessCache = false;
423 if (LastChecked) {
424 for (auto *Redecl : CanonicalD->redecls()) {
425 if (Redecl == D) {
426 CanUseCommentlessCache = true;
427 break;
428 }
429 if (Redecl == LastChecked)
430 break;
431 }
432 }
433 // FIXME: This could be improved so that even if CanUseCommentlessCache
434 // is false, once we've traversed past CanonicalD we still skip ahead
435 // LastChecked.
436 return CanUseCommentlessCache ? LastChecked : nullptr;
437 }();
438
439 for (const Decl *Redecl : D->redecls()) {
440 assert(Redecl);
441 // Skip all redeclarations that have been checked previously.
442 if (LastCheckedRedecl) {
443 if (LastCheckedRedecl == Redecl) {
444 LastCheckedRedecl = nullptr;
445 }
446 continue;
447 }
448 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
449 if (RedeclComment) {
450 cacheRawComment(Redecl, *RedeclComment);
451 if (OriginalDecl)
452 *OriginalDecl = Redecl;
453 return RedeclComment;
454 }
455 CommentlessRedeclChains[CanonicalD] = Redecl;
456 }
457
458 if (OriginalDecl)
459 *OriginalDecl = nullptr;
460 return nullptr;
461}
462
464 const RawComment &Comment) const {
465 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
466 RawComments.try_emplace(Original, &Comment);
467 if (const auto *D = dyn_cast<const Decl *>(Original)) {
468 const Decl *const CanonicalDecl = D->getCanonicalDecl();
469 RedeclChainComments.try_emplace(CanonicalDecl, D);
470 CommentlessRedeclChains.erase(CanonicalDecl);
471 }
472}
473
474static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
476 const DeclContext *DC = ObjCMethod->getDeclContext();
477 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
478 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
479 if (!ID)
480 return;
481 // Add redeclared method here.
482 for (const auto *Ext : ID->known_extensions()) {
483 if (ObjCMethodDecl *RedeclaredMethod =
484 Ext->getMethod(ObjCMethod->getSelector(),
485 ObjCMethod->isInstanceMethod()))
486 Redeclared.push_back(RedeclaredMethod);
487 }
488 }
489}
490
492 const Preprocessor *PP) {
493 if (Comments.empty() || Decls.empty())
494 return;
495
496 FileID File;
497 for (const Decl *D : Decls) {
498 if (D->isInvalidDecl())
499 continue;
500
501 D = &adjustDeclToTemplate(*D);
502 SourceLocation Loc = D->getLocation();
503 if (Loc.isValid()) {
504 // See if there are any new comments that are not attached to a decl.
505 // The location doesn't have to be precise - we care only about the file.
506 File = SourceMgr.getDecomposedLoc(Loc).first;
507 break;
508 }
509 }
510
511 if (File.isInvalid())
512 return;
513
514 auto CommentsInThisFile = Comments.getCommentsInFile(File);
515 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
516 CommentsInThisFile->rbegin()->second->isAttached())
517 return;
518
519 // There is at least one comment not attached to a decl.
520 // Maybe it should be attached to one of Decls?
521 //
522 // Note that this way we pick up not only comments that precede the
523 // declaration, but also comments that *follow* the declaration -- thanks to
524 // the lookahead in the lexer: we've consumed the semicolon and looked
525 // ahead through comments.
526 for (const Decl *D : Decls) {
527 assert(D);
528 if (D->isInvalidDecl())
529 continue;
530
531 D = &adjustDeclToTemplate(*D);
532
533 if (RawComments.count(D) > 0)
534 continue;
535
536 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
537
538 for (const auto DeclLoc : DeclLocs) {
539 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
540 continue;
541
542 if (RawComment *const DocComment =
543 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
544 cacheRawComment(D, *DocComment);
545 comments::FullComment *FC = DocComment->parse(*this, PP, D);
546 ParsedComments[D->getCanonicalDecl()] = FC;
547 break;
548 }
549 }
550 }
551}
552
554 const Decl *D) const {
555 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
556 ThisDeclInfo->CommentDecl = D;
557 ThisDeclInfo->IsFilled = false;
558 ThisDeclInfo->fill();
559 ThisDeclInfo->CommentDecl = FC->getDecl();
560 if (!ThisDeclInfo->TemplateParameters)
561 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
563 new (*this) comments::FullComment(FC->getBlocks(),
564 ThisDeclInfo);
565 return CFC;
566}
567
569 const RawComment *RC = getRawCommentNoCache(D);
570 return RC ? RC->parse(*this, nullptr, D) : nullptr;
571}
572
574 const Decl *D,
575 const Preprocessor *PP) const {
576 if (!D || D->isInvalidDecl())
577 return nullptr;
578 D = &adjustDeclToTemplate(*D);
579
580 const Decl *Canonical = D->getCanonicalDecl();
581 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
582 ParsedComments.find(Canonical);
583
584 if (Pos != ParsedComments.end()) {
585 if (Canonical != D) {
586 comments::FullComment *FC = Pos->second;
588 return CFC;
589 }
590 return Pos->second;
591 }
592
593 const Decl *OriginalDecl = nullptr;
594
595 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
596 if (!RC) {
599 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
600 if (OMD && OMD->isPropertyAccessor())
601 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
602 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
603 return cloneFullComment(FC, D);
604 if (OMD)
605 addRedeclaredMethods(OMD, Overridden);
606 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
607 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
608 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
609 return cloneFullComment(FC, D);
610 }
611 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
612 // Attach any tag type's documentation to its typedef if latter
613 // does not have one of its own.
614 QualType QT = TD->getUnderlyingType();
615 if (const auto *TT = QT->getAs<TagType>())
616 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
617 return cloneFullComment(FC, D);
618 }
619 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
620 while (IC->getSuperClass()) {
621 IC = IC->getSuperClass();
623 return cloneFullComment(FC, D);
624 }
625 }
626 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
627 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
629 return cloneFullComment(FC, D);
630 }
631 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
632 if (!(RD = RD->getDefinition()))
633 return nullptr;
634 // Check non-virtual bases.
635 for (const auto &I : RD->bases()) {
636 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
637 continue;
638 QualType Ty = I.getType();
639 if (Ty.isNull())
640 continue;
642 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
643 continue;
644
646 return cloneFullComment(FC, D);
647 }
648 }
649 // Check virtual bases.
650 for (const auto &I : RD->vbases()) {
651 if (I.getAccessSpecifier() != AS_public)
652 continue;
653 QualType Ty = I.getType();
654 if (Ty.isNull())
655 continue;
656 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
657 if (!(VirtualBase= VirtualBase->getDefinition()))
658 continue;
660 return cloneFullComment(FC, D);
661 }
662 }
663 }
664 return nullptr;
665 }
666
667 // If the RawComment was attached to other redeclaration of this Decl, we
668 // should parse the comment in context of that other Decl. This is important
669 // because comments can contain references to parameter names which can be
670 // different across redeclarations.
671 if (D != OriginalDecl && OriginalDecl)
672 return getCommentForDecl(OriginalDecl, PP);
673
674 comments::FullComment *FC = RC->parse(*this, PP, D);
675 ParsedComments[Canonical] = FC;
676 return FC;
677}
678
679void ASTContext::CanonicalTemplateTemplateParm::Profile(
680 llvm::FoldingSetNodeID &ID, const ASTContext &C,
682 ID.AddInteger(Parm->getDepth());
683 ID.AddInteger(Parm->getPosition());
684 ID.AddBoolean(Parm->isParameterPack());
685 ID.AddInteger(Parm->templateParameterKind());
686
688 ID.AddInteger(Params->size());
690 PEnd = Params->end();
691 P != PEnd; ++P) {
692 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
693 ID.AddInteger(0);
694 ID.AddBoolean(TTP->isParameterPack());
695 ID.AddInteger(
696 TTP->getNumExpansionParameters().toInternalRepresentation());
697 continue;
698 }
699
700 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
701 ID.AddInteger(1);
702 ID.AddBoolean(NTTP->isParameterPack());
703 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
704 .getAsOpaquePtr());
705 if (NTTP->isExpandedParameterPack()) {
706 ID.AddBoolean(true);
707 ID.AddInteger(NTTP->getNumExpansionTypes());
708 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
709 QualType T = NTTP->getExpansionType(I);
710 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
711 }
712 } else
713 ID.AddBoolean(false);
714 continue;
715 }
716
717 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
718 ID.AddInteger(2);
719 Profile(ID, C, TTP);
720 }
721}
722
723TemplateTemplateParmDecl *
725 TemplateTemplateParmDecl *TTP) const {
726 // Check if we already have a canonical template template parameter.
727 llvm::FoldingSetNodeID ID;
728 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
729 llvm::FoldingSetInsertToken Token;
730 CanonicalTemplateTemplateParm *Canonical =
731 CanonTemplateTemplateParms.lookup(ID, Token);
732 if (Canonical)
733 return Canonical->getParam();
734
735 // Build a canonical template parameter list.
737 SmallVector<NamedDecl *, 4> CanonParams;
738 CanonParams.reserve(Params->size());
740 PEnd = Params->end();
741 P != PEnd; ++P) {
742 // Note that, per C++20 [temp.over.link]/6, when determining whether
743 // template-parameters are equivalent, constraints are ignored.
744 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
747 TTP->getDepth(), TTP->getIndex(), nullptr, false,
748 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
749 TTP->getNumExpansionParameters());
750 CanonParams.push_back(NewTTP);
751 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
755 if (NTTP->isExpandedParameterPack()) {
756 SmallVector<QualType, 2> ExpandedTypes;
758 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
759 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
760 ExpandedTInfos.push_back(
761 getTrivialTypeSourceInfo(ExpandedTypes.back()));
762 }
763
767 NTTP->getDepth(),
768 NTTP->getPosition(), nullptr,
769 T,
770 TInfo,
771 ExpandedTypes,
772 ExpandedTInfos);
773 } else {
777 NTTP->getDepth(),
778 NTTP->getPosition(), nullptr,
779 T,
780 NTTP->isParameterPack(),
781 TInfo);
782 }
783 CanonParams.push_back(Param);
784 } else
785 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
787 }
788
791 TTP->getPosition(), TTP->isParameterPack(), nullptr,
793 /*Typename=*/false,
795 CanonParams, SourceLocation(),
796 /*RequiresClause=*/nullptr));
797
798 // Get the new insert position for the node we care about.
799 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
800 assert(!Canonical && "Shouldn't be in the map!");
801 (void)Canonical;
802
803 // Create the canonical template template parameter entry.
804 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
805 CanonTemplateTemplateParms.insert(Canonical, Token);
806 return CanonTTP;
807}
808
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
814 llvm::FoldingSetInsertToken Token;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.lookup(ID, Token);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
825 llvm::FoldingSetInsertToken Token;
826 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
827 return Existing->getParam();
828 CanonTemplateTemplateParms.insert(
829 new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
830 return CanonTTP;
831}
832
833/// For the purposes of overflow pattern exclusion, does this match the
834/// while(i--) pattern?
835static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
836 if (UO->getOpcode() != UO_PostDec)
837 return false;
838
839 if (!UO->getType()->isUnsignedIntegerType())
840 return false;
841
842 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
845 return false;
846
847 // all Parents (usually just one) must be a WhileStmt
848 return llvm::all_of(
850 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
851}
852
854 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
855 // ... like -1UL;
856 if (UO->getOpcode() == UO_Minus &&
857 getLangOpts().isOverflowPatternExcluded(
859 UO->isIntegerConstantExpr(*this)) {
860 return true;
861 }
862
863 if (matchesPostDecrInWhile(UO, *this))
864 return true;
865
866 return false;
867}
868
869/// Check if a type can have its sanitizer instrumentation elided based on its
870/// presence within an ignorelist.
872 const QualType &Ty) const {
873 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
874 return NoSanitizeL->containsType(Mask, TyName);
875}
876
878 auto Kind = getTargetInfo().getCXXABI().getKind();
879 return getLangOpts().CXXABI.value_or(Kind);
880}
881
882CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
884
885 switch (getCXXABIKind()) {
886 case TargetCXXABI::AppleARM64:
887 case TargetCXXABI::Fuchsia:
888 case TargetCXXABI::GenericARM: // Same as Itanium at this level
889 case TargetCXXABI::iOS:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(*this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(*this);
899 }
900 llvm_unreachable("Invalid CXXABI type!");
901}
902
904 if (!InterpContext) {
905 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
906 }
907 return *InterpContext;
908}
909
911 if (!ParentMapCtx)
912 ParentMapCtx.reset(new ParentMapContext(*this));
913 return *ParentMapCtx;
914}
915
917 const LangOptions &LangOpts) {
918 switch (LangOpts.getAddressSpaceMapMangling()) {
920 return TI.useAddressSpaceMapMangling();
922 return true;
924 return false;
925 }
926 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
927}
928
930 IdentifierTable &idents, SelectorTable &sels,
932 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
933 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
934 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
935 DependentSizedMatrixTypes(this_()),
936 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
937 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
938 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
939 AttributedTypes(this_()), DependentBitIntTypes(this_()),
940 HLSLAttributedResourceTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
943 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
944 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
945 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
946 LangOpts.XRayNeverInstrumentFiles,
947 LangOpts.XRayAttrListFiles, SM)),
948 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
949 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
950 BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
951 Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
952 CompCategories(this_()), LastSDM(nullptr, 0) {
954}
955
957 // Release the DenseMaps associated with DeclContext objects.
958 // FIXME: Is this the ideal solution?
959 ReleaseDeclContextMaps();
960
961 // Call all of the deallocation functions on all of their targets.
962 for (auto &Pair : Deallocations)
963 (Pair.first)(Pair.second);
964 Deallocations.clear();
965
966 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
967 // because they can contain DenseMaps.
968 for (llvm::DenseMap<const ObjCInterfaceDecl *,
970 I = ObjCLayouts.begin(),
971 E = ObjCLayouts.end();
972 I != E;)
973 // Increment in loop to prevent using deallocated memory.
974 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
975 R->Destroy(*this);
976 ObjCLayouts.clear();
977
978 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
979 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
980 // Increment in loop to prevent using deallocated memory.
981 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
982 R->Destroy(*this);
983 }
984 ASTRecordLayouts.clear();
985
986 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
987 AEnd = DeclAttrs.end();
988 A != AEnd; ++A)
989 A->second->~AttrVec();
990 DeclAttrs.clear();
991
992 CtorClosureDefaultArgs.clear();
993
994 for (const auto &Value : ModuleInitializers)
995 Value.second->~PerModuleInitializers();
996 ModuleInitializers.clear();
997
998 TUDecl = nullptr;
999 XRayFilter.reset();
1000 NoSanitizeL.reset();
1001}
1002
1004
1005void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1006 TraversalScope = TopLevelDecls;
1008}
1009
1010void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1011 Deallocations.push_back({Callback, Data});
1012}
1013
1014void
1018
1020 llvm::errs() << "\n*** AST Context Stats:\n";
1021 llvm::errs() << " " << Types.size() << " types total.\n";
1022
1023 unsigned counts[] = {
1024#define TYPE(Name, Parent) 0,
1025#define ABSTRACT_TYPE(Name, Parent)
1026#include "clang/AST/TypeNodes.inc"
1027 0 // Extra
1028 };
1029
1030 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1031 Type *T = Types[i];
1032 counts[(unsigned)T->getTypeClass()]++;
1033 }
1034
1035 unsigned Idx = 0;
1036 unsigned TotalBytes = 0;
1037#define TYPE(Name, Parent) \
1038 if (counts[Idx]) \
1039 llvm::errs() << " " << counts[Idx] << " " << #Name \
1040 << " types, " << sizeof(Name##Type) << " each " \
1041 << "(" << counts[Idx] * sizeof(Name##Type) \
1042 << " bytes)\n"; \
1043 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1044 ++Idx;
1045#define ABSTRACT_TYPE(Name, Parent)
1046#include "clang/AST/TypeNodes.inc"
1047
1048 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1049
1050 // Implicit special member functions.
1051 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1053 << " implicit default constructors created\n";
1054 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1056 << " implicit copy constructors created\n";
1057 if (getLangOpts().CPlusPlus)
1058 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1060 << " implicit move constructors created\n";
1061 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1063 << " implicit copy assignment operators created\n";
1064 if (getLangOpts().CPlusPlus)
1065 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1067 << " implicit move assignment operators created\n";
1068 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1070 << " implicit destructors created\n";
1071
1072 if (ExternalSource) {
1073 llvm::errs() << "\n";
1074 ExternalSource->PrintStats();
1075 }
1076
1077 BumpAlloc.PrintStats();
1078}
1079
1081 bool NotifyListeners) {
1082 if (NotifyListeners)
1083 if (auto *Listener = getASTMutationListener();
1085 Listener->RedefinedHiddenDefinition(ND, M);
1086
1087 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1088}
1089
1091 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1092 if (It == MergedDefModules.end())
1093 return;
1094
1095 auto &Merged = It->second;
1096 llvm::DenseSet<Module*> Found;
1097 for (Module *&M : Merged)
1098 if (!Found.insert(M).second)
1099 M = nullptr;
1100 llvm::erase(Merged, nullptr);
1101}
1102
1105 auto MergedIt =
1106 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1107 if (MergedIt == MergedDefModules.end())
1108 return {};
1109 return MergedIt->second;
1110}
1111
1112void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1113 if (LazyInitializers.empty())
1114 return;
1115
1116 auto *Source = Ctx.getExternalSource();
1117 assert(Source && "lazy initializers but no external source");
1118
1119 auto LazyInits = std::move(LazyInitializers);
1120 LazyInitializers.clear();
1121
1122 for (auto ID : LazyInits)
1123 Initializers.push_back(Source->GetExternalDecl(ID));
1124
1125 assert(LazyInitializers.empty() &&
1126 "GetExternalDecl for lazy module initializer added more inits");
1127}
1128
1130 // One special case: if we add a module initializer that imports another
1131 // module, and that module's only initializer is an ImportDecl, simplify.
1132 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1133 auto It = ModuleInitializers.find(ID->getImportedModule());
1134
1135 // Maybe the ImportDecl does nothing at all. (Common case.)
1136 if (It == ModuleInitializers.end())
1137 return;
1138
1139 // Maybe the ImportDecl only imports another ImportDecl.
1140 auto &Imported = *It->second;
1141 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1142 Imported.resolve(*this);
1143 auto *OnlyDecl = Imported.Initializers.front();
1144 if (isa<ImportDecl>(OnlyDecl))
1145 D = OnlyDecl;
1146 }
1147 }
1148
1149 auto *&Inits = ModuleInitializers[M];
1150 if (!Inits)
1151 Inits = new (*this) PerModuleInitializers;
1152 Inits->Initializers.push_back(D);
1153}
1154
1157 auto *&Inits = ModuleInitializers[M];
1158 if (!Inits)
1159 Inits = new (*this) PerModuleInitializers;
1160 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1161 IDs.begin(), IDs.end());
1162}
1163
1165 auto It = ModuleInitializers.find(M);
1166 if (It == ModuleInitializers.end())
1167 return {};
1168
1169 auto *Inits = It->second;
1170 Inits->resolve(*this);
1171 return Inits->Initializers;
1172}
1173
1175 assert(M->isNamedModule());
1176 assert(!CurrentCXXNamedModule &&
1177 "We should set named module for ASTContext for only once");
1178 CurrentCXXNamedModule = M;
1179}
1180
1181bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1182 if (!M1 != !M2)
1183 return false;
1184
1185 /// Get the representative module for M. The representative module is the
1186 /// first module unit for a specific primary module name. So that the module
1187 /// units have the same representative module belongs to the same module.
1188 ///
1189 /// The process is helpful to reduce the expensive string operations.
1190 auto GetRepresentativeModule = [this](const Module *M) {
1191 auto Iter = SameModuleLookupSet.find(M);
1192 if (Iter != SameModuleLookupSet.end())
1193 return Iter->second;
1194
1195 const Module *RepresentativeModule =
1196 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1197 .first->second;
1198 SameModuleLookupSet[M] = RepresentativeModule;
1199 return RepresentativeModule;
1200 };
1201
1202 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1203 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1204}
1205
1207 if (!ExternCContext)
1208 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1209
1210 return ExternCContext;
1211}
1212
1223
1224#define BuiltinTemplate(BTName) \
1225 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1226 if (!Decl##BTName) \
1227 Decl##BTName = \
1228 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1229 return Decl##BTName; \
1230 }
1231#include "clang/Basic/BuiltinTemplates.inc"
1232
1234 RecordDecl::TagKind TK) const {
1235 SourceLocation Loc;
1236 RecordDecl *NewDecl;
1237 if (getLangOpts().CPlusPlus)
1238 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1239 Loc, &Idents.get(Name));
1240 else
1241 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1242 &Idents.get(Name));
1243 NewDecl->setImplicit();
1244 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1245 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1246 return NewDecl;
1247}
1248
1250 StringRef Name) const {
1253 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1254 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1255 NewDecl->setImplicit();
1256 return NewDecl;
1257}
1258
1260 if (!Int128Decl)
1261 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1262 return Int128Decl;
1263}
1264
1266 if (!UInt128Decl)
1267 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1268 return UInt128Decl;
1269}
1270
1271void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1272 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1274 Types.push_back(Ty);
1275}
1276
1278 const TargetInfo *AuxTarget) {
1279 assert((!this->Target || this->Target == &Target) &&
1280 "Incorrect target reinitialization");
1281 assert(VoidTy.isNull() && "Context reinitialized?");
1282
1283 this->Target = &Target;
1284 this->AuxTarget = AuxTarget;
1285
1286 ABI.reset(createCXXABI(Target));
1287 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1288
1289 // C99 6.2.5p19.
1290 InitBuiltinType(VoidTy, BuiltinType::Void);
1291
1292 // C99 6.2.5p2.
1293 InitBuiltinType(BoolTy, BuiltinType::Bool);
1294 // C99 6.2.5p3.
1295 if (LangOpts.CharIsSigned)
1296 InitBuiltinType(CharTy, BuiltinType::Char_S);
1297 else
1298 InitBuiltinType(CharTy, BuiltinType::Char_U);
1299 // C99 6.2.5p4.
1300 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1301 InitBuiltinType(ShortTy, BuiltinType::Short);
1302 InitBuiltinType(IntTy, BuiltinType::Int);
1303 InitBuiltinType(LongTy, BuiltinType::Long);
1304 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1305
1306 // C99 6.2.5p6.
1307 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1308 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1309 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1310 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1311 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1312
1313 // C99 6.2.5p10.
1314 InitBuiltinType(FloatTy, BuiltinType::Float);
1315 InitBuiltinType(DoubleTy, BuiltinType::Double);
1316 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1317
1318 // GNU extension, __float128 for IEEE quadruple precision
1319 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1320
1321 // __ibm128 for IBM extended precision
1322 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1323
1324 // C11 extension ISO/IEC TS 18661-3
1325 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1326
1327 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1328 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1329 InitBuiltinType(AccumTy, BuiltinType::Accum);
1330 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1331 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1332 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1333 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1334 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1335 InitBuiltinType(FractTy, BuiltinType::Fract);
1336 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1337 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1338 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1339 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1340 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1341 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1342 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1343 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1344 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1345 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1346 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1347 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1348 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1349 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1350 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1351 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1352
1353 // GNU extension, 128-bit integers.
1354 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1355 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1356
1357 // C++ 3.9.1p5
1358 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1359 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1360 else // -fshort-wchar makes wchar_t be unsigned.
1361 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1362 if (LangOpts.CPlusPlus && LangOpts.WChar)
1364 else {
1365 // C99 (or C++ using -fno-wchar).
1366 WideCharTy = getFromTargetType(Target.getWCharType());
1367 }
1368
1369 WIntTy = getFromTargetType(Target.getWIntType());
1370
1371 // C++20 (proposed)
1372 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1373
1374 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1375 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1376 else // C99
1377 Char16Ty = getFromTargetType(Target.getChar16Type());
1378
1379 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1380 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1381 else // C99
1382 Char32Ty = getFromTargetType(Target.getChar32Type());
1383
1384 // Placeholder type for type-dependent expressions whose type is
1385 // completely unknown. No code should ever check a type against
1386 // DependentTy and users should never see it; however, it is here to
1387 // help diagnose failures to properly check for type-dependent
1388 // expressions.
1389 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1390
1391 // Placeholder type for functions.
1392 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1393
1394 // Placeholder type for bound members.
1395 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1396
1397 // Placeholder type for unresolved templates.
1398 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1399
1400 // Placeholder type for pseudo-objects.
1401 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1402
1403 // "any" type; useful for debugger-like clients.
1404 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1405
1406 // Placeholder type for unbridged ARC casts.
1407 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1408
1409 // Placeholder type for builtin functions.
1410 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1411
1412 // Placeholder type for OMP array sections.
1413 if (LangOpts.OpenMP) {
1414 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1415 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1416 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1417 }
1418 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1419 // don't bother, as we're just using the same type as OMP.
1420 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1421 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1422 }
1423 if (LangOpts.MatrixTypes)
1424 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1425
1426 // Builtin types for 'id', 'Class', and 'SEL'.
1427 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1428 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1429 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1430
1431 if (LangOpts.OpenCL) {
1432#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1433 InitBuiltinType(SingletonId, BuiltinType::Id);
1434#include "clang/Basic/OpenCLImageTypes.def"
1435
1436 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1437 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1438 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1439 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1440 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1441
1442#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1443 InitBuiltinType(Id##Ty, BuiltinType::Id);
1444#include "clang/Basic/OpenCLExtensionTypes.def"
1445 }
1446
1447 if (LangOpts.HLSL) {
1448#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1449 InitBuiltinType(SingletonId, BuiltinType::Id);
1450#include "clang/Basic/HLSLIntangibleTypes.def"
1451 }
1452
1453 if (Target.hasAArch64ACLETypes() ||
1454 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1455#define SVE_TYPE(Name, Id, SingletonId) \
1456 InitBuiltinType(SingletonId, BuiltinType::Id);
1457#include "clang/Basic/AArch64ACLETypes.def"
1458 }
1459
1460 if (Target.getTriple().isPPC64()) {
1461#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1462 InitBuiltinType(Id##Ty, BuiltinType::Id);
1463#include "clang/Basic/PPCTypes.def"
1464#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1465 InitBuiltinType(Id##Ty, BuiltinType::Id);
1466#include "clang/Basic/PPCTypes.def"
1467 }
1468
1469 if (Target.hasRISCVVTypes()) {
1470#define RVV_TYPE(Name, Id, SingletonId) \
1471 InitBuiltinType(SingletonId, BuiltinType::Id);
1472#include "clang/Basic/RISCVVTypes.def"
1473 }
1474
1475 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1476#define WASM_TYPE(Name, Id, SingletonId) \
1477 InitBuiltinType(SingletonId, BuiltinType::Id);
1478#include "clang/Basic/WebAssemblyReferenceTypes.def"
1479 }
1480
1481 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1482#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1483 InitBuiltinType(SingletonId, BuiltinType::Id);
1484#include "clang/Basic/AMDGPUTypes.def"
1485 }
1486
1487 if (Target.getTriple().isSPIRV() ||
1488 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1489#define SPIRV_TYPE(Name, Id, SingletonId) \
1490 InitBuiltinType(SingletonId, BuiltinType::Id);
1491#include "clang/Basic/SPIRVTypes.def"
1492 }
1493
1494 // Builtin type for __objc_yes and __objc_no
1495 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1497
1498 ObjCConstantStringType = QualType();
1499
1500 ObjCSuperType = QualType();
1501
1502 // void * type
1503 if (LangOpts.OpenCLGenericAddressSpace) {
1504 auto Q = VoidTy.getQualifiers();
1505 Q.setAddressSpace(LangAS::opencl_generic);
1507 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1508 } else {
1510 }
1511
1512 // nullptr type (C++0x 2.14.7)
1513 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1514
1515 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1516 InitBuiltinType(HalfTy, BuiltinType::Half);
1517
1518 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1519
1520 // Builtin type used to help define __builtin_va_list.
1521 VaListTagDecl = nullptr;
1522
1523 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1524 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1527 }
1528}
1529
1531 return SourceMgr.getDiagnostics();
1532}
1533
1535 AttrVec *&Result = DeclAttrs[D];
1536 if (!Result) {
1537 void *Mem = Allocate(sizeof(AttrVec));
1538 Result = new (Mem) AttrVec;
1539 }
1540
1541 return *Result;
1542}
1543
1544/// Erase the attributes corresponding to the given declaration.
1546 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1547 if (Pos != DeclAttrs.end()) {
1548 Pos->second->~AttrVec();
1549 DeclAttrs.erase(Pos);
1550 }
1551}
1552
1555 return CtorClosureDefaultArgs.lookup(CD);
1556}
1557
1560 assert(!CtorClosureDefaultArgs.contains(CD));
1561 CtorClosureDefaultArgs[CD] = Args;
1562}
1563
1566 auto It =
1567 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1568 if (It != ExplicitInstantiations.end())
1569 return It->second;
1570 return {};
1571}
1572
1575 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1576 EID);
1577}
1578
1579// FIXME: Remove ?
1582 assert(Var->isStaticDataMember() && "Not a static data member");
1584 .dyn_cast<MemberSpecializationInfo *>();
1585}
1586
1589 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1590 TemplateOrInstantiation.find(Var);
1591 if (Pos == TemplateOrInstantiation.end())
1592 return {};
1593
1594 return Pos->second;
1595}
1596
1597void
1600 SourceLocation PointOfInstantiation) {
1601 assert(Inst->isStaticDataMember() && "Not a static data member");
1602 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1604 Tmpl, TSK, PointOfInstantiation));
1605}
1606
1607void
1610 assert(!TemplateOrInstantiation[Inst] &&
1611 "Already noted what the variable was instantiated from");
1612 TemplateOrInstantiation[Inst] = TSI;
1613}
1614
1615NamedDecl *
1617 return InstantiatedFromUsingDecl.lookup(UUD);
1618}
1619
1620void
1622 assert((isa<UsingDecl>(Pattern) ||
1625 "pattern decl is not a using decl");
1626 assert((isa<UsingDecl>(Inst) ||
1629 "instantiation did not produce a using decl");
1630 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1631 InstantiatedFromUsingDecl[Inst] = Pattern;
1632}
1633
1636 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1637}
1638
1640 UsingEnumDecl *Pattern) {
1641 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1642 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1643}
1644
1647 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1648}
1649
1650void
1652 UsingShadowDecl *Pattern) {
1653 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1654 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1655}
1656
1657FieldDecl *
1659 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1660}
1661
1663 FieldDecl *Tmpl) {
1664 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1665 "Instantiated field decl is not unnamed");
1666 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1667 "Template field decl is not unnamed");
1668 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1669 "Already noted what unnamed field was instantiated from");
1670
1671 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1672}
1673
1678
1683
1684unsigned
1686 auto Range = overridden_methods(Method);
1687 return Range.end() - Range.begin();
1688}
1689
1692 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1693 OverriddenMethods.find(Method->getCanonicalDecl());
1694 if (Pos == OverriddenMethods.end())
1695 return overridden_method_range(nullptr, nullptr);
1696 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1697}
1698
1700 const CXXMethodDecl *Overridden) {
1701 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1702 OverriddenMethods[Method].push_back(Overridden);
1703}
1704
1706 const NamedDecl *D,
1707 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1708 assert(D);
1709
1710 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1711 Overridden.append(overridden_methods_begin(CXXMethod),
1712 overridden_methods_end(CXXMethod));
1713 return;
1714 }
1715
1716 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1717 if (!Method)
1718 return;
1719
1721 Method->getOverriddenMethods(OverDecls);
1722 Overridden.append(OverDecls.begin(), OverDecls.end());
1723}
1724
1725std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1727 assert(RD);
1728 CXXRecordDecl *D = RD->getDefinition();
1729 auto it = RelocatableClasses.find(D);
1730 if (it != RelocatableClasses.end())
1731 return it->getSecond();
1732 return std::nullopt;
1733}
1734
1737 assert(RD);
1738 CXXRecordDecl *D = RD->getDefinition();
1739 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1740 RelocatableClasses.insert({D, Info});
1741}
1742
1744 const ASTContext &Context, const CXXRecordDecl *Class) {
1745 if (!Class->isPolymorphic())
1746 return false;
1747 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1748 using AuthAttr = VTablePointerAuthenticationAttr;
1749 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1750 if (!ExplicitAuth)
1751 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1752 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1753 ExplicitAuth->getAddressDiscrimination();
1754 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1755 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1756 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1757}
1758
1759ASTContext::PointerAuthContent
1760ASTContext::findPointerAuthContent(QualType T) const {
1761 assert(isPointerAuthenticationAvailable());
1762
1763 T = T.getCanonicalType();
1764 if (T->isDependentType())
1765 return PointerAuthContent::None;
1766
1767 if (T.hasAddressDiscriminatedPointerAuth())
1768 return PointerAuthContent::AddressDiscriminatedData;
1769 const RecordDecl *RD = T->getAsRecordDecl();
1770 if (!RD)
1771 return PointerAuthContent::None;
1772
1773 if (RD->isInvalidDecl())
1774 return PointerAuthContent::None;
1775
1776 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1777 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1778 return Existing->second;
1779
1780 PointerAuthContent Result = PointerAuthContent::None;
1781
1782 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1783 auto [ResultIter, DidAdd] =
1784 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1785 (void)ResultIter;
1786 (void)DidAdd;
1787 assert(DidAdd);
1788 return Result;
1789 };
1790 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1791 static_assert(PointerAuthContent::None <
1792 PointerAuthContent::AddressDiscriminatedVTable);
1793 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1794 PointerAuthContent::AddressDiscriminatedData);
1795 if (NewResult > Result)
1796 Result = NewResult;
1797 return Result != PointerAuthContent::AddressDiscriminatedData;
1798 };
1799 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1801 !ShouldContinueAfterUpdate(
1802 PointerAuthContent::AddressDiscriminatedVTable))
1803 return SaveResultAndReturn();
1804 for (auto Base : CXXRD->bases()) {
1805 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1806 return SaveResultAndReturn();
1807 }
1808 }
1809 for (auto *FieldDecl : RD->fields()) {
1810 if (!ShouldContinueAfterUpdate(
1811 findPointerAuthContent(FieldDecl->getType())))
1812 return SaveResultAndReturn();
1813 }
1814 return SaveResultAndReturn();
1815}
1816
1818 assert(!Import->getNextLocalImport() &&
1819 "Import declaration already in the chain");
1820 assert(!Import->isFromASTFile() && "Non-local import declaration");
1821 if (!FirstLocalImport) {
1822 FirstLocalImport = Import;
1823 LastLocalImport = Import;
1824 return;
1825 }
1826
1827 LastLocalImport->setNextLocalImport(Import);
1828 LastLocalImport = Import;
1829}
1830
1831//===----------------------------------------------------------------------===//
1832// Type Sizing and Analysis
1833//===----------------------------------------------------------------------===//
1834
1835/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1836/// scalar floating point type.
1837const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1838 switch (T->castAs<BuiltinType>()->getKind()) {
1839 default:
1840 llvm_unreachable("Not a floating point type!");
1841 case BuiltinType::BFloat16:
1842 return Target->getBFloat16Format();
1843 case BuiltinType::Float16:
1844 return Target->getHalfFormat();
1845 case BuiltinType::Half:
1846 return Target->getHalfFormat();
1847 case BuiltinType::Float: return Target->getFloatFormat();
1848 case BuiltinType::Double: return Target->getDoubleFormat();
1849 case BuiltinType::Ibm128:
1850 return Target->getIbm128Format();
1851 case BuiltinType::LongDouble:
1852 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1853 return AuxTarget->getLongDoubleFormat();
1854 return Target->getLongDoubleFormat();
1855 case BuiltinType::Float128:
1856 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1857 return AuxTarget->getFloat128Format();
1858 return Target->getFloat128Format();
1859 }
1860}
1861
1862CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1863 unsigned Align = Target->getCharWidth();
1864
1865 const unsigned AlignFromAttr = D->getMaxAlignment();
1866 if (AlignFromAttr)
1867 Align = AlignFromAttr;
1868
1869 // __attribute__((aligned)) can increase or decrease alignment
1870 // *except* on a struct or struct member, where it only increases
1871 // alignment unless 'packed' is also specified.
1872 //
1873 // It is an error for alignas to decrease alignment, so we can
1874 // ignore that possibility; Sema should diagnose it.
1875 bool UseAlignAttrOnly;
1876 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1877 UseAlignAttrOnly =
1878 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1879 else
1880 UseAlignAttrOnly = AlignFromAttr != 0;
1881 // If we're using the align attribute only, just ignore everything
1882 // else about the declaration and its type.
1883 if (UseAlignAttrOnly) {
1884 // do nothing
1885 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1886 QualType T = VD->getType();
1887 if (const auto *RT = T->getAs<ReferenceType>()) {
1888 if (ForAlignof)
1889 T = RT->getPointeeType();
1890 else
1891 T = getPointerType(RT->getPointeeType());
1892 }
1893 QualType BaseT = getBaseElementType(T);
1894 if (T->isFunctionType())
1895 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1896 else if (!BaseT->isIncompleteType()) {
1897 // Adjust alignments of declarations with array type by the
1898 // large-array alignment on the target.
1899 if (const ArrayType *arrayType = getAsArrayType(T)) {
1900 unsigned MinWidth = Target->getLargeArrayMinWidth();
1901 if (!ForAlignof && MinWidth) {
1903 Align = std::max(Align, Target->getLargeArrayAlign());
1906 Align = std::max(Align, Target->getLargeArrayAlign());
1907 }
1908 }
1909 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1910 if (BaseT.getQualifiers().hasUnaligned())
1911 Align = Target->getCharWidth();
1912 }
1913
1914 // Ensure minimum alignment for global variables.
1915 if (const auto *VD = dyn_cast<VarDecl>(D))
1916 if (VD->hasGlobalStorage() && !ForAlignof) {
1917 uint64_t TypeSize =
1918 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1919 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1920 }
1921
1922 // Fields can be subject to extra alignment constraints, like if
1923 // the field is packed, the struct is packed, or the struct has a
1924 // a max-field-alignment constraint (#pragma pack). So calculate
1925 // the actual alignment of the field within the struct, and then
1926 // (as we're expected to) constrain that by the alignment of the type.
1927 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1928 const RecordDecl *Parent = Field->getParent();
1929 // We can only produce a sensible answer if the record is valid.
1930 if (!Parent->isInvalidDecl()) {
1931 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1932
1933 // Start with the record's overall alignment.
1934 unsigned FieldAlign = toBits(Layout.getAlignment());
1935
1936 // Use the GCD of that and the offset within the record.
1937 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1938 if (Offset > 0) {
1939 // Alignment is always a power of 2, so the GCD will be a power of 2,
1940 // which means we get to do this crazy thing instead of Euclid's.
1941 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1942 if (LowBitOfOffset < FieldAlign)
1943 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1944 }
1945
1946 Align = std::min(Align, FieldAlign);
1947 }
1948 }
1949 }
1950
1951 // Some targets have hard limitation on the maximum requestable alignment in
1952 // aligned attribute for static variables.
1953 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1954 const auto *VD = dyn_cast<VarDecl>(D);
1955 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1956 Align = std::min(Align, MaxAlignedAttr);
1957
1958 return toCharUnitsFromBits(Align);
1959}
1960
1962 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1963}
1964
1965// getTypeInfoDataSizeInChars - Return the size of a type, in
1966// chars. If the type is a record, its data size is returned. This is
1967// the size of the memcpy that's performed when assigning this type
1968// using a trivial copy/move assignment operator.
1971
1972 // In C++, objects can sometimes be allocated into the tail padding
1973 // of a base-class subobject. We decide whether that's possible
1974 // during class layout, so here we can just trust the layout results.
1975 if (getLangOpts().CPlusPlus) {
1976 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1977 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1978 Info.Width = layout.getDataSize();
1979 }
1980 }
1981
1982 return Info;
1983}
1984
1985/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1986/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1989 const ConstantArrayType *CAT) {
1990 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1991 uint64_t Size = CAT->getZExtSize();
1992 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1993 (uint64_t)(-1)/Size) &&
1994 "Overflow in array type char size evaluation");
1995 uint64_t Width = EltInfo.Width.getQuantity() * Size;
1996 unsigned Align = EltInfo.Align.getQuantity();
1997 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1998 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
1999 Width = llvm::alignTo(Width, Align);
2002 EltInfo.AlignRequirement);
2003}
2004
2006 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2007 return getConstantArrayInfoInChars(*this, CAT);
2008 TypeInfo Info = getTypeInfo(T);
2011}
2012
2016
2018 // HLSL doesn't promote all small integer types to int, it
2019 // just uses the rank-based promotion rules for all types.
2020 if (getLangOpts().HLSL)
2021 return false;
2022
2023 if (const auto *BT = T->getAs<BuiltinType>())
2024 switch (BT->getKind()) {
2025 case BuiltinType::Bool:
2026 case BuiltinType::Char_S:
2027 case BuiltinType::Char_U:
2028 case BuiltinType::SChar:
2029 case BuiltinType::UChar:
2030 case BuiltinType::Short:
2031 case BuiltinType::UShort:
2032 case BuiltinType::WChar_S:
2033 case BuiltinType::WChar_U:
2034 case BuiltinType::Char8:
2035 case BuiltinType::Char16:
2036 case BuiltinType::Char32:
2037 return true;
2038 default:
2039 return false;
2040 }
2041
2042 // Enumerated types are promotable to their compatible integer types
2043 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2044 if (const auto *ED = T->getAsEnumDecl()) {
2045 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2046 ED->isScoped())
2047 return false;
2048
2049 return true;
2050 }
2051
2052 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2053 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2054 return isPromotableIntegerType(OBT->getUnderlyingType());
2055 }
2056
2057 return false;
2058}
2059
2063
2065 return isAlignmentRequired(T.getTypePtr());
2066}
2067
2069 bool NeedsPreferredAlignment) const {
2070 // An alignment on a typedef overrides anything else.
2071 if (const auto *TT = T->getAs<TypedefType>())
2072 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2073 return Align;
2074
2075 // If we have an (array of) complete type, we're done.
2077 if (!T->isIncompleteType())
2078 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2079
2080 // If we had an array type, its element type might be a typedef
2081 // type with an alignment attribute.
2082 if (const auto *TT = T->getAs<TypedefType>())
2083 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2084 return Align;
2085
2086 // Otherwise, see if the declaration of the type had an attribute.
2087 if (const auto *TD = T->getAsTagDecl())
2088 return TD->getMaxAlignment();
2089
2090 return 0;
2091}
2092
2094 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2095 if (I != MemoizedTypeInfo.end())
2096 return I->second;
2097
2098 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2099 TypeInfo TI = getTypeInfoImpl(T);
2100 MemoizedTypeInfo[T] = TI;
2101 return TI;
2102}
2103
2104/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2105/// method does not work on incomplete types.
2106///
2107/// FIXME: Pointers into different addr spaces could have different sizes and
2108/// alignment requirements: getPointerInfo should take an AddrSpace, this
2109/// should take a QualType, &c.
2110TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2111 uint64_t Width = 0;
2112 unsigned Align = 8;
2115 switch (T->getTypeClass()) {
2116#define TYPE(Class, Base)
2117#define ABSTRACT_TYPE(Class, Base)
2118#define NON_CANONICAL_TYPE(Class, Base)
2119#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2120#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2121 case Type::Class: \
2122 assert(!T->isDependentType() && "should not see dependent types here"); \
2123 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2124#include "clang/AST/TypeNodes.inc"
2125 llvm_unreachable("Should not see dependent types");
2126
2127 case Type::FunctionNoProto:
2128 case Type::FunctionProto:
2129 // GCC extension: alignof(function) = 32 bits
2130 Width = 0;
2131 Align = 32;
2132 break;
2133
2134 case Type::IncompleteArray:
2135 case Type::VariableArray:
2136 case Type::ConstantArray:
2137 case Type::ArrayParameter: {
2138 // Model non-constant sized arrays as size zero, but track the alignment.
2139 uint64_t Size = 0;
2140 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2141 Size = CAT->getZExtSize();
2142
2143 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2144 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2145 "Overflow in array type bit size evaluation");
2146 Width = EltInfo.Width * Size;
2147 Align = EltInfo.Align;
2148 AlignRequirement = EltInfo.AlignRequirement;
2149 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2150 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2151 Width = llvm::alignTo(Width, Align);
2152 break;
2153 }
2154
2155 case Type::ExtVector:
2156 case Type::Vector: {
2157 const auto *VT = cast<VectorType>(T);
2158 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2159 Width = VT->isPackedVectorBoolType(*this)
2160 ? VT->getNumElements()
2161 : EltInfo.Width * VT->getNumElements();
2162 // Enforce at least byte size and alignment.
2163 Width = std::max<unsigned>(8, Width);
2164 Align = std::max<unsigned>(
2165 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2166
2167 // If the alignment is not a power of 2, round up to the next power of 2.
2168 // This happens for non-power-of-2 length vectors.
2169 if (Align & (Align-1)) {
2170 Align = llvm::bit_ceil(Align);
2171 Width = llvm::alignTo(Width, Align);
2172 }
2173 // Adjust the alignment based on the target max.
2174 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2175 if (TargetVectorAlign && TargetVectorAlign < Align)
2176 Align = TargetVectorAlign;
2177 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2178 // Adjust the alignment for fixed-length SVE vectors. This is important
2179 // for non-power-of-2 vector lengths.
2180 Align = 128;
2181 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2182 // Adjust the alignment for fixed-length SVE predicates.
2183 Align = 16;
2184 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2185 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2186 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2187 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2188 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2189 // Adjust the alignment for fixed-length RVV vectors.
2190 Align = std::min<unsigned>(64, Width);
2191 break;
2192 }
2193
2194 case Type::ConstantMatrix: {
2195 const auto *MT = cast<ConstantMatrixType>(T);
2196 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2197 // The internal layout of a matrix value is implementation defined.
2198 // Initially be ABI compatible with arrays with respect to alignment and
2199 // size.
2200 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2201 Align = ElementInfo.Align;
2202 break;
2203 }
2204
2205 case Type::Builtin:
2206 switch (cast<BuiltinType>(T)->getKind()) {
2207 default: llvm_unreachable("Unknown builtin type!");
2208 case BuiltinType::Void:
2209 // GCC extension: alignof(void) = 8 bits.
2210 Width = 0;
2211 Align = 8;
2212 break;
2213 case BuiltinType::Bool:
2214 Width = Target->getBoolWidth();
2215 Align = Target->getBoolAlign();
2216 break;
2217 case BuiltinType::Char_S:
2218 case BuiltinType::Char_U:
2219 case BuiltinType::UChar:
2220 case BuiltinType::SChar:
2221 case BuiltinType::Char8:
2222 Width = Target->getCharWidth();
2223 Align = Target->getCharAlign();
2224 break;
2225 case BuiltinType::WChar_S:
2226 case BuiltinType::WChar_U:
2227 Width = Target->getWCharWidth();
2228 Align = Target->getWCharAlign();
2229 break;
2230 case BuiltinType::Char16:
2231 Width = Target->getChar16Width();
2232 Align = Target->getChar16Align();
2233 break;
2234 case BuiltinType::Char32:
2235 Width = Target->getChar32Width();
2236 Align = Target->getChar32Align();
2237 break;
2238 case BuiltinType::UShort:
2239 case BuiltinType::Short:
2240 Width = Target->getShortWidth();
2241 Align = Target->getShortAlign();
2242 break;
2243 case BuiltinType::UInt:
2244 case BuiltinType::Int:
2245 Width = Target->getIntWidth();
2246 Align = Target->getIntAlign();
2247 break;
2248 case BuiltinType::ULong:
2249 case BuiltinType::Long:
2250 Width = Target->getLongWidth();
2251 Align = Target->getLongAlign();
2252 break;
2253 case BuiltinType::ULongLong:
2254 case BuiltinType::LongLong:
2255 Width = Target->getLongLongWidth();
2256 Align = Target->getLongLongAlign();
2257 break;
2258 case BuiltinType::Int128:
2259 case BuiltinType::UInt128:
2260 Width = 128;
2261 Align = Target->getInt128Align();
2262 break;
2263 case BuiltinType::ShortAccum:
2264 case BuiltinType::UShortAccum:
2265 case BuiltinType::SatShortAccum:
2266 case BuiltinType::SatUShortAccum:
2267 Width = Target->getShortAccumWidth();
2268 Align = Target->getShortAccumAlign();
2269 break;
2270 case BuiltinType::Accum:
2271 case BuiltinType::UAccum:
2272 case BuiltinType::SatAccum:
2273 case BuiltinType::SatUAccum:
2274 Width = Target->getAccumWidth();
2275 Align = Target->getAccumAlign();
2276 break;
2277 case BuiltinType::LongAccum:
2278 case BuiltinType::ULongAccum:
2279 case BuiltinType::SatLongAccum:
2280 case BuiltinType::SatULongAccum:
2281 Width = Target->getLongAccumWidth();
2282 Align = Target->getLongAccumAlign();
2283 break;
2284 case BuiltinType::ShortFract:
2285 case BuiltinType::UShortFract:
2286 case BuiltinType::SatShortFract:
2287 case BuiltinType::SatUShortFract:
2288 Width = Target->getShortFractWidth();
2289 Align = Target->getShortFractAlign();
2290 break;
2291 case BuiltinType::Fract:
2292 case BuiltinType::UFract:
2293 case BuiltinType::SatFract:
2294 case BuiltinType::SatUFract:
2295 Width = Target->getFractWidth();
2296 Align = Target->getFractAlign();
2297 break;
2298 case BuiltinType::LongFract:
2299 case BuiltinType::ULongFract:
2300 case BuiltinType::SatLongFract:
2301 case BuiltinType::SatULongFract:
2302 Width = Target->getLongFractWidth();
2303 Align = Target->getLongFractAlign();
2304 break;
2305 case BuiltinType::BFloat16:
2306 if (Target->hasBFloat16Type()) {
2307 Width = Target->getBFloat16Width();
2308 Align = Target->getBFloat16Align();
2309 } else if ((getLangOpts().SYCLIsDevice ||
2310 (getLangOpts().OpenMP &&
2311 getLangOpts().OpenMPIsTargetDevice)) &&
2312 AuxTarget->hasBFloat16Type()) {
2313 Width = AuxTarget->getBFloat16Width();
2314 Align = AuxTarget->getBFloat16Align();
2315 }
2316 break;
2317 case BuiltinType::Float16:
2318 case BuiltinType::Half:
2319 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2320 !getLangOpts().OpenMPIsTargetDevice) {
2321 Width = Target->getHalfWidth();
2322 Align = Target->getHalfAlign();
2323 } else {
2324 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2325 "Expected OpenMP device compilation.");
2326 Width = AuxTarget->getHalfWidth();
2327 Align = AuxTarget->getHalfAlign();
2328 }
2329 break;
2330 case BuiltinType::Float:
2331 Width = Target->getFloatWidth();
2332 Align = Target->getFloatAlign();
2333 break;
2334 case BuiltinType::Double:
2335 Width = Target->getDoubleWidth();
2336 Align = Target->getDoubleAlign();
2337 break;
2338 case BuiltinType::Ibm128:
2339 Width = Target->getIbm128Width();
2340 Align = Target->getIbm128Align();
2341 break;
2342 case BuiltinType::LongDouble:
2343 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2344 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2345 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2346 Width = AuxTarget->getLongDoubleWidth();
2347 Align = AuxTarget->getLongDoubleAlign();
2348 } else {
2349 Width = Target->getLongDoubleWidth();
2350 Align = Target->getLongDoubleAlign();
2351 }
2352 break;
2353 case BuiltinType::Float128:
2354 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2355 !getLangOpts().OpenMPIsTargetDevice) {
2356 Width = Target->getFloat128Width();
2357 Align = Target->getFloat128Align();
2358 } else {
2359 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2360 "Expected OpenMP device compilation.");
2361 Width = AuxTarget->getFloat128Width();
2362 Align = AuxTarget->getFloat128Align();
2363 }
2364 break;
2365 case BuiltinType::NullPtr:
2366 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2367 Width = Target->getPointerWidth(LangAS::Default);
2368 Align = Target->getPointerAlign(LangAS::Default);
2369 break;
2370 case BuiltinType::ObjCId:
2371 case BuiltinType::ObjCClass:
2372 case BuiltinType::ObjCSel:
2373 Width = Target->getPointerWidth(LangAS::Default);
2374 Align = Target->getPointerAlign(LangAS::Default);
2375 break;
2376 case BuiltinType::OCLSampler:
2377 case BuiltinType::OCLEvent:
2378 case BuiltinType::OCLClkEvent:
2379 case BuiltinType::OCLQueue:
2380 case BuiltinType::OCLReserveID:
2381#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2382 case BuiltinType::Id:
2383#include "clang/Basic/OpenCLImageTypes.def"
2384#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2385 case BuiltinType::Id:
2386#include "clang/Basic/OpenCLExtensionTypes.def"
2387 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2388 Width = Target->getPointerWidth(AS);
2389 Align = Target->getPointerAlign(AS);
2390 break;
2391 // The SVE types are effectively target-specific. The length of an
2392 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2393 // of 128 bits. There is one predicate bit for each vector byte, so the
2394 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2395 //
2396 // Because the length is only known at runtime, we use a dummy value
2397 // of 0 for the static length. The alignment values are those defined
2398 // by the Procedure Call Standard for the Arm Architecture.
2399#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2400 case BuiltinType::Id: \
2401 Width = 0; \
2402 Align = 128; \
2403 break;
2404#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2405 case BuiltinType::Id: \
2406 Width = 0; \
2407 Align = 16; \
2408 break;
2409#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2410 case BuiltinType::Id: \
2411 Width = 0; \
2412 Align = 16; \
2413 break;
2414#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2415 case BuiltinType::Id: \
2416 Width = Bits; \
2417 Align = Bits; \
2418 break;
2419#include "clang/Basic/AArch64ACLETypes.def"
2420#define PPC_VECTOR_TYPE(Name, Id, Size) \
2421 case BuiltinType::Id: \
2422 Width = Size; \
2423 Align = Size; \
2424 break;
2425#include "clang/Basic/PPCTypes.def"
2426#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2427 IsFP, IsBF) \
2428 case BuiltinType::Id: \
2429 Width = 0; \
2430 Align = ElBits; \
2431 break;
2432#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2433 case BuiltinType::Id: \
2434 Width = 0; \
2435 Align = 8; \
2436 break;
2437#include "clang/Basic/RISCVVTypes.def"
2438#define WASM_TYPE(Name, Id, SingletonId) \
2439 case BuiltinType::Id: \
2440 Width = 0; \
2441 Align = 8; \
2442 break;
2443#include "clang/Basic/WebAssemblyReferenceTypes.def"
2444#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2445 case BuiltinType::ID: \
2446 Width = WIDTH; \
2447 Align = ALIGN; \
2448 break;
2449#include "clang/Basic/AMDGPUTypes.def"
2450#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2451#include "clang/Basic/HLSLIntangibleTypes.def"
2452 Width = Target->getPointerWidth(LangAS::Default);
2453 Align = Target->getPointerAlign(LangAS::Default);
2454 break;
2455#define SPIRV_TYPE(Name, Id, SingletonId) \
2456 case BuiltinType::Id: \
2457 Width = Target->getPointerWidth(LangAS::Default); \
2458 Align = Target->getPointerAlign(LangAS::Default); \
2459 break;
2460#include "clang/Basic/SPIRVTypes.def"
2461 }
2462 break;
2463 case Type::ObjCObjectPointer:
2464 Width = Target->getPointerWidth(LangAS::Default);
2465 Align = Target->getPointerAlign(LangAS::Default);
2466 break;
2467 case Type::BlockPointer:
2468 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2469 Width = Target->getPointerWidth(AS);
2470 Align = Target->getPointerAlign(AS);
2471 break;
2472 case Type::LValueReference:
2473 case Type::RValueReference:
2474 // alignof and sizeof should never enter this code path here, so we go
2475 // the pointer route.
2476 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2477 Width = Target->getPointerWidth(AS);
2478 Align = Target->getPointerAlign(AS);
2479 break;
2480 case Type::Pointer:
2481 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2482 Width = Target->getPointerWidth(AS);
2483 Align = Target->getPointerAlign(AS);
2484 break;
2485 case Type::MemberPointer: {
2486 const auto *MPT = cast<MemberPointerType>(T);
2487 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2488 Width = MPI.Width;
2489 Align = MPI.Align;
2490 break;
2491 }
2492 case Type::Complex: {
2493 // Complex types have the same alignment as their elements, but twice the
2494 // size.
2495 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2496 Width = EltInfo.Width * 2;
2497 Align = EltInfo.Align;
2498 break;
2499 }
2500 case Type::ObjCObject:
2501 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2502 case Type::Adjusted:
2503 case Type::Decayed:
2504 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2505 case Type::ObjCInterface: {
2506 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2507 if (ObjCI->getDecl()->isInvalidDecl()) {
2508 Width = 8;
2509 Align = 8;
2510 break;
2511 }
2512 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2513 Width = toBits(Layout.getSize());
2514 Align = toBits(Layout.getAlignment());
2515 break;
2516 }
2517 case Type::BitInt: {
2518 const auto *EIT = cast<BitIntType>(T);
2519 Align = Target->getBitIntAlign(EIT->getNumBits());
2520 Width = Target->getBitIntWidth(EIT->getNumBits());
2521 break;
2522 }
2523 case Type::Record:
2524 case Type::Enum: {
2525 const auto *TT = cast<TagType>(T);
2526 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2527
2528 if (TD->isInvalidDecl()) {
2529 Width = 8;
2530 Align = 8;
2531 break;
2532 }
2533
2534 if (isa<EnumType>(TT)) {
2535 const EnumDecl *ED = cast<EnumDecl>(TD);
2536 TypeInfo Info =
2538 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2539 Info.Align = AttrAlign;
2541 }
2542 return Info;
2543 }
2544
2545 const auto *RD = cast<RecordDecl>(TD);
2546 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2547 Width = toBits(Layout.getSize());
2548 Align = toBits(Layout.getAlignment());
2549 AlignRequirement = RD->hasAttr<AlignedAttr>()
2551 : AlignRequirementKind::None;
2552 break;
2553 }
2554
2555 case Type::SubstTemplateTypeParm:
2557 getReplacementType().getTypePtr());
2558
2559 case Type::Auto:
2560 case Type::DeducedTemplateSpecialization: {
2561 const auto *A = cast<DeducedType>(T);
2562 assert(!A->getDeducedType().isNull() &&
2563 "cannot request the size of an undeduced or dependent auto type");
2564 return getTypeInfo(A->getDeducedType().getTypePtr());
2565 }
2566
2567 case Type::Paren:
2568 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2569
2570 case Type::MacroQualified:
2571 return getTypeInfo(
2573
2574 case Type::ObjCTypeParam:
2575 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2576
2577 case Type::Using:
2578 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2579
2580 case Type::Typedef: {
2581 const auto *TT = cast<TypedefType>(T);
2582 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2583 // If the typedef has an aligned attribute on it, it overrides any computed
2584 // alignment we have. This violates the GCC documentation (which says that
2585 // attribute(aligned) can only round up) but matches its implementation.
2586 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2587 Align = AttrAlign;
2588 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2589 } else {
2590 Align = Info.Align;
2591 AlignRequirement = Info.AlignRequirement;
2592 }
2593 Width = Info.Width;
2594 break;
2595 }
2596
2597 case Type::Attributed:
2598 return getTypeInfo(
2599 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2600
2601 case Type::CountAttributed:
2602 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2603
2604 case Type::LateParsedAttr:
2605 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2606
2607 case Type::BTFTagAttributed:
2608 return getTypeInfo(
2609 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2610
2611 case Type::OverflowBehavior:
2612 return getTypeInfo(
2614
2615 case Type::HLSLAttributedResource:
2616 return getTypeInfo(
2617 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2618
2619 case Type::HLSLInlineSpirv: {
2620 const auto *ST = cast<HLSLInlineSpirvType>(T);
2621 // Size is specified in bytes, convert to bits
2622 Width = ST->getSize() * 8;
2623 Align = ST->getAlignment();
2624 if (Width == 0 && Align == 0) {
2625 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2626 Width = 32;
2627 Align = 32;
2628 }
2629 break;
2630 }
2631
2632 case Type::Atomic: {
2633 // Start with the base type information.
2634 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2635 Width = Info.Width;
2636 Align = Info.Align;
2637
2638 if (!Width) {
2639 // An otherwise zero-sized type should still generate an
2640 // atomic operation.
2641 Width = Target->getCharWidth();
2642 assert(Align);
2643 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2644 // If the size of the type doesn't exceed the platform's max
2645 // atomic promotion width, make the size and alignment more
2646 // favorable to atomic operations:
2647
2648 // Round the size up to a power of 2.
2649 Width = llvm::bit_ceil(Width);
2650
2651 // Set the alignment equal to the size.
2652 Align = static_cast<unsigned>(Width);
2653 }
2654 }
2655 break;
2656
2657 case Type::PredefinedSugar:
2658 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2659
2660 case Type::Pipe:
2661 Width = Target->getPointerWidth(LangAS::opencl_global);
2662 Align = Target->getPointerAlign(LangAS::opencl_global);
2663 break;
2664 }
2665
2666 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2667 return TypeInfo(Width, Align, AlignRequirement);
2668}
2669
2671 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2672 if (I != MemoizedUnadjustedAlign.end())
2673 return I->second;
2674
2675 unsigned UnadjustedAlign;
2676 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2677 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2678 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2679 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2680 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2681 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2682 } else {
2683 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2684 }
2685
2686 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2687 return UnadjustedAlign;
2688}
2689
2691 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2692 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2693 return SimdAlign;
2694}
2695
2696/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2698 return CharUnits::fromQuantity(BitSize / getCharWidth());
2699}
2700
2701/// toBits - Convert a size in characters to a size in characters.
2702int64_t ASTContext::toBits(CharUnits CharSize) const {
2703 return CharSize.getQuantity() * getCharWidth();
2704}
2705
2706/// getTypeSizeInChars - Return the size of the specified type, in characters.
2707/// This method does not work on incomplete types.
2714
2715/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2716/// characters. This method does not work on incomplete types.
2723
2724/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2725/// type, in characters, before alignment adjustments. This method does
2726/// not work on incomplete types.
2733
2734/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2735/// type for the current target in bits. This can be different than the ABI
2736/// alignment in cases where it is beneficial for performance or backwards
2737/// compatibility preserving to overalign a data type. (Note: despite the name,
2738/// the preferred alignment is ABI-impacting, and not an optimization.)
2740 TypeInfo TI = getTypeInfo(T);
2741 unsigned ABIAlign = TI.Align;
2742
2743 T = T->getBaseElementTypeUnsafe();
2744
2745 // The preferred alignment of member pointers is that of a pointer.
2746 if (T->isMemberPointerType())
2747 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2748
2749 if (!Target->allowsLargerPreferedTypeAlignment())
2750 return ABIAlign;
2751
2752 if (const auto *RD = T->getAsRecordDecl()) {
2753 // When used as part of a typedef, or together with a 'packed' attribute,
2754 // the 'aligned' attribute can be used to decrease alignment. Note that the
2755 // 'packed' case is already taken into consideration when computing the
2756 // alignment, we only need to handle the typedef case here.
2758 RD->isInvalidDecl())
2759 return ABIAlign;
2760
2761 unsigned PreferredAlign = static_cast<unsigned>(
2762 toBits(getASTRecordLayout(RD).PreferredAlignment));
2763 assert(PreferredAlign >= ABIAlign &&
2764 "PreferredAlign should be at least as large as ABIAlign.");
2765 return PreferredAlign;
2766 }
2767
2768 // Double (and, for targets supporting AIX `power` alignment, long double) and
2769 // long long should be naturally aligned (despite requiring less alignment) if
2770 // possible.
2771 if (const auto *CT = T->getAs<ComplexType>())
2772 T = CT->getElementType().getTypePtr();
2773 if (const auto *ED = T->getAsEnumDecl())
2774 T = ED->getIntegerType().getTypePtr();
2775 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2776 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2777 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2778 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2779 Target->defaultsToAIXPowerAlignment()))
2780 // Don't increase the alignment if an alignment attribute was specified on a
2781 // typedef declaration.
2782 if (!TI.isAlignRequired())
2783 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2784
2785 return ABIAlign;
2786}
2787
2788/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2789/// for __attribute__((aligned)) on this target, to be used if no alignment
2790/// value is specified.
2794
2795/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2796/// to a global variable of the specified type.
2798 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2799 return std::max(getPreferredTypeAlign(T),
2800 getMinGlobalAlignOfVar(TypeSize, VD));
2801}
2802
2803/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2804/// should be given to a global variable of the specified type.
2809
2811 const VarDecl *VD) const {
2812 // Make the default handling as that of a non-weak definition in the
2813 // current translation unit.
2814 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2815 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2816}
2817
2819 CharUnits Offset = CharUnits::Zero();
2820 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2821 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2822 Offset += Layout->getBaseClassOffset(Base);
2823 Layout = &getASTRecordLayout(Base);
2824 }
2825 return Offset;
2826}
2827
2829 const ValueDecl *MPD = MP.getMemberPointerDecl();
2832 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2834 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2835 const CXXRecordDecl *Base = RD;
2836 const CXXRecordDecl *Derived = Path[I];
2837 if (DerivedMember)
2838 std::swap(Base, Derived);
2840 RD = Path[I];
2841 }
2842 if (DerivedMember)
2844 return ThisAdjustment;
2845}
2846
2847/// DeepCollectObjCIvars -
2848/// This routine first collects all declared, but not synthesized, ivars in
2849/// super class and then collects all ivars, including those synthesized for
2850/// current class. This routine is used for implementation of current class
2851/// when all ivars, declared and synthesized are known.
2853 bool leafClass,
2855 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2856 DeepCollectObjCIvars(SuperClass, false, Ivars);
2857 if (!leafClass) {
2858 llvm::append_range(Ivars, OI->ivars());
2859 } else {
2860 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2861 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2862 Iv= Iv->getNextIvar())
2863 Ivars.push_back(Iv);
2864 }
2865}
2866
2867/// CollectInheritedProtocols - Collect all protocols in current class and
2868/// those inherited by it.
2871 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2872 // We can use protocol_iterator here instead of
2873 // all_referenced_protocol_iterator since we are walking all categories.
2874 for (auto *Proto : OI->all_referenced_protocols()) {
2875 CollectInheritedProtocols(Proto, Protocols);
2876 }
2877
2878 // Categories of this Interface.
2879 for (const auto *Cat : OI->visible_categories())
2880 CollectInheritedProtocols(Cat, Protocols);
2881
2882 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2883 while (SD) {
2884 CollectInheritedProtocols(SD, Protocols);
2885 SD = SD->getSuperClass();
2886 }
2887 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2888 for (auto *Proto : OC->protocols()) {
2889 CollectInheritedProtocols(Proto, Protocols);
2890 }
2891 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2892 // Insert the protocol.
2893 if (!Protocols.insert(
2894 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2895 return;
2896
2897 for (auto *Proto : OP->protocols())
2898 CollectInheritedProtocols(Proto, Protocols);
2899 }
2900}
2901
2903 const RecordDecl *RD,
2904 bool CheckIfTriviallyCopyable) {
2905 assert(RD->isUnion() && "Must be union type");
2906 CharUnits UnionSize =
2907 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2908
2909 for (const auto *Field : RD->fields()) {
2910 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2911 CheckIfTriviallyCopyable))
2912 return false;
2913 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2914 if (FieldSize != UnionSize)
2915 return false;
2916 }
2917 return !RD->field_empty();
2918}
2919
2920static int64_t getSubobjectOffset(const FieldDecl *Field,
2921 const ASTContext &Context,
2922 const clang::ASTRecordLayout & /*Layout*/) {
2923 return Context.getFieldOffset(Field);
2924}
2925
2926static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2927 const ASTContext &Context,
2928 const clang::ASTRecordLayout &Layout) {
2929 return Context.toBits(Layout.getBaseClassOffset(RD));
2930}
2931
2932static std::optional<int64_t>
2934 const RecordDecl *RD,
2935 bool CheckIfTriviallyCopyable);
2936
2937static std::optional<int64_t>
2938getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2939 bool CheckIfTriviallyCopyable) {
2940 if (const auto *RD = Field->getType()->getAsRecordDecl();
2941 RD && !RD->isUnion())
2942 return structHasUniqueObjectRepresentations(Context, RD,
2943 CheckIfTriviallyCopyable);
2944
2945 // A _BitInt type may not be unique if it has padding bits
2946 // but if it is a bitfield the padding bits are not used.
2947 bool IsBitIntType = Field->getType()->isBitIntType();
2948 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2949 !Context.hasUniqueObjectRepresentations(Field->getType(),
2950 CheckIfTriviallyCopyable))
2951 return std::nullopt;
2952
2953 int64_t FieldSizeInBits =
2954 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2955 if (Field->isBitField()) {
2956 // If we have explicit padding bits, they don't contribute bits
2957 // to the actual object representation, so return 0.
2958 if (Field->isUnnamedBitField())
2959 return 0;
2960
2961 int64_t BitfieldSize = Field->getBitWidthValue();
2962 if (IsBitIntType) {
2963 if ((unsigned)BitfieldSize >
2964 cast<BitIntType>(Field->getType())->getNumBits())
2965 return std::nullopt;
2966 } else if (BitfieldSize > FieldSizeInBits) {
2967 return std::nullopt;
2968 }
2969 FieldSizeInBits = BitfieldSize;
2970 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2971 Field->getType(), CheckIfTriviallyCopyable)) {
2972 return std::nullopt;
2973 }
2974 return FieldSizeInBits;
2975}
2976
2977static std::optional<int64_t>
2979 bool CheckIfTriviallyCopyable) {
2980 return structHasUniqueObjectRepresentations(Context, RD,
2981 CheckIfTriviallyCopyable);
2982}
2983
2984template <typename RangeT>
2986 const RangeT &Subobjects, int64_t CurOffsetInBits,
2987 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
2988 bool CheckIfTriviallyCopyable) {
2989 for (const auto *Subobject : Subobjects) {
2990 std::optional<int64_t> SizeInBits =
2991 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
2992 if (!SizeInBits)
2993 return std::nullopt;
2994 if (*SizeInBits != 0) {
2995 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
2996 if (Offset != CurOffsetInBits)
2997 return std::nullopt;
2998 CurOffsetInBits += *SizeInBits;
2999 }
3000 }
3001 return CurOffsetInBits;
3002}
3003
3004static std::optional<int64_t>
3006 const RecordDecl *RD,
3007 bool CheckIfTriviallyCopyable) {
3008 assert(!RD->isUnion() && "Must be struct/class type");
3009 const auto &Layout = Context.getASTRecordLayout(RD);
3010
3011 int64_t CurOffsetInBits = 0;
3012 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3013 if (ClassDecl->isDynamicClass())
3014 return std::nullopt;
3015
3017 for (const auto &Base : ClassDecl->bases()) {
3018 // Empty types can be inherited from, and non-empty types can potentially
3019 // have tail padding, so just make sure there isn't an error.
3020 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3021 }
3022
3023 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3024 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3025 });
3026
3027 std::optional<int64_t> OffsetAfterBases =
3029 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3030 if (!OffsetAfterBases)
3031 return std::nullopt;
3032 CurOffsetInBits = *OffsetAfterBases;
3033 }
3034
3035 std::optional<int64_t> OffsetAfterFields =
3037 RD->fields(), CurOffsetInBits, Context, Layout,
3038 CheckIfTriviallyCopyable);
3039 if (!OffsetAfterFields)
3040 return std::nullopt;
3041 CurOffsetInBits = *OffsetAfterFields;
3042
3043 return CurOffsetInBits;
3044}
3045
3047 QualType Ty, bool CheckIfTriviallyCopyable) const {
3048 // C++17 [meta.unary.prop]:
3049 // The predicate condition for a template specialization
3050 // has_unique_object_representations<T> shall be satisfied if and only if:
3051 // (9.1) - T is trivially copyable, and
3052 // (9.2) - any two objects of type T with the same value have the same
3053 // object representation, where:
3054 // - two objects of array or non-union class type are considered to have
3055 // the same value if their respective sequences of direct subobjects
3056 // have the same values, and
3057 // - two objects of union type are considered to have the same value if
3058 // they have the same active member and the corresponding members have
3059 // the same value.
3060 // The set of scalar types for which this condition holds is
3061 // implementation-defined. [ Note: If a type has padding bits, the condition
3062 // does not hold; otherwise, the condition holds true for unsigned integral
3063 // types. -- end note ]
3064 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3065
3066 // Arrays are unique only if their element type is unique.
3067 if (Ty->isArrayType())
3069 CheckIfTriviallyCopyable);
3070
3071 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3072 "hasUniqueObjectRepresentations should not be called with an "
3073 "incomplete type");
3074
3075 // (9.1) - T is trivially copyable...
3076 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3077 return false;
3078
3079 // All integrals and enums are unique.
3080 if (Ty->isIntegralOrEnumerationType()) {
3081 // Address discriminated integer types are not unique.
3083 return false;
3084 // Except _BitInt types that have padding bits.
3085 if (const auto *BIT = Ty->getAs<BitIntType>())
3086 return getTypeSize(BIT) == BIT->getNumBits();
3087
3088 return true;
3089 }
3090
3091 // All other pointers are unique.
3092 if (Ty->isPointerType())
3094
3095 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3096 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3097
3098 if (const auto *Record = Ty->getAsRecordDecl()) {
3099 if (Record->isInvalidDecl())
3100 return false;
3101
3102 if (Record->isUnion())
3104 CheckIfTriviallyCopyable);
3105
3106 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3107 *this, Record, CheckIfTriviallyCopyable);
3108
3109 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3110 }
3111
3112 // FIXME: More cases to handle here (list by rsmith):
3113 // vectors (careful about, eg, vector of 3 foo)
3114 // _Complex int and friends
3115 // _Atomic T
3116 // Obj-C block pointers
3117 // Obj-C object pointers
3118 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3119 // clk_event_t, queue_t, reserve_id_t)
3120 // There're also Obj-C class types and the Obj-C selector type, but I think it
3121 // makes sense for those to return false here.
3122
3123 return false;
3124}
3125
3127 unsigned count = 0;
3128 // Count ivars declared in class extension.
3129 for (const auto *Ext : OI->known_extensions())
3130 count += Ext->ivar_size();
3131
3132 // Count ivar defined in this class's implementation. This
3133 // includes synthesized ivars.
3134 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3135 count += ImplDecl->ivar_size();
3136
3137 return count;
3138}
3139
3141 if (!E)
3142 return false;
3143
3144 // nullptr_t is always treated as null.
3145 if (E->getType()->isNullPtrType()) return true;
3146
3147 if (E->getType()->isAnyPointerType() &&
3150 return true;
3151
3152 // Unfortunately, __null has type 'int'.
3153 if (isa<GNUNullExpr>(E)) return true;
3154
3155 return false;
3156}
3157
3158/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3159/// exists.
3161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3162 I = ObjCImpls.find(D);
3163 if (I != ObjCImpls.end())
3164 return cast<ObjCImplementationDecl>(I->second);
3165 return nullptr;
3166}
3167
3168/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3169/// exists.
3171 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3172 I = ObjCImpls.find(D);
3173 if (I != ObjCImpls.end())
3174 return cast<ObjCCategoryImplDecl>(I->second);
3175 return nullptr;
3176}
3177
3178/// Set the implementation of ObjCInterfaceDecl.
3180 ObjCImplementationDecl *ImplD) {
3181 assert(IFaceD && ImplD && "Passed null params");
3182 ObjCImpls[IFaceD] = ImplD;
3183}
3184
3185/// Set the implementation of ObjCCategoryDecl.
3187 ObjCCategoryImplDecl *ImplD) {
3188 assert(CatD && ImplD && "Passed null params");
3189 ObjCImpls[CatD] = ImplD;
3190}
3191
3192const ObjCMethodDecl *
3194 return ObjCMethodRedecls.lookup(MD);
3195}
3196
3198 const ObjCMethodDecl *Redecl) {
3199 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3200 ObjCMethodRedecls[MD] = Redecl;
3201}
3202
3204 const NamedDecl *ND) const {
3205 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3206 return ID;
3207 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3208 return CD->getClassInterface();
3209 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3210 return IMD->getClassInterface();
3211
3212 return nullptr;
3213}
3214
3215/// Get the copy initialization expression of VarDecl, or nullptr if
3216/// none exists.
3218 assert(VD && "Passed null params");
3219 assert(VD->hasAttr<BlocksAttr>() &&
3220 "getBlockVarCopyInits - not __block var");
3221 auto I = BlockVarCopyInits.find(VD);
3222 if (I != BlockVarCopyInits.end())
3223 return I->second;
3224 return {nullptr, false};
3225}
3226
3227/// Set the copy initialization expression of a block var decl.
3229 bool CanThrow) {
3230 assert(VD && CopyExpr && "Passed null params");
3231 assert(VD->hasAttr<BlocksAttr>() &&
3232 "setBlockVarCopyInits - not __block var");
3233 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3234}
3235
3237 unsigned DataSize) const {
3238 if (!DataSize)
3240 else
3241 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3242 "incorrect data size provided to CreateTypeSourceInfo!");
3243
3244 auto *TInfo =
3245 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3246 new (TInfo) TypeSourceInfo(T, DataSize);
3247 return TInfo;
3248}
3249
3251 SourceLocation L) const {
3253 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3254 return TSI;
3255}
3256
3257const ASTRecordLayout &
3259 return getObjCLayout(D);
3260}
3261
3264 bool &AnyNonCanonArgs) {
3265 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3266 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3267 return CanonArgs;
3268}
3269
3272 bool AnyNonCanonArgs = false;
3273 for (auto &Arg : Args) {
3274 TemplateArgument OrigArg = Arg;
3276 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3277 }
3278 return AnyNonCanonArgs;
3279}
3280
3281//===----------------------------------------------------------------------===//
3282// Type creation/memoization methods
3283//===----------------------------------------------------------------------===//
3284
3286ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3287 unsigned fastQuals = quals.getFastQualifiers();
3288 quals.removeFastQualifiers();
3289
3290 // Check if we've already instantiated this type.
3291 llvm::FoldingSetNodeID ID;
3292 ExtQuals::Profile(ID, baseType, quals);
3293 llvm::FoldingSetInsertToken Token;
3294 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3295 assert(eq->getQualifiers() == quals);
3296 return QualType(eq, fastQuals);
3297 }
3298
3299 // If the base type is not canonical, make the appropriate canonical type.
3300 QualType canon;
3301 if (!baseType->isCanonicalUnqualified()) {
3302 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3303 canonSplit.Quals.addConsistentQualifiers(quals);
3304 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3305
3306 // Re-find the insert position.
3307 (void)ExtQualNodes.lookup(ID, Token);
3308 }
3309
3310 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3311 ExtQualNodes.insert(eq, Token);
3312 return QualType(eq, fastQuals);
3313}
3314
3316 LangAS AddressSpace) const {
3317 QualType CanT = getCanonicalType(T);
3318 if (CanT.getAddressSpace() == AddressSpace)
3319 return T;
3320
3321 // If we are composing extended qualifiers together, merge together
3322 // into one ExtQuals node.
3323 QualifierCollector Quals;
3324 const Type *TypeNode = Quals.strip(T);
3325
3326 // If this type already has an address space specified, it cannot get
3327 // another one.
3328 assert(!Quals.hasAddressSpace() &&
3329 "Type cannot be in multiple addr spaces!");
3330 Quals.addAddressSpace(AddressSpace);
3331
3332 return getExtQualType(TypeNode, Quals);
3333}
3334
3336 // If the type is not qualified with an address space, just return it
3337 // immediately.
3338 if (!T.hasAddressSpace())
3339 return T;
3340
3341 QualifierCollector Quals;
3342 const Type *TypeNode;
3343 // For arrays, strip the qualifier off the element type, then reconstruct the
3344 // array type
3345 if (T.getTypePtr()->isArrayType()) {
3346 T = getUnqualifiedArrayType(T, Quals);
3347 TypeNode = T.getTypePtr();
3348 } else {
3349 // If we are composing extended qualifiers together, merge together
3350 // into one ExtQuals node.
3351 while (T.hasAddressSpace()) {
3352 TypeNode = Quals.strip(T);
3353
3354 // If the type no longer has an address space after stripping qualifiers,
3355 // jump out.
3356 if (!QualType(TypeNode, 0).hasAddressSpace())
3357 break;
3358
3359 // There might be sugar in the way. Strip it and try again.
3360 T = T.getSingleStepDesugaredType(*this);
3361 }
3362 }
3363
3364 Quals.removeAddressSpace();
3365
3366 // Removal of the address space can mean there are no longer any
3367 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3368 // or required.
3369 if (Quals.hasNonFastQualifiers())
3370 return getExtQualType(TypeNode, Quals);
3371 else
3372 return QualType(TypeNode, Quals.getFastQualifiers());
3373}
3374
3375uint16_t
3377 bool IsVTTEntry) {
3378 assert(RD->isPolymorphic() &&
3379 "Attempted to get vtable pointer discriminator on a monomorphic type");
3380
3381 std::unique_ptr<MangleContext> MC(createMangleContext());
3382 SmallString<256> Str;
3383 llvm::raw_svector_ostream Out(Str);
3384 MC->mangleCXXVTable(RD, Out);
3385 if (IsVTTEntry)
3387 return llvm::getPointerAuthStableSipHash(Str);
3388}
3389
3390/// Encode a function type for use in the discriminator of a function pointer
3391/// type. We can't use the itanium scheme for this since C has quite permissive
3392/// rules for type compatibility that we need to be compatible with.
3393///
3394/// Formally, this function associates every function pointer type T with an
3395/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3396/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3397/// compatibility requires equivalent treatment under the ABI, so
3398/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3399/// a subset of ~. Crucially, however, it must be a proper subset because
3400/// CCompatible is not an equivalence relation: for example, int[] is compatible
3401/// with both int[1] and int[2], but the latter are not compatible with each
3402/// other. Therefore this encoding function must be careful to only distinguish
3403/// types if there is no third type with which they are both required to be
3404/// compatible.
3406 raw_ostream &OS, QualType QT) {
3407 // FIXME: Consider address space qualifiers.
3408 const Type *T = QT.getCanonicalType().getTypePtr();
3409
3410 // FIXME: Consider using the C++ type mangling when we encounter a construct
3411 // that is incompatible with C.
3412
3413 switch (T->getTypeClass()) {
3414 case Type::Atomic:
3416 Ctx, OS, cast<AtomicType>(T)->getValueType());
3417
3418 case Type::LValueReference:
3419 OS << "R";
3422 return;
3423 case Type::RValueReference:
3424 OS << "O";
3427 return;
3428
3429 case Type::Pointer:
3430 // C11 6.7.6.1p2:
3431 // For two pointer types to be compatible, both shall be identically
3432 // qualified and both shall be pointers to compatible types.
3433 // FIXME: we should also consider pointee types.
3434 OS << "P";
3435 return;
3436
3437 case Type::ObjCObjectPointer:
3438 case Type::BlockPointer:
3439 OS << "P";
3440 return;
3441
3442 case Type::Complex:
3443 OS << "C";
3445 Ctx, OS, cast<ComplexType>(T)->getElementType());
3446
3447 case Type::VariableArray:
3448 case Type::ConstantArray:
3449 case Type::IncompleteArray:
3450 case Type::ArrayParameter:
3451 // C11 6.7.6.2p6:
3452 // For two array types to be compatible, both shall have compatible
3453 // element types, and if both size specifiers are present, and are integer
3454 // constant expressions, then both size specifiers shall have the same
3455 // constant value [...]
3456 //
3457 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3458 // width of the array.
3459 OS << "A";
3461 Ctx, OS, cast<ArrayType>(T)->getElementType());
3462
3463 case Type::ObjCInterface:
3464 case Type::ObjCObject:
3465 OS << "<objc_object>";
3466 return;
3467
3468 case Type::Enum: {
3469 // C11 6.7.2.2p4:
3470 // Each enumerated type shall be compatible with char, a signed integer
3471 // type, or an unsigned integer type.
3472 //
3473 // So we have to treat enum types as integers.
3474 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3476 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3477 }
3478
3479 case Type::FunctionNoProto:
3480 case Type::FunctionProto: {
3481 // C11 6.7.6.3p15:
3482 // For two function types to be compatible, both shall specify compatible
3483 // return types. Moreover, the parameter type lists, if both are present,
3484 // shall agree in the number of parameters and in the use of the ellipsis
3485 // terminator; corresponding parameters shall have compatible types.
3486 //
3487 // That paragraph goes on to describe how unprototyped functions are to be
3488 // handled, which we ignore here. Unprototyped function pointers are hashed
3489 // as though they were prototyped nullary functions since thats probably
3490 // what the user meant. This behavior is non-conforming.
3491 // FIXME: If we add a "custom discriminator" function type attribute we
3492 // should encode functions as their discriminators.
3493 OS << "F";
3494 const auto *FuncType = cast<FunctionType>(T);
3495 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3496 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3497 for (QualType Param : FPT->param_types()) {
3498 Param = Ctx.getSignatureParameterType(Param);
3499 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3500 }
3501 if (FPT->isVariadic())
3502 OS << "z";
3503 }
3504 OS << "E";
3505 return;
3506 }
3507
3508 case Type::MemberPointer: {
3509 OS << "M";
3510 const auto *MPT = T->castAs<MemberPointerType>();
3512 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3513 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3514 return;
3515 }
3516 case Type::ExtVector:
3517 case Type::Vector:
3518 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3519 break;
3520
3521 // Don't bother discriminating based on these types.
3522 case Type::Pipe:
3523 case Type::BitInt:
3524 case Type::ConstantMatrix:
3525 OS << "?";
3526 return;
3527
3528 case Type::Builtin: {
3529 const auto *BTy = T->castAs<BuiltinType>();
3530 switch (BTy->getKind()) {
3531#define SIGNED_TYPE(Id, SingletonId) \
3532 case BuiltinType::Id: \
3533 OS << "i"; \
3534 return;
3535#define UNSIGNED_TYPE(Id, SingletonId) \
3536 case BuiltinType::Id: \
3537 OS << "i"; \
3538 return;
3539#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3540#define BUILTIN_TYPE(Id, SingletonId)
3541#include "clang/AST/BuiltinTypes.def"
3542 llvm_unreachable("placeholder types should not appear here.");
3543
3544 case BuiltinType::Half:
3545 OS << "Dh";
3546 return;
3547 case BuiltinType::Float:
3548 OS << "f";
3549 return;
3550 case BuiltinType::Double:
3551 OS << "d";
3552 return;
3553 case BuiltinType::LongDouble:
3554 OS << "e";
3555 return;
3556 case BuiltinType::Float16:
3557 OS << "DF16_";
3558 return;
3559 case BuiltinType::Float128:
3560 OS << "g";
3561 return;
3562
3563 case BuiltinType::Void:
3564 OS << "v";
3565 return;
3566
3567 case BuiltinType::ObjCId:
3568 case BuiltinType::ObjCClass:
3569 case BuiltinType::ObjCSel:
3570 case BuiltinType::NullPtr:
3571 OS << "P";
3572 return;
3573
3574 // Don't bother discriminating based on OpenCL types.
3575 case BuiltinType::OCLSampler:
3576 case BuiltinType::OCLEvent:
3577 case BuiltinType::OCLClkEvent:
3578 case BuiltinType::OCLQueue:
3579 case BuiltinType::OCLReserveID:
3580 case BuiltinType::BFloat16:
3581 case BuiltinType::VectorQuad:
3582 case BuiltinType::VectorPair:
3583 case BuiltinType::DMR1024:
3584 case BuiltinType::DMR2048:
3585 OS << "?";
3586 return;
3587
3588 // Don't bother discriminating based on these seldom-used types.
3589 case BuiltinType::Ibm128:
3590 return;
3591#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3592 case BuiltinType::Id: \
3593 return;
3594#include "clang/Basic/OpenCLImageTypes.def"
3595#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3596 case BuiltinType::Id: \
3597 return;
3598#include "clang/Basic/OpenCLExtensionTypes.def"
3599#define SVE_TYPE(Name, Id, SingletonId) \
3600 case BuiltinType::Id: \
3601 return;
3602#include "clang/Basic/AArch64ACLETypes.def"
3603#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3604 case BuiltinType::Id: \
3605 return;
3606#include "clang/Basic/HLSLIntangibleTypes.def"
3607 case BuiltinType::Dependent:
3608 llvm_unreachable("should never get here");
3609#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3610#include "clang/Basic/AMDGPUTypes.def"
3611 case BuiltinType::WasmExternRef:
3612#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3613#include "clang/Basic/RISCVVTypes.def"
3614#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3615#include "clang/Basic/SPIRVTypes.def"
3616 llvm_unreachable("not yet implemented");
3617 }
3618 llvm_unreachable("should never get here");
3619 }
3620 case Type::Record: {
3621 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3622 const IdentifierInfo *II = RD->getIdentifier();
3623
3624 // In C++, an immediate typedef of an anonymous struct or union
3625 // is considered to name it for ODR purposes, but C's specification
3626 // of type compatibility does not have a similar rule. Using the typedef
3627 // name in function type discriminators anyway, as we do here,
3628 // therefore technically violates the C standard: two function pointer
3629 // types defined in terms of two typedef'd anonymous structs with
3630 // different names are formally still compatible, but we are assigning
3631 // them different discriminators and therefore incompatible ABIs.
3632 //
3633 // This is a relatively minor violation that significantly improves
3634 // discrimination in some cases and has not caused problems in
3635 // practice. Regardless, it is now part of the ABI in places where
3636 // function type discrimination is used, and it can no longer be
3637 // changed except on new platforms.
3638
3639 if (!II)
3640 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3641 II = Typedef->getDeclName().getAsIdentifierInfo();
3642
3643 if (!II) {
3644 OS << "<anonymous_record>";
3645 return;
3646 }
3647 OS << II->getLength() << II->getName();
3648 return;
3649 }
3650 case Type::HLSLAttributedResource:
3651 case Type::HLSLInlineSpirv:
3652 llvm_unreachable("should never get here");
3653 break;
3654 case Type::OverflowBehavior:
3655 llvm_unreachable("should never get here");
3656 break;
3657 case Type::DeducedTemplateSpecialization:
3658 case Type::Auto:
3659#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3660#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3661#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3662#define ABSTRACT_TYPE(Class, Base)
3663#define TYPE(Class, Base)
3664#include "clang/AST/TypeNodes.inc"
3665 llvm_unreachable("unexpected non-canonical or dependent type!");
3666 return;
3667 }
3668}
3669
3671 assert(!T->isDependentType() &&
3672 "cannot compute type discriminator of a dependent type");
3673 SmallString<256> Str;
3674 llvm::raw_svector_ostream Out(Str);
3675
3676 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3677 T = T->getPointeeType();
3678
3679 if (T->isFunctionType()) {
3681 } else {
3682 T = T.getUnqualifiedType();
3683 // Calls to member function pointers don't need to worry about
3684 // language interop or the laxness of the C type compatibility rules.
3685 // We just mangle the member pointer type directly, which is
3686 // implicitly much stricter about type matching. However, we do
3687 // strip any top-level exception specification before this mangling.
3688 // C++23 requires calls to work when the function type is convertible
3689 // to the pointer type by a function pointer conversion, which can
3690 // change the exception specification. This does not technically
3691 // require the exception specification to not affect representation,
3692 // because the function pointer conversion is still always a direct
3693 // value conversion and therefore an opportunity to resign the
3694 // pointer. (This is in contrast to e.g. qualification conversions,
3695 // which can be applied in nested pointer positions, effectively
3696 // requiring qualified and unqualified representations to match.)
3697 // However, it is pragmatic to ignore exception specifications
3698 // because it allows a certain amount of `noexcept` mismatching
3699 // to not become a visible ODR problem. This also leaves some
3700 // room for the committee to add laxness to function pointer
3701 // conversions in future standards.
3702 if (auto *MPT = T->getAs<MemberPointerType>())
3703 if (MPT->isMemberFunctionPointer()) {
3704 QualType PointeeType = MPT->getPointeeType();
3705 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3706 EST_None) {
3708 T = getMemberPointerType(FT, MPT->getQualifier(),
3709 MPT->getMostRecentCXXRecordDecl());
3710 }
3711 }
3712 std::unique_ptr<MangleContext> MC(createMangleContext());
3713 MC->mangleCanonicalTypeName(T, Out);
3714 }
3715
3716 return llvm::getPointerAuthStableSipHash(Str);
3717}
3718
3720 Qualifiers::GC GCAttr) const {
3721 QualType CanT = getCanonicalType(T);
3722 if (CanT.getObjCGCAttr() == GCAttr)
3723 return T;
3724
3725 if (const auto *ptr = T->getAs<PointerType>()) {
3726 QualType Pointee = ptr->getPointeeType();
3727 if (Pointee->isAnyPointerType()) {
3728 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3729 return getPointerType(ResultType);
3730 }
3731 }
3732
3733 // If we are composing extended qualifiers together, merge together
3734 // into one ExtQuals node.
3735 QualifierCollector Quals;
3736 const Type *TypeNode = Quals.strip(T);
3737
3738 // If this type already has an ObjCGC specified, it cannot get
3739 // another one.
3740 assert(!Quals.hasObjCGCAttr() &&
3741 "Type cannot have multiple ObjCGCs!");
3742 Quals.addObjCGCAttr(GCAttr);
3743
3744 return getExtQualType(TypeNode, Quals);
3745}
3746
3748 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3749 QualType Pointee = Ptr->getPointeeType();
3750 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3751 return getPointerType(removeAddrSpaceQualType(Pointee));
3752 }
3753 }
3754 return T;
3755}
3756
3758 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3759 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3760 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3761
3762 llvm::FoldingSetNodeID ID;
3763 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3764
3765 llvm::FoldingSetInsertToken Token;
3766 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3767 if (CATy)
3768 return QualType(CATy, 0);
3769
3770 QualType CanonTy = getCanonicalType(WrappedTy);
3771 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3772 DependentDecls.size());
3774 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3775 OrNull, DependentDecls);
3776 Types.push_back(CATy);
3777 CountAttributedTypes.insert(CATy, Token);
3778
3779 return QualType(CATy, 0);
3780}
3781
3783 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3784 QualType CanonTy = getCanonicalType(WrappedTy);
3785
3786 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3787 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3788
3789 Types.push_back(LPATy);
3790 return QualType(LPATy, 0);
3791}
3792
3795 llvm::function_ref<QualType(QualType)> Adjust) const {
3796 switch (Orig->getTypeClass()) {
3797 case Type::Attributed: {
3798 const auto *AT = cast<AttributedType>(Orig);
3799 return getAttributedType(AT->getAttrKind(),
3800 adjustType(AT->getModifiedType(), Adjust),
3801 adjustType(AT->getEquivalentType(), Adjust),
3802 AT->getAttr());
3803 }
3804
3805 case Type::BTFTagAttributed: {
3806 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3807 return getBTFTagAttributedType(BTFT->getAttr(),
3808 adjustType(BTFT->getWrappedType(), Adjust));
3809 }
3810
3811 case Type::OverflowBehavior: {
3812 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3813 return getOverflowBehaviorType(OB->getBehaviorKind(),
3814 adjustType(OB->getUnderlyingType(), Adjust));
3815 }
3816
3817 case Type::Paren:
3818 return getParenType(
3819 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3820
3821 case Type::Adjusted: {
3822 const auto *AT = cast<AdjustedType>(Orig);
3823 return getAdjustedType(AT->getOriginalType(),
3824 adjustType(AT->getAdjustedType(), Adjust));
3825 }
3826
3827 case Type::MacroQualified: {
3828 const auto *MQT = cast<MacroQualifiedType>(Orig);
3829 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3830 MQT->getMacroIdentifier());
3831 }
3832
3833 default:
3834 return Adjust(Orig);
3835 }
3836}
3837
3839 FunctionType::ExtInfo Info) {
3840 if (T->getExtInfo() == Info)
3841 return T;
3842
3844 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3845 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3846 } else {
3847 const auto *FPT = cast<FunctionProtoType>(T);
3848 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3849 EPI.ExtInfo = Info;
3850 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3851 }
3852
3853 return cast<FunctionType>(Result.getTypePtr());
3854}
3855
3857 QualType ResultType) {
3858 return adjustType(FunctionType, [&](QualType Orig) {
3859 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3860 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3861
3862 const auto *FPT = Orig->castAs<FunctionProtoType>();
3863 return getFunctionType(ResultType, FPT->getParamTypes(),
3864 FPT->getExtProtoInfo());
3865 });
3866}
3867
3869 QualType ResultType) {
3870 FD = FD->getMostRecentDecl();
3871 while (true) {
3872 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3873 if (FunctionDecl *Next = FD->getPreviousDecl())
3874 FD = Next;
3875 else
3876 break;
3877 }
3879 L->DeducedReturnType(FD, ResultType);
3880}
3881
3882/// Get a function type and produce the equivalent function type with the
3883/// specified exception specification. Type sugar that can be present on a
3884/// declaration of a function with an exception specification is permitted
3885/// and preserved. Other type sugar (for instance, typedefs) is not.
3887 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3888 return adjustType(Orig, [&](QualType Ty) {
3889 const auto *Proto = Ty->castAs<FunctionProtoType>();
3890 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3891 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3892 });
3893}
3894
3902
3904 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3905 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3906 SmallVector<QualType, 16> Args(Proto->param_types().size());
3907 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3908 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3909 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3910 }
3911
3912 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3913 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3914 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3915 }
3916
3917 return T;
3918}
3919
3925
3927 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3928 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3929 EPI.ExtParameterInfos = nullptr;
3930 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3931 }
3932 return T;
3933}
3934
3940
3943 bool AsWritten) {
3944 // Update the type.
3945 QualType Updated =
3947 FD->setType(Updated);
3948
3949 if (!AsWritten)
3950 return;
3951
3952 // Update the type in the type source information too.
3953 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3954 // If the type and the type-as-written differ, we may need to update
3955 // the type-as-written too.
3956 if (TSInfo->getType() != FD->getType())
3957 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3958
3959 // FIXME: When we get proper type location information for exceptions,
3960 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3961 // up the TypeSourceInfo;
3962 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3963 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3964 "TypeLoc size mismatch from updating exception specification");
3965 TSInfo->overrideType(Updated);
3966 }
3967}
3968
3969/// getComplexType - Return the uniqued reference to the type for a complex
3970/// number with the specified element type.
3972 // Unique pointers, to guarantee there is only one pointer of a particular
3973 // structure.
3974 llvm::FoldingSetInsertToken Token;
3975 if (ComplexType *CT = ComplexTypes.lookup(T, Token))
3976 return QualType(CT, 0);
3977
3978 // If the pointee type isn't canonical, this won't be a canonical type either,
3979 // so fill in the canonical type field.
3980 QualType Canonical;
3981 if (!T.isCanonical()) {
3982 Canonical = getComplexType(getCanonicalType(T));
3983
3984 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
3985 }
3986 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3987 Types.push_back(New);
3988 ComplexTypes.insert(New, Token);
3989 return QualType(New, 0);
3990}
3991
3992/// getPointerType - Return the uniqued reference to the type for a pointer to
3993/// the specified type.
3995 // Unique pointers, to guarantee there is only one pointer of a particular
3996 // structure.
3997 llvm::FoldingSetInsertToken Token;
3998 if (PointerType *PT = PointerTypes.lookup(T, Token))
3999 return QualType(PT, 0);
4000
4001 // If the pointee type isn't canonical, this won't be a canonical type either,
4002 // so fill in the canonical type field.
4003 QualType Canonical;
4004 if (!T.isCanonical()) {
4005 Canonical = getPointerType(getCanonicalType(T));
4006
4007 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4008 }
4009 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4010 Types.push_back(New);
4011 PointerTypes.insert(New, Token);
4012 return QualType(New, 0);
4013}
4014
4016 llvm::FoldingSetInsertToken Token;
4017 AdjustedType *AT = AdjustedTypes.lookup({Orig, New}, Token);
4018 if (AT)
4019 return QualType(AT, 0);
4020
4021 QualType Canonical = getCanonicalType(New);
4022
4023 AT = new (*this, alignof(AdjustedType))
4024 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4025 Types.push_back(AT);
4026 AdjustedTypes.insert(AT, Token);
4027 return QualType(AT, 0);
4028}
4029
4031 llvm::FoldingSetInsertToken Token;
4032 AdjustedType *AT = AdjustedTypes.lookup({Orig, Decayed}, Token);
4033 if (AT)
4034 return QualType(AT, 0);
4035
4036 QualType Canonical = getCanonicalType(Decayed);
4037
4038 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4039 Types.push_back(AT);
4040 AdjustedTypes.insert(AT, Token);
4041 return QualType(AT, 0);
4042}
4043
4045 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4046
4047 QualType Decayed;
4048
4049 // C99 6.7.5.3p7:
4050 // A declaration of a parameter as "array of type" shall be
4051 // adjusted to "qualified pointer to type", where the type
4052 // qualifiers (if any) are those specified within the [ and ] of
4053 // the array type derivation.
4054 if (T->isArrayType())
4055 Decayed = getArrayDecayedType(T);
4056
4057 // C99 6.7.5.3p8:
4058 // A declaration of a parameter as "function returning type"
4059 // shall be adjusted to "pointer to function returning type", as
4060 // in 6.3.2.1.
4061 if (T->isFunctionType())
4062 Decayed = getPointerType(T);
4063
4064 return getDecayedType(T, Decayed);
4065}
4066
4068 if (Ty->isArrayParameterType())
4069 return Ty;
4070 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4071 QualType DTy = Ty.getDesugaredType(*this);
4072 const auto *ATy = cast<ConstantArrayType>(DTy);
4073 llvm::FoldingSetNodeID ID;
4074 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4075 ATy->getSizeExpr(), ATy->getSizeModifier(),
4076 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4077 llvm::FoldingSetInsertToken Token;
4078 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4079 if (AT)
4080 return QualType(AT, 0);
4081
4082 QualType Canonical;
4083 if (!DTy.isCanonical()) {
4084 Canonical = getArrayParameterType(getCanonicalType(Ty));
4085
4086 // Get the new insert position for the node we care about.
4087 AT = ArrayParameterTypes.lookup(ID, Token);
4088 assert(!AT && "Shouldn't be in the map!");
4089 }
4090
4091 AT = new (*this, alignof(ArrayParameterType))
4092 ArrayParameterType(ATy, Canonical);
4093 Types.push_back(AT);
4094 ArrayParameterTypes.insert(AT, Token);
4095 return QualType(AT, 0);
4096}
4097
4098/// getBlockPointerType - Return the uniqued reference to the type for
4099/// a pointer to the specified block.
4101 assert(T->isFunctionType() && "block of function types only");
4102 // Unique pointers, to guarantee there is only one block of a particular
4103 // structure.
4104 llvm::FoldingSetInsertToken Token;
4105 if (BlockPointerType *PT = BlockPointerTypes.lookup(T, Token))
4106 return QualType(PT, 0);
4107
4108 // If the block pointee type isn't canonical, this won't be a canonical
4109 // type either so fill in the canonical type field.
4110 QualType Canonical;
4111 if (!T.isCanonical()) {
4113
4114 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4115 }
4116 auto *New =
4117 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4118 Types.push_back(New);
4119 BlockPointerTypes.insert(New, Token);
4120 return QualType(New, 0);
4121}
4122
4123/// getLValueReferenceType - Return the uniqued reference to the type for an
4124/// lvalue reference to the specified type.
4126ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4127 assert((!T->isPlaceholderType() ||
4128 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4129 "Unresolved placeholder type");
4130
4131 // Unique pointers, to guarantee there is only one pointer of a particular
4132 // structure.
4133 llvm::FoldingSetInsertToken Token;
4134 if (LValueReferenceType *RT =
4135 LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token))
4136 return QualType(RT, 0);
4137
4138 const auto *InnerRef = T->getAs<ReferenceType>();
4139
4140 // If the referencee type isn't canonical, this won't be a canonical type
4141 // either, so fill in the canonical type field.
4142 QualType Canonical;
4143 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4144 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4145 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4146
4147 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4148 "Shouldn't be in the map!");
4149 }
4150
4151 auto *New = new (*this, alignof(LValueReferenceType))
4152 LValueReferenceType(T, Canonical, SpelledAsLValue);
4153 Types.push_back(New);
4154 LValueReferenceTypes.insert(New, Token);
4155
4156 return QualType(New, 0);
4157}
4158
4159/// getRValueReferenceType - Return the uniqued reference to the type for an
4160/// rvalue reference to the specified type.
4162 assert((!T->isPlaceholderType() ||
4163 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4164 "Unresolved placeholder type");
4165
4166 // Unique pointers, to guarantee there is only one pointer of a particular
4167 // structure.
4168 llvm::FoldingSetInsertToken Token;
4169 if (RValueReferenceType *RT = RValueReferenceTypes.lookup({T, false}, Token))
4170 return QualType(RT, 0);
4171
4172 const auto *InnerRef = T->getAs<ReferenceType>();
4173
4174 // If the referencee type isn't canonical, this won't be a canonical type
4175 // either, so fill in the canonical type field.
4176 QualType Canonical;
4177 if (InnerRef || !T.isCanonical()) {
4178 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4179 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4180
4181 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4182 "Shouldn't be in the map!");
4183 }
4184
4185 auto *New = new (*this, alignof(RValueReferenceType))
4186 RValueReferenceType(T, Canonical);
4187 Types.push_back(New);
4188 RValueReferenceTypes.insert(New, Token);
4189 return QualType(New, 0);
4190}
4191
4193 NestedNameSpecifier Qualifier,
4194 const CXXRecordDecl *Cls) const {
4195 if (!Qualifier) {
4196 assert(Cls && "At least one of Qualifier or Cls must be provided");
4197 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4198 } else if (!Cls) {
4199 Cls = Qualifier.getAsRecordDecl();
4200 }
4201 // Unique pointers, to guarantee there is only one pointer of a particular
4202 // structure.
4203 llvm::FoldingSetNodeID ID;
4204 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4205
4206 llvm::FoldingSetInsertToken Token;
4207 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4208 return QualType(PT, 0);
4209
4210 NestedNameSpecifier CanonicalQualifier = [&] {
4211 if (!Cls)
4212 return Qualifier.getCanonical();
4213 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4214 assert(R.isCanonical());
4215 return R;
4216 }();
4217 // If the pointee or class type isn't canonical, this won't be a canonical
4218 // type either, so fill in the canonical type field.
4219 QualType Canonical;
4220 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4221 Canonical =
4222 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4223 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4224 // Get the new insert position for the node we care about.
4225 [[maybe_unused]] MemberPointerType *NewIP =
4226 MemberPointerTypes.lookup(ID, Token);
4227 assert(!NewIP && "Shouldn't be in the map!");
4228 }
4229 auto *New = new (*this, alignof(MemberPointerType))
4230 MemberPointerType(T, Qualifier, Canonical);
4231 Types.push_back(New);
4232 MemberPointerTypes.insert(New, Token);
4233 return QualType(New, 0);
4234}
4235
4236/// getConstantArrayType - Return the unique reference to the type for an
4237/// array of the specified element type.
4239 const llvm::APInt &ArySizeIn,
4240 const Expr *SizeExpr,
4242 unsigned IndexTypeQuals) const {
4243 assert((EltTy->isDependentType() ||
4244 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4245 "Constant array of VLAs is illegal!");
4246
4247 // We only need the size as part of the type if it's instantiation-dependent.
4248 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4249 SizeExpr = nullptr;
4250
4251 // Convert the array size into a canonical width matching the pointer size for
4252 // the target.
4253 llvm::APInt ArySize(ArySizeIn);
4254 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4255
4256 // The type stores only the CVR bits of the index qualifiers, so key on
4257 // those.
4258 IndexTypeQuals &= Qualifiers::CVRMask;
4259
4260 llvm::FoldingSetNodeID ID;
4261 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4262 ASM, IndexTypeQuals);
4263
4264 llvm::FoldingSetInsertToken Token;
4265 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4266 return QualType(ATP, 0);
4267
4268 // If the element type isn't canonical or has qualifiers, or the array bound
4269 // is instantiation-dependent, this won't be a canonical type either, so fill
4270 // in the canonical type field.
4271 QualType Canon;
4272 // FIXME: Check below should look for qualifiers behind sugar.
4273 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4274 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4275 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4276 ASM, IndexTypeQuals);
4277 Canon = getQualifiedType(Canon, canonSplit.Quals);
4278
4279 // Get the new insert position for the node we care about.
4280 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4281 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4282 }
4283
4284 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4285 ASM, IndexTypeQuals);
4286 ConstantArrayTypes.insert(New, Token);
4287 Types.push_back(New);
4288 return QualType(New, 0);
4289}
4290
4291/// getVariableArrayDecayedType - Turns the given type, which may be
4292/// variably-modified, into the corresponding type with all the known
4293/// sizes replaced with [*].
4295 // Vastly most common case.
4296 if (!type->isVariablyModifiedType()) return type;
4297
4298 QualType result;
4299
4300 SplitQualType split = type.getSplitDesugaredType();
4301 const Type *ty = split.Ty;
4302 switch (ty->getTypeClass()) {
4303#define TYPE(Class, Base)
4304#define ABSTRACT_TYPE(Class, Base)
4305#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4306#include "clang/AST/TypeNodes.inc"
4307 llvm_unreachable("didn't desugar past all non-canonical types?");
4308
4309 // These types should never be variably-modified.
4310 case Type::Builtin:
4311 case Type::Complex:
4312 case Type::Vector:
4313 case Type::DependentVector:
4314 case Type::ExtVector:
4315 case Type::DependentSizedExtVector:
4316 case Type::ConstantMatrix:
4317 case Type::DependentSizedMatrix:
4318 case Type::DependentAddressSpace:
4319 case Type::ObjCObject:
4320 case Type::ObjCInterface:
4321 case Type::ObjCObjectPointer:
4322 case Type::Record:
4323 case Type::Enum:
4324 case Type::UnresolvedUsing:
4325 case Type::TypeOfExpr:
4326 case Type::TypeOf:
4327 case Type::Decltype:
4328 case Type::UnaryTransform:
4329 case Type::DependentName:
4330 case Type::InjectedClassName:
4331 case Type::TemplateSpecialization:
4332 case Type::TemplateTypeParm:
4333 case Type::SubstTemplateTypeParmPack:
4334 case Type::SubstBuiltinTemplatePack:
4335 case Type::Auto:
4336 case Type::DeducedTemplateSpecialization:
4337 case Type::PackExpansion:
4338 case Type::PackIndexing:
4339 case Type::BitInt:
4340 case Type::DependentBitInt:
4341 case Type::ArrayParameter:
4342 case Type::HLSLAttributedResource:
4343 case Type::HLSLInlineSpirv:
4344 case Type::OverflowBehavior:
4345 llvm_unreachable("type should never be variably-modified");
4346
4347 // These types can be variably-modified but should never need to
4348 // further decay.
4349 case Type::FunctionNoProto:
4350 case Type::FunctionProto:
4351 case Type::BlockPointer:
4352 case Type::MemberPointer:
4353 case Type::Pipe:
4354 return type;
4355
4356 // These types can be variably-modified. All these modifications
4357 // preserve structure except as noted by comments.
4358 // TODO: if we ever care about optimizing VLAs, there are no-op
4359 // optimizations available here.
4360 case Type::Pointer:
4363 break;
4364
4365 case Type::LValueReference: {
4366 const auto *lv = cast<LValueReferenceType>(ty);
4367 result = getLValueReferenceType(
4368 getVariableArrayDecayedType(lv->getPointeeType()),
4369 lv->isSpelledAsLValue());
4370 break;
4371 }
4372
4373 case Type::RValueReference: {
4374 const auto *lv = cast<RValueReferenceType>(ty);
4375 result = getRValueReferenceType(
4376 getVariableArrayDecayedType(lv->getPointeeType()));
4377 break;
4378 }
4379
4380 case Type::Atomic: {
4381 const auto *at = cast<AtomicType>(ty);
4382 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4383 break;
4384 }
4385
4386 case Type::ConstantArray: {
4387 const auto *cat = cast<ConstantArrayType>(ty);
4388 result = getConstantArrayType(
4389 getVariableArrayDecayedType(cat->getElementType()),
4390 cat->getSize(),
4391 cat->getSizeExpr(),
4392 cat->getSizeModifier(),
4393 cat->getIndexTypeCVRQualifiers());
4394 break;
4395 }
4396
4397 case Type::DependentSizedArray: {
4398 const auto *dat = cast<DependentSizedArrayType>(ty);
4400 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4401 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4402 break;
4403 }
4404
4405 // Turn incomplete types into [*] types.
4406 case Type::IncompleteArray: {
4407 const auto *iat = cast<IncompleteArrayType>(ty);
4408 result =
4410 /*size*/ nullptr, ArraySizeModifier::Normal,
4411 iat->getIndexTypeCVRQualifiers());
4412 break;
4413 }
4414
4415 // Turn VLA types into [*] types.
4416 case Type::VariableArray: {
4417 const auto *vat = cast<VariableArrayType>(ty);
4418 result =
4420 /*size*/ nullptr, ArraySizeModifier::Star,
4421 vat->getIndexTypeCVRQualifiers());
4422 break;
4423 }
4424 }
4425
4426 // Apply the top-level qualifiers from the original.
4427 return getQualifiedType(result, split.Quals);
4428}
4429
4430/// getVariableArrayType - Returns a non-unique reference to the type for a
4431/// variable array of the specified element type.
4434 unsigned IndexTypeQuals) const {
4435 // Since we don't unique expressions, it isn't possible to unique VLA's
4436 // that have an expression provided for their size.
4437 QualType Canon;
4438
4439 // Be sure to pull qualifiers off the element type.
4440 // FIXME: Check below should look for qualifiers behind sugar.
4441 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4442 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4443 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4444 IndexTypeQuals);
4445 Canon = getQualifiedType(Canon, canonSplit.Quals);
4446 }
4447
4448 auto *New = new (*this, alignof(VariableArrayType))
4449 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4450
4451 VariableArrayTypes.push_back(New);
4452 Types.push_back(New);
4453 return QualType(New, 0);
4454}
4455
4456/// getDependentSizedArrayType - Returns a non-unique reference to
4457/// the type for a dependently-sized array of the specified element
4458/// type.
4462 unsigned elementTypeQuals) const {
4463 assert((!numElements || numElements->isTypeDependent() ||
4464 numElements->isValueDependent()) &&
4465 "Size must be type- or value-dependent!");
4466
4467 SplitQualType canonElementType = getCanonicalType(elementType).split();
4468
4469 llvm::FoldingSetInsertToken Token;
4470 llvm::FoldingSetNodeID ID;
4472 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4473 ASM, elementTypeQuals, numElements);
4474
4475 // Look for an existing type with these properties.
4476 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4477
4478 // Dependently-sized array types that do not have a specified number
4479 // of elements will have their sizes deduced from a dependent
4480 // initializer.
4481 if (!numElements) {
4482 if (canonTy)
4483 return QualType(canonTy, 0);
4484
4485 auto *newType = new (*this, alignof(DependentSizedArrayType))
4486 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4487 elementTypeQuals);
4488 DependentSizedArrayTypes.insert(newType, Token);
4489 Types.push_back(newType);
4490 return QualType(newType, 0);
4491 }
4492
4493 // If we don't have one, build one.
4494 if (!canonTy) {
4495 canonTy = new (*this, alignof(DependentSizedArrayType))
4496 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4497 numElements, ASM, elementTypeQuals);
4498 DependentSizedArrayTypes.insert(canonTy, Token);
4499 Types.push_back(canonTy);
4500 }
4501
4502 // Apply qualifiers from the element type to the array.
4503 QualType canon = getQualifiedType(QualType(canonTy,0),
4504 canonElementType.Quals);
4505
4506 // If we didn't need extra canonicalization for the element type or the size
4507 // expression, then just use that as our result.
4508 if (QualType(canonElementType.Ty, 0) == elementType &&
4509 canonTy->getSizeExpr() == numElements)
4510 return canon;
4511
4512 // Otherwise, we need to build a type which follows the spelling
4513 // of the element type.
4514 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4515 DependentSizedArrayType(elementType, canon, numElements, ASM,
4516 elementTypeQuals);
4517 Types.push_back(sugaredType);
4518 return QualType(sugaredType, 0);
4519}
4520
4523 unsigned elementTypeQuals) const {
4524 llvm::FoldingSetNodeID ID;
4525 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4526
4527 llvm::FoldingSetInsertToken Token;
4528 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4529 return QualType(iat, 0);
4530
4531 // If the element type isn't canonical, this won't be a canonical type
4532 // either, so fill in the canonical type field. We also have to pull
4533 // qualifiers off the element type.
4534 QualType canon;
4535
4536 // FIXME: Check below should look for qualifiers behind sugar.
4537 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4538 SplitQualType canonSplit = getCanonicalType(elementType).split();
4539 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4540 ASM, elementTypeQuals);
4541 canon = getQualifiedType(canon, canonSplit.Quals);
4542
4543 // Get the new insert position for the node we care about.
4544 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4545 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4546 }
4547
4548 auto *newType = new (*this, alignof(IncompleteArrayType))
4549 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4550
4551 IncompleteArrayTypes.insert(newType, Token);
4552 Types.push_back(newType);
4553 return QualType(newType, 0);
4554}
4555
4558#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4559 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4560 NUMVECTORS};
4561
4562#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4563 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4564
4565 switch (Ty->getKind()) {
4566 default:
4567 llvm_unreachable("Unsupported builtin vector type");
4568
4569#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4570 ElBits, NF, IsSigned) \
4571 case BuiltinType::Id: \
4572 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4573 llvm::ElementCount::getScalable(NumEls), NF};
4574#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4575 ElBits, NF) \
4576 case BuiltinType::Id: \
4577 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4578 llvm::ElementCount::getScalable(NumEls), NF};
4579#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4580 ElBits, NF) \
4581 case BuiltinType::Id: \
4582 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4583#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4584 ElBits, NF) \
4585 case BuiltinType::Id: \
4586 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4587#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4588 case BuiltinType::Id: \
4589 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4590#include "clang/Basic/AArch64ACLETypes.def"
4591
4592#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4593 IsSigned) \
4594 case BuiltinType::Id: \
4595 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4596 llvm::ElementCount::getScalable(NumEls), NF};
4597#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4598 case BuiltinType::Id: \
4599 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4600 llvm::ElementCount::getScalable(NumEls), NF};
4601#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4602 case BuiltinType::Id: \
4603 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4604#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4605 case BuiltinType::Id: \
4606 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4607#include "clang/Basic/RISCVVTypes.def"
4608 }
4609}
4610
4611/// getExternrefType - Return a WebAssembly externref type, which represents an
4612/// opaque reference to a host value.
4614 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4615#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4616 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4617 return SingletonId;
4618#include "clang/Basic/WebAssemblyReferenceTypes.def"
4619 }
4620 llvm_unreachable(
4621 "shouldn't try to generate type externref outside WebAssembly target");
4622}
4623
4624/// getScalableVectorType - Return the unique reference to a scalable vector
4625/// type of the specified element type and size. VectorType must be a built-in
4626/// type.
4628 unsigned NumFields) const {
4629 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4630 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4631 return It->second;
4632
4633 if (Target->hasAArch64ACLETypes()) {
4634 uint64_t EltTySize = getTypeSize(EltTy);
4635
4636#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4637 ElBits, NF, IsSigned) \
4638 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4639 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4640 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4641 return ScalableVecTyMap[K] = SingletonId; \
4642 }
4643#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4644 ElBits, NF) \
4645 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4646 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4647 return ScalableVecTyMap[K] = SingletonId; \
4648 }
4649#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4650 ElBits, NF) \
4651 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4652 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4653 return ScalableVecTyMap[K] = SingletonId; \
4654 }
4655#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4656 ElBits, NF) \
4657 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4658 NumElts == (NumEls * NF) && NumFields == 1) { \
4659 return ScalableVecTyMap[K] = SingletonId; \
4660 }
4661#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4662 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4663 return ScalableVecTyMap[K] = SingletonId;
4664#include "clang/Basic/AArch64ACLETypes.def"
4665 } else if (Target->hasRISCVVTypes()) {
4666 uint64_t EltTySize = getTypeSize(EltTy);
4667#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4668 IsFP, IsBF) \
4669 if (!EltTy->isBooleanType() && \
4670 ((EltTy->hasIntegerRepresentation() && \
4671 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4672 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4673 IsFP && !IsBF) || \
4674 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4675 IsBF && !IsFP)) && \
4676 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4677 return ScalableVecTyMap[K] = SingletonId;
4678#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4679 if (EltTy->isBooleanType() && NumElts == NumEls) \
4680 return ScalableVecTyMap[K] = SingletonId;
4681#include "clang/Basic/RISCVVTypes.def"
4682 }
4683 return QualType();
4684}
4685
4686/// getVectorType - Return the unique reference to a vector type of
4687/// the specified element type and size. VectorType must be a built-in type.
4689 VectorKind VecKind) const {
4690 assert(vecType->isBuiltinType() ||
4691 (vecType->isBitIntType() &&
4692 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4693 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4694
4695 // Check if we've already instantiated a vector of this type.
4696 llvm::FoldingSetNodeID ID;
4697 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4698
4699 llvm::FoldingSetInsertToken Token;
4700 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4701 return QualType(VTP, 0);
4702
4703 // If the element type isn't canonical, this won't be a canonical type either,
4704 // so fill in the canonical type field.
4705 QualType Canonical;
4706 if (!vecType.isCanonical()) {
4707 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4708
4709 // Get the new insert position for the node we care about.
4710 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4711 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4712 }
4713 auto *New = new (*this, alignof(VectorType))
4714 VectorType(vecType, NumElts, Canonical, VecKind);
4715 VectorTypes.insert(New, Token);
4716 Types.push_back(New);
4717 return QualType(New, 0);
4718}
4719
4721 SourceLocation AttrLoc,
4722 VectorKind VecKind) const {
4723 llvm::FoldingSetNodeID ID;
4724 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4725 VecKind);
4726 llvm::FoldingSetInsertToken Token;
4727 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4729
4730 if (Canon) {
4731 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4732 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4733 } else {
4734 QualType CanonVecTy = getCanonicalType(VecType);
4735 if (CanonVecTy == VecType) {
4736 New = new (*this, alignof(DependentVectorType))
4737 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4738
4739 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4740 assert(!CanonCheck &&
4741 "Dependent-sized vector_size canonical type broken");
4742 (void)CanonCheck;
4743 DependentVectorTypes.insert(New, Token);
4744 } else {
4745 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4746 SourceLocation(), VecKind);
4747 New = new (*this, alignof(DependentVectorType))
4748 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4749 }
4750 }
4751
4752 Types.push_back(New);
4753 return QualType(New, 0);
4754}
4755
4756/// getExtVectorType - Return the unique reference to an extended vector type of
4757/// the specified element type and size. VectorType must be a built-in type.
4759 unsigned NumElts) const {
4760 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4761 (vecType->isBitIntType() &&
4762 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4763 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4764
4765 // Check if we've already instantiated a vector of this type.
4766 llvm::FoldingSetNodeID ID;
4767 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4769 llvm::FoldingSetInsertToken Token;
4770 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4771 return QualType(VTP, 0);
4772
4773 // If the element type isn't canonical, this won't be a canonical type either,
4774 // so fill in the canonical type field.
4775 QualType Canonical;
4776 if (!vecType.isCanonical()) {
4777 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4778
4779 // Get the new insert position for the node we care about.
4780 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4781 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4782 }
4783 auto *New = new (*this, alignof(ExtVectorType))
4784 ExtVectorType(vecType, NumElts, Canonical);
4785 VectorTypes.insert(New, Token);
4786 Types.push_back(New);
4787 return QualType(New, 0);
4788}
4789
4792 Expr *SizeExpr,
4793 SourceLocation AttrLoc) const {
4794 llvm::FoldingSetNodeID ID;
4796 SizeExpr);
4797
4798 llvm::FoldingSetInsertToken Token;
4800 DependentSizedExtVectorTypes.lookup(ID, Token);
4802 if (Canon) {
4803 // We already have a canonical version of this array type; use it as
4804 // the canonical type for a newly-built type.
4805 New = new (*this, alignof(DependentSizedExtVectorType))
4806 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4807 AttrLoc);
4808 } else {
4809 QualType CanonVecTy = getCanonicalType(vecType);
4810 if (CanonVecTy == vecType) {
4811 New = new (*this, alignof(DependentSizedExtVectorType))
4812 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4813
4814 DependentSizedExtVectorType *CanonCheck =
4815 DependentSizedExtVectorTypes.lookup(ID, Token);
4816 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4817 (void)CanonCheck;
4818 DependentSizedExtVectorTypes.insert(New, Token);
4819 } else {
4820 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4821 SourceLocation());
4822 New = new (*this, alignof(DependentSizedExtVectorType))
4823 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4824 }
4825 }
4826
4827 Types.push_back(New);
4828 return QualType(New, 0);
4829}
4830
4832 unsigned NumColumns) const {
4833 llvm::FoldingSetNodeID ID;
4834 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4835 Type::ConstantMatrix);
4836
4837 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4838 "need a valid element type");
4839 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4840 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4841 "need valid matrix dimensions");
4842 llvm::FoldingSetInsertToken Token;
4843 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4844 return QualType(MTP, 0);
4845
4846 QualType Canonical;
4847 if (!ElementTy.isCanonical()) {
4848 Canonical =
4849 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4850
4851 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4852 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4853 (void)NewIP;
4854 }
4855
4856 auto *New = new (*this, alignof(ConstantMatrixType))
4857 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4858 MatrixTypes.insert(New, Token);
4859 Types.push_back(New);
4860 return QualType(New, 0);
4861}
4862
4864 Expr *RowExpr,
4865 Expr *ColumnExpr,
4866 SourceLocation AttrLoc) const {
4867 QualType CanonElementTy = getCanonicalType(ElementTy);
4868 llvm::FoldingSetNodeID ID;
4869 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4870 ColumnExpr);
4871
4872 llvm::FoldingSetInsertToken Token;
4873 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4874
4875 if (!Canon) {
4876 Canon = new (*this, alignof(DependentSizedMatrixType))
4877 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4878 ColumnExpr, AttrLoc);
4879#ifndef NDEBUG
4880 DependentSizedMatrixType *CanonCheck =
4881 DependentSizedMatrixTypes.lookup(ID, Token);
4882 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4883#endif
4884 DependentSizedMatrixTypes.insert(Canon, Token);
4885 Types.push_back(Canon);
4886 }
4887
4888 // Already have a canonical version of the matrix type
4889 //
4890 // If it exactly matches the requested type, use it directly.
4891 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4892 Canon->getRowExpr() == ColumnExpr)
4893 return QualType(Canon, 0);
4894
4895 // Use Canon as the canonical type for newly-built type.
4897 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4898 ColumnExpr, AttrLoc);
4899 Types.push_back(New);
4900 return QualType(New, 0);
4901}
4902
4904 Expr *AddrSpaceExpr,
4905 SourceLocation AttrLoc) const {
4906 assert(AddrSpaceExpr->isInstantiationDependent());
4907
4908 QualType canonPointeeType = getCanonicalType(PointeeType);
4909
4910 llvm::FoldingSetInsertToken Token;
4911 llvm::FoldingSetNodeID ID;
4912 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4913 AddrSpaceExpr);
4914
4915 DependentAddressSpaceType *canonTy =
4916 DependentAddressSpaceTypes.lookup(ID, Token);
4917
4918 if (!canonTy) {
4919 canonTy = new (*this, alignof(DependentAddressSpaceType))
4920 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4921 AttrLoc);
4922 DependentAddressSpaceTypes.insert(canonTy, Token);
4923 Types.push_back(canonTy);
4924 }
4925
4926 if (canonPointeeType == PointeeType &&
4927 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4928 return QualType(canonTy, 0);
4929
4930 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4931 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4932 AddrSpaceExpr, AttrLoc);
4933 Types.push_back(sugaredType);
4934 return QualType(sugaredType, 0);
4935}
4936
4937/// Determine whether \p T is canonical as the result type of a function.
4939 return T.isCanonical() &&
4940 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4941 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4942}
4943
4944/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4945QualType
4947 const FunctionType::ExtInfo &Info) const {
4948 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4949 // functionality creates a function without a prototype regardless of
4950 // language mode (so it makes them even in C++). Once the rewriter has been
4951 // fixed, this assertion can be enabled again.
4952 //assert(!LangOpts.requiresStrictPrototypes() &&
4953 // "strict prototypes are disabled");
4954
4955 // Unique functions, to guarantee there is only one function of a particular
4956 // structure.
4957 llvm::FoldingSetNodeID ID;
4958 FunctionNoProtoType::Profile(ID, ResultTy, Info);
4959
4960 llvm::FoldingSetInsertToken Token;
4961 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
4962 return QualType(FT, 0);
4963
4964 QualType Canonical;
4965 if (!isCanonicalResultType(ResultTy)) {
4966 Canonical =
4968
4969 // Get the new insert position for the node we care about.
4970 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
4971 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4972 }
4973
4974 auto *New = new (*this, alignof(FunctionNoProtoType))
4975 FunctionNoProtoType(ResultTy, Canonical, Info);
4976 Types.push_back(New);
4977 FunctionNoProtoTypes.insert(New, Token);
4978 return QualType(New, 0);
4979}
4980
4983 CanQualType CanResultType = getCanonicalType(ResultType);
4984
4985 // Canonical result types do not have ARC lifetime qualifiers.
4986 if (CanResultType.getQualifiers().hasObjCLifetime()) {
4987 Qualifiers Qs = CanResultType.getQualifiers();
4988 Qs.removeObjCLifetime();
4990 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
4991 }
4992
4993 return CanResultType;
4994}
4995
4997 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
4998 if (ESI.Type == EST_None)
4999 return true;
5000 if (!NoexceptInType)
5001 return false;
5002
5003 // C++17 onwards: exception specification is part of the type, as a simple
5004 // boolean "can this function type throw".
5005 if (ESI.Type == EST_BasicNoexcept)
5006 return true;
5007
5008 // A noexcept(expr) specification is (possibly) canonical if expr is
5009 // value-dependent.
5010 if (ESI.Type == EST_DependentNoexcept)
5011 return true;
5012
5013 // A dynamic exception specification is canonical if it only contains pack
5014 // expansions (so we can't tell whether it's non-throwing) and all its
5015 // contained types are canonical.
5016 if (ESI.Type == EST_Dynamic) {
5017 bool AnyPackExpansions = false;
5018 for (QualType ET : ESI.Exceptions) {
5019 if (!ET.isCanonical())
5020 return false;
5021 if (ET->getAs<PackExpansionType>())
5022 AnyPackExpansions = true;
5023 }
5024 return AnyPackExpansions;
5025 }
5026
5027 return false;
5028}
5029
5030QualType ASTContext::getFunctionTypeInternal(
5031 QualType ResultTy, ArrayRef<QualType> ArgArray,
5032 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5033 size_t NumArgs = ArgArray.size();
5034
5035 // Unique functions, to guarantee there is only one function of a particular
5036 // structure.
5037 llvm::FoldingSetNodeID ID;
5038 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5039 *this);
5040
5041 QualType Canonical;
5042 bool Unique = false;
5043
5044 llvm::FoldingSetInsertToken Token;
5045 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5046 QualType Existing = QualType(FPT, 0);
5047
5048 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5049 // it so long as our exception specification doesn't contain a dependent
5050 // noexcept expression, or we're just looking for a canonical type.
5051 // Otherwise, we're going to need to create a type
5052 // sugar node to hold the concrete expression.
5053 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5054 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5055 return Existing;
5056
5057 // We need a new type sugar node for this one, to hold the new noexcept
5058 // expression. We do no canonicalization here, but that's OK since we don't
5059 // expect to see the same noexcept expression much more than once.
5060 Canonical = getCanonicalType(Existing);
5061 Unique = true;
5062 }
5063
5064 bool NoexceptInType = getLangOpts().CPlusPlus17;
5065 bool IsCanonicalExceptionSpec =
5067
5068 // Determine whether the type being created is already canonical or not.
5069 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5070 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5071 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5072 if (!ArgArray[i].isCanonicalAsParam())
5073 isCanonical = false;
5074
5075 if (OnlyWantCanonical)
5076 assert(isCanonical &&
5077 "given non-canonical parameters constructing canonical type");
5078
5079 // If this type isn't canonical, get the canonical version of it if we don't
5080 // already have it. The exception spec is only partially part of the
5081 // canonical type, and only in C++17 onwards.
5082 if (!isCanonical && Canonical.isNull()) {
5083 SmallVector<QualType, 16> CanonicalArgs;
5084 CanonicalArgs.reserve(NumArgs);
5085 for (unsigned i = 0; i != NumArgs; ++i)
5086 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5087
5088 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5089 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5090 CanonicalEPI.HasTrailingReturn = false;
5091
5092 if (IsCanonicalExceptionSpec) {
5093 // Exception spec is already OK.
5094 } else if (NoexceptInType) {
5095 switch (EPI.ExceptionSpec.Type) {
5097 // We don't know yet. It shouldn't matter what we pick here; no-one
5098 // should ever look at this.
5099 [[fallthrough]];
5100 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5101 CanonicalEPI.ExceptionSpec.Type = EST_None;
5102 break;
5103
5104 // A dynamic exception specification is almost always "not noexcept",
5105 // with the exception that a pack expansion might expand to no types.
5106 case EST_Dynamic: {
5107 bool AnyPacks = false;
5108 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5109 if (ET->getAs<PackExpansionType>())
5110 AnyPacks = true;
5111 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5112 }
5113 if (!AnyPacks)
5114 CanonicalEPI.ExceptionSpec.Type = EST_None;
5115 else {
5116 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5117 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5118 }
5119 break;
5120 }
5121
5122 case EST_DynamicNone:
5123 case EST_BasicNoexcept:
5124 case EST_NoexceptTrue:
5125 case EST_NoThrow:
5126 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5127 break;
5128
5130 llvm_unreachable("dependent noexcept is already canonical");
5131 }
5132 } else {
5133 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5134 }
5135
5136 // Adjust the canonical function result type.
5137 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5138 Canonical =
5139 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5140
5141 // Get the new insert position for the node we care about.
5142 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5143 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5144 }
5145
5146 // Compute the needed size to hold this FunctionProtoType and the
5147 // various trailing objects.
5148 auto ESH = FunctionProtoType::getExceptionSpecSize(
5149 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5150 size_t Size = FunctionProtoType::totalSizeToAlloc<
5151 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5152 FunctionType::FunctionTypeExtraAttributeInfo,
5153 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5154 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5155 FunctionEffect, EffectConditionExpr>(
5158 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5159 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5160 EPI.ExtParameterInfos ? NumArgs : 0,
5162 EPI.FunctionEffects.conditions().size());
5163
5164 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5165 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5166 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5167 Types.push_back(FTP);
5168 if (!Unique)
5169 FunctionProtoTypes.insert(FTP, Token);
5170 if (!EPI.FunctionEffects.empty())
5171 AnyFunctionEffects = true;
5172 return QualType(FTP, 0);
5173}
5174
5175QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5176 llvm::FoldingSetInsertToken Token;
5177 if (PipeType *PT = PipeTypes.lookup({T, ReadOnly}, Token))
5178 return QualType(PT, 0);
5179
5180 // If the pipe element type isn't canonical, this won't be a canonical type
5181 // either, so fill in the canonical type field.
5182 QualType Canonical;
5183 if (!T.isCanonical()) {
5184 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5185
5186 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5187 "Shouldn't be in the map!");
5188 }
5189 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5190 Types.push_back(New);
5191 PipeTypes.insert(New, Token);
5192 return QualType(New, 0);
5193}
5194
5196 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5197 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5198 : Ty;
5199}
5200
5202 return getPipeType(T, true);
5203}
5204
5206 return getPipeType(T, false);
5207}
5208
5209QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5210 auto Key = std::make_pair(unsigned(IsUnsigned), NumBits);
5211
5212 llvm::FoldingSetInsertToken Token;
5213 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5214 return QualType(EIT, 0);
5215
5216 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5217 BitIntTypes.insert(New, Token);
5218 Types.push_back(New);
5219 return QualType(New, 0);
5220}
5221
5223 Expr *NumBitsExpr) const {
5224 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5225 llvm::FoldingSetNodeID ID;
5226 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5227
5228 llvm::FoldingSetInsertToken Token;
5229 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5230 return QualType(Existing, 0);
5231
5232 auto *New = new (*this, alignof(DependentBitIntType))
5233 DependentBitIntType(IsUnsigned, NumBitsExpr);
5234 DependentBitIntTypes.insert(New, Token);
5235
5236 Types.push_back(New);
5237 return QualType(New, 0);
5238}
5239
5242 using Kind = PredefinedSugarType::Kind;
5243
5244 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5245 Target != nullptr)
5246 return QualType(Target, 0);
5247
5248 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5249 switch (KDI) {
5250 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5251 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5252 // are part of the core language and are widely used. Using
5253 // PredefinedSugarType makes these types as named sugar types rather than
5254 // standard integer types, enabling better hints and diagnostics.
5255 case Kind::SizeT:
5256 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5257 case Kind::SignedSizeT:
5258 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5259 case Kind::PtrdiffT:
5260 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5261 }
5262 llvm_unreachable("unexpected kind");
5263 };
5264 auto *New = new (*this, alignof(PredefinedSugarType))
5265 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5266 getCanonicalType(*this, static_cast<Kind>(KD)));
5267 Types.push_back(New);
5268 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5269 return QualType(New, 0);
5270}
5271
5273 NestedNameSpecifier Qualifier,
5274 const TypeDecl *Decl) const {
5275 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5276 return getTagType(Keyword, Qualifier, Tag,
5277 /*OwnsTag=*/false);
5278 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5279 return getTypedefType(Keyword, Qualifier, Typedef);
5280 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5281 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5282
5284 assert(!Qualifier);
5285 return QualType(Decl->TypeForDecl, 0);
5286}
5287
5289 if (auto *Tag = dyn_cast<TagDecl>(TD))
5290 return getCanonicalTagType(Tag);
5291 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5292 return getCanonicalType(TN->getUnderlyingType());
5293 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5295 assert(TD->TypeForDecl);
5296 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5297}
5298
5300 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5301 return getCanonicalTagType(TD);
5302 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5303 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5305 /*Qualifier=*/std::nullopt, TD);
5306 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5307 return getCanonicalUnresolvedUsingType(Using);
5308
5309 assert(Decl->TypeForDecl);
5310 return QualType(Decl->TypeForDecl, 0);
5311}
5312
5313/// getTypedefType - Return the unique reference to the type for the
5314/// specified typedef name decl.
5317 NestedNameSpecifier Qualifier,
5318 const TypedefNameDecl *Decl, QualType UnderlyingType,
5319 std::optional<bool> TypeMatchesDeclOrNone) const {
5320 if (!TypeMatchesDeclOrNone) {
5321 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5322 assert(!DeclUnderlyingType.isNull());
5323 if (UnderlyingType.isNull())
5324 UnderlyingType = DeclUnderlyingType;
5325 else
5326 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5327 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5328 } else {
5329 // FIXME: This is a workaround for a serialization cycle: assume the decl
5330 // underlying type is not available; don't touch it.
5331 assert(!UnderlyingType.isNull());
5332 }
5333
5334 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5335 *TypeMatchesDeclOrNone) {
5336 if (Decl->TypeForDecl)
5337 return QualType(Decl->TypeForDecl, 0);
5338
5339 auto *NewType = new (*this, alignof(TypedefType))
5340 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5341 !*TypeMatchesDeclOrNone);
5342
5343 Types.push_back(NewType);
5344 Decl->TypeForDecl = NewType;
5345 return QualType(NewType, 0);
5346 }
5347
5348 llvm::FoldingSetNodeID ID;
5349 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5350 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5351
5352 llvm::FoldingSetInsertToken Token;
5353 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5354 TypedefTypes.lookup(ID, Token))
5355 return QualType(Placeholder->getType(), 0);
5356
5357 void *Mem =
5358 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5360 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5361 alignof(TypedefType));
5362 auto *NewType =
5363 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5364 UnderlyingType, !*TypeMatchesDeclOrNone);
5365 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5367 TypedefTypes.insert(Placeholder, Token);
5368 Types.push_back(NewType);
5369 return QualType(NewType, 0);
5370}
5371
5373 NestedNameSpecifier Qualifier,
5374 const UsingShadowDecl *D,
5375 QualType UnderlyingType) const {
5376 // FIXME: This is expensive to compute every time!
5377 if (UnderlyingType.isNull()) {
5378 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5379 UnderlyingType =
5382 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5383 }
5384
5385 llvm::FoldingSetNodeID ID;
5386 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5387
5388 llvm::FoldingSetInsertToken Token;
5389 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5390 return QualType(T, 0);
5391
5392 assert(!UnderlyingType.hasLocalQualifiers());
5393
5394 assert(
5396 UnderlyingType));
5397
5398 void *Mem =
5399 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5400 alignof(UsingType));
5401 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5402 Types.push_back(T);
5403 UsingTypes.insert(T, Token);
5404 return QualType(T, 0);
5405}
5406
5407TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5408 NestedNameSpecifier Qualifier,
5409 const TagDecl *TD, bool OwnsTag,
5410 bool IsInjected,
5411 const Type *CanonicalType,
5412 bool WithFoldingSetNode) const {
5413 auto [TC, Size] = [&] {
5414 switch (TD->getDeclKind()) {
5415 case Decl::Enum:
5416 static_assert(alignof(EnumType) == alignof(TagType));
5417 return std::make_tuple(Type::Enum, sizeof(EnumType));
5418 case Decl::ClassTemplatePartialSpecialization:
5419 case Decl::ClassTemplateSpecialization:
5420 case Decl::CXXRecord:
5421 static_assert(alignof(RecordType) == alignof(TagType));
5422 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5423 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5424 return std::make_tuple(Type::InjectedClassName,
5425 sizeof(InjectedClassNameType));
5426 [[fallthrough]];
5427 case Decl::Record:
5428 return std::make_tuple(Type::Record, sizeof(RecordType));
5429 default:
5430 llvm_unreachable("unexpected decl kind");
5431 }
5432 }();
5433
5434 if (Qualifier) {
5435 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5436 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5437 sizeof(NestedNameSpecifier);
5438 }
5439 void *Mem;
5440 if (WithFoldingSetNode) {
5441 // FIXME: It would be more profitable to tail allocate the folding set node
5442 // from the type, instead of the other way around, due to the greater
5443 // alignment requirements of the type. But this makes it harder to deal with
5444 // the different type node sizes. This would require either uniquing from
5445 // different folding sets, or having the folding setaccept a
5446 // contextual parameter which is not fixed at construction.
5447 Mem = Allocate(
5448 sizeof(TagTypeFoldingSetPlaceholder) +
5449 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5450 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5451 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5452 Mem = T->getTagType();
5453 } else {
5454 Mem = Allocate(Size, alignof(TagType));
5455 }
5456
5457 auto *T = [&, TC = TC]() -> TagType * {
5458 switch (TC) {
5459 case Type::Enum: {
5460 assert(isa<EnumDecl>(TD));
5461 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5462 IsInjected, CanonicalType);
5463 assert(reinterpret_cast<void *>(T) ==
5464 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5465 "TagType must be the first base of EnumType");
5466 return T;
5467 }
5468 case Type::Record: {
5469 assert(isa<RecordDecl>(TD));
5470 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5471 IsInjected, CanonicalType);
5472 assert(reinterpret_cast<void *>(T) ==
5473 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5474 "TagType must be the first base of RecordType");
5475 return T;
5476 }
5477 case Type::InjectedClassName: {
5478 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5479 IsInjected, CanonicalType);
5480 assert(reinterpret_cast<void *>(T) ==
5481 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5482 "TagType must be the first base of InjectedClassNameType");
5483 return T;
5484 }
5485 default:
5486 llvm_unreachable("unexpected type class");
5487 }
5488 }();
5489 assert(T->getKeyword() == Keyword);
5490 assert(T->getQualifier() == Qualifier);
5491 assert(T->getDecl() == TD);
5492 assert(T->isInjected() == IsInjected);
5493 assert(T->isTagOwned() == OwnsTag);
5494 assert((T->isCanonicalUnqualified()
5495 ? QualType()
5496 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5497 Types.push_back(T);
5498 return T;
5499}
5500
5501static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5502 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5503 RD && RD->isInjectedClassName())
5504 return cast<TagDecl>(RD->getDeclContext());
5505 return TD;
5506}
5507
5510 if (TD->TypeForDecl)
5511 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5512
5513 const Type *CanonicalType = getTagTypeInternal(
5515 /*Qualifier=*/std::nullopt, TD,
5516 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5517 /*WithFoldingSetNode=*/false);
5518 TD->TypeForDecl = CanonicalType;
5519 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5520}
5521
5523 NestedNameSpecifier Qualifier,
5524 const TagDecl *TD, bool OwnsTag) const {
5525
5526 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5527 bool IsInjected = TD != NonInjectedTD;
5528
5529 ElaboratedTypeKeyword PreferredKeyword =
5532 NonInjectedTD->getTagKind());
5533
5534 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5535 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5536 return QualType(T, 0);
5537
5538 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5539 const Type *T =
5540 getTagTypeInternal(Keyword,
5541 /*Qualifier=*/std::nullopt, NonInjectedTD,
5542 /*OwnsTag=*/false, IsInjected, CanonicalType,
5543 /*WithFoldingSetNode=*/false);
5544 TD->TypeForDecl = T;
5545 return QualType(T, 0);
5546 }
5547
5548 llvm::FoldingSetNodeID ID;
5549 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5550 OwnsTag, IsInjected);
5551
5552 llvm::FoldingSetInsertToken Token;
5553 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5554 return QualType(T->getTagType(), 0);
5555
5556 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5557 TagType *T =
5558 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5559 CanonicalType, /*WithFoldingSetNode=*/true);
5560 TagTypes.insert(TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5561 return QualType(T, 0);
5562}
5563
5564bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5565 unsigned NumPositiveBits,
5566 QualType &BestType,
5567 QualType &BestPromotionType) {
5568 unsigned IntWidth = Target->getIntWidth();
5569 unsigned CharWidth = Target->getCharWidth();
5570 unsigned ShortWidth = Target->getShortWidth();
5571 bool EnumTooLarge = false;
5572 unsigned BestWidth;
5573 if (NumNegativeBits) {
5574 // If there is a negative value, figure out the smallest integer type (of
5575 // int/long/longlong) that fits.
5576 // If it's packed, check also if it fits a char or a short.
5577 if (IsPacked && NumNegativeBits <= CharWidth &&
5578 NumPositiveBits < CharWidth) {
5579 BestType = SignedCharTy;
5580 BestWidth = CharWidth;
5581 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5582 NumPositiveBits < ShortWidth) {
5583 BestType = ShortTy;
5584 BestWidth = ShortWidth;
5585 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5586 BestType = IntTy;
5587 BestWidth = IntWidth;
5588 } else {
5589 BestWidth = Target->getLongWidth();
5590
5591 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5592 BestType = LongTy;
5593 } else {
5594 BestWidth = Target->getLongLongWidth();
5595
5596 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5597 EnumTooLarge = true;
5598 BestType = LongLongTy;
5599 }
5600 }
5601 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5602 } else {
5603 // If there is no negative value, figure out the smallest type that fits
5604 // all of the enumerator values.
5605 // If it's packed, check also if it fits a char or a short.
5606 if (IsPacked && NumPositiveBits <= CharWidth) {
5607 BestType = UnsignedCharTy;
5608 BestPromotionType = IntTy;
5609 BestWidth = CharWidth;
5610 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5611 BestType = UnsignedShortTy;
5612 BestPromotionType = IntTy;
5613 BestWidth = ShortWidth;
5614 } else if (NumPositiveBits <= IntWidth) {
5615 BestType = UnsignedIntTy;
5616 BestWidth = IntWidth;
5617 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5619 : IntTy;
5620 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5621 BestType = UnsignedLongTy;
5622 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5624 : LongTy;
5625 } else {
5626 BestWidth = Target->getLongLongWidth();
5627 if (NumPositiveBits > BestWidth) {
5628 // This can happen with bit-precise integer types, but those are not
5629 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5630 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5631 // a 128-bit integer, we should consider doing the same.
5632 EnumTooLarge = true;
5633 }
5634 BestType = UnsignedLongLongTy;
5635 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5637 : LongLongTy;
5638 }
5639 }
5640 return EnumTooLarge;
5641}
5642
5644 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5645 "Integral type required!");
5646 unsigned BitWidth = getIntWidth(T);
5647
5648 if (Value.isUnsigned() || Value.isNonNegative()) {
5649 if (T->isSignedIntegerOrEnumerationType())
5650 --BitWidth;
5651 return Value.getActiveBits() <= BitWidth;
5652 }
5653 return Value.getSignificantBits() <= BitWidth;
5654}
5655
5656UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5658 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5659 const Type *CanonicalType) const {
5660 void *Mem = Allocate(
5661 UnresolvedUsingType::totalSizeToAlloc<
5663 !!Token, !!Qualifier),
5664 alignof(UnresolvedUsingType));
5665 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5666 if (Token) {
5667 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5669 UnresolvedUsingTypes.insert(Placeholder, Token);
5670 }
5671 Types.push_back(T);
5672 return T;
5673}
5674
5676 const UnresolvedUsingTypenameDecl *D) const {
5677 D = D->getCanonicalDecl();
5678 if (D->TypeForDecl)
5679 return D->TypeForDecl->getCanonicalTypeUnqualified();
5680
5681 const Type *CanonicalType =
5682 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5683 /*Qualifier=*/std::nullopt, D,
5684 /*Token=*/{}, /*CanonicalType=*/nullptr);
5685 D->TypeForDecl = CanonicalType;
5686 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5687}
5688
5691 NestedNameSpecifier Qualifier,
5692 const UnresolvedUsingTypenameDecl *D) const {
5693 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5694 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5695 return QualType(T, 0);
5696
5697 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5698 const Type *T =
5699 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5700 /*Qualifier=*/std::nullopt, D,
5701 /*Token=*/{}, CanonicalType);
5702 D->TypeForDecl = T;
5703 return QualType(T, 0);
5704 }
5705
5706 llvm::FoldingSetNodeID ID;
5707 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5708
5709 llvm::FoldingSetInsertToken Token;
5711 UnresolvedUsingTypes.lookup(ID, Token))
5712 return QualType(Placeholder->getType(), 0);
5713 assert(Token);
5714
5715 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5716 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5717 CanonicalType);
5718 return QualType(T, 0);
5719}
5720
5722 QualType modifiedType,
5723 QualType equivalentType,
5724 const Attr *attr) const {
5725 llvm::FoldingSetNodeID id;
5726 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5727 attr);
5728
5729 llvm::FoldingSetInsertToken Token;
5730 AttributedType *type = AttributedTypes.lookup(id, Token);
5731 if (type) return QualType(type, 0);
5732
5733 assert(!attr || attr->getKind() == attrKind);
5734
5735 QualType canon = getCanonicalType(equivalentType);
5736 type = new (*this, alignof(AttributedType))
5737 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5738
5739 Types.push_back(type);
5740 AttributedTypes.insert(type, Token);
5741
5742 return QualType(type, 0);
5743}
5744
5746 QualType equivalentType) const {
5747 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5748}
5749
5751 QualType modifiedType,
5752 QualType equivalentType) const {
5753 switch (nullability) {
5755 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5756
5758 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5759
5761 return getAttributedType(attr::TypeNullableResult, modifiedType,
5762 equivalentType);
5763
5765 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5766 equivalentType);
5767 }
5768
5769 llvm_unreachable("Unknown nullability kind");
5770}
5771
5772QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5773 QualType Wrapped) const {
5774 llvm::FoldingSetNodeID ID;
5775 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5776
5777 llvm::FoldingSetInsertToken Token;
5778 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5779 if (Ty)
5780 return QualType(Ty, 0);
5781
5782 QualType Canon = getCanonicalType(Wrapped);
5783 Ty = new (*this, alignof(BTFTagAttributedType))
5784 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5785
5786 Types.push_back(Ty);
5787 BTFTagAttributedTypes.insert(Ty, Token);
5788
5789 return QualType(Ty, 0);
5790}
5791
5793 QualType Underlying) const {
5794 const IdentifierInfo *II = Attr->getBehaviorKind();
5795 StringRef IdentName = II->getName();
5796 OverflowBehaviorType::OverflowBehaviorKind Kind;
5797 if (IdentName == "wrap") {
5798 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5799 } else if (IdentName == "trap") {
5800 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5801 } else {
5802 return Underlying;
5803 }
5804
5805 return getOverflowBehaviorType(Kind, Underlying);
5806}
5807
5809 OverflowBehaviorType::OverflowBehaviorKind Kind,
5810 QualType Underlying) const {
5811 assert(!Underlying->isOverflowBehaviorType() &&
5812 "Cannot have underlying types that are themselves OBTs");
5813 llvm::FoldingSetNodeID ID;
5814 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5815 llvm::FoldingSetInsertToken Token;
5816
5817 if (OverflowBehaviorType *OBT = OverflowBehaviorTypes.lookup(ID, Token)) {
5818 return QualType(OBT, 0);
5819 }
5820
5821 QualType Canonical;
5822 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5823 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5824 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5825 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5826 assert(!OverflowBehaviorTypes.lookup(ID, Token) &&
5827 "Shouldn't be in the map");
5828 }
5829
5830 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5831 OverflowBehaviorType(Canonical, Underlying, Kind);
5832
5833 Types.push_back(Ty);
5834 OverflowBehaviorTypes.insert(Ty, Token);
5835 return QualType(Ty, 0);
5836}
5837
5839 QualType Wrapped, QualType Contained,
5840 const HLSLAttributedResourceType::Attributes &Attrs) {
5841
5842 llvm::FoldingSetNodeID ID;
5843 HLSLAttributedResourceType::Profile(ID, *this, Wrapped, Contained, Attrs);
5844
5845 llvm::FoldingSetInsertToken Token;
5846 HLSLAttributedResourceType *Ty =
5847 HLSLAttributedResourceTypes.lookup(ID, Token);
5848 if (Ty)
5849 return QualType(Ty, 0);
5850
5851 Ty = new (*this, alignof(HLSLAttributedResourceType))
5852 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5853
5854 Types.push_back(Ty);
5855 HLSLAttributedResourceTypes.insert(Ty, Token);
5856
5857 return QualType(Ty, 0);
5858}
5859
5860QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5861 uint32_t Alignment,
5862 ArrayRef<SpirvOperand> Operands) {
5863 llvm::FoldingSetNodeID ID;
5864 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5865
5866 llvm::FoldingSetInsertToken Token;
5867 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5868 if (Ty)
5869 return QualType(Ty, 0);
5870
5871 void *Mem = Allocate(
5872 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5873 alignof(HLSLInlineSpirvType));
5874
5875 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5876
5877 Types.push_back(Ty);
5878 HLSLInlineSpirvTypes.insert(Ty, Token);
5879
5880 return QualType(Ty, 0);
5881}
5882
5883/// Retrieve a substitution-result type.
5885 Decl *AssociatedDecl,
5886 unsigned Index,
5888 bool Final) const {
5889 auto Key =
5890 std::make_tuple(Replacement, AssociatedDecl, Index,
5891 PackIndex.toInternalRepresentation(), unsigned(Final));
5892 llvm::FoldingSetInsertToken Token;
5893 SubstTemplateTypeParmType *SubstParm =
5894 SubstTemplateTypeParmTypes.lookup(Key, Token);
5895
5896 if (!SubstParm) {
5897 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5898 !Replacement.isCanonical()),
5899 alignof(SubstTemplateTypeParmType));
5900 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5901 Index, PackIndex, Final);
5902 Types.push_back(SubstParm);
5903 SubstTemplateTypeParmTypes.insert(SubstParm, Token);
5904 }
5905
5906 return QualType(SubstParm, 0);
5907}
5908
5911 unsigned Index, bool Final,
5912 const TemplateArgument &ArgPack) {
5913#ifndef NDEBUG
5914 for (const auto &P : ArgPack.pack_elements())
5915 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5916#endif
5917
5918 llvm::FoldingSetNodeID ID;
5919 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5920 ArgPack);
5921 llvm::FoldingSetInsertToken Token;
5922 if (SubstTemplateTypeParmPackType *SubstParm =
5923 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
5924 return QualType(SubstParm, 0);
5925
5926 QualType Canon;
5927 {
5928 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5929 if (!AssociatedDecl->isCanonicalDecl() ||
5930 !CanonArgPack.structurallyEquals(ArgPack)) {
5932 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5933 [[maybe_unused]] const auto *Nothing =
5934 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
5935 assert(!Nothing);
5936 }
5937 }
5938
5939 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
5940 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
5941 ArgPack);
5942 Types.push_back(SubstParm);
5943 SubstTemplateTypeParmPackTypes.insert(SubstParm, Token);
5944 return QualType(SubstParm, 0);
5945}
5946
5949 assert(llvm::all_of(ArgPack.pack_elements(),
5950 [](const auto &P) {
5951 return P.getKind() == TemplateArgument::Type;
5952 }) &&
5953 "Pack contains a non-type");
5954
5955 llvm::FoldingSetNodeID ID;
5956 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
5957
5958 llvm::FoldingSetInsertToken Token;
5959 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
5960 return QualType(T, 0);
5961
5962 QualType Canon;
5963 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5964 if (!CanonArgPack.structurallyEquals(ArgPack)) {
5965 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
5966 // Refresh Token, in case the recursive call above caused rehashing,
5967 // which would invalidate the bucket pointer.
5968 [[maybe_unused]] const auto *Nothing =
5969 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
5970 assert(!Nothing);
5971 }
5972
5973 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
5974 SubstBuiltinTemplatePackType(Canon, ArgPack);
5975 Types.push_back(PackType);
5976 SubstBuiltinTemplatePackTypes.insert(PackType, Token);
5977 return QualType(PackType, 0);
5978}
5979
5980/// Retrieve the template type parameter type for a template
5981/// parameter or parameter pack with the given depth, index, and (optionally)
5982/// name.
5984ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
5985 TemplateTypeParmDecl *TTPDecl) const {
5986 assert(Depth >= 0 && "Depth must be non-negative");
5987 assert(Index >= 0 && "Index must be non-negative");
5988
5989 auto Key = std::make_tuple(unsigned(Depth), unsigned(Index),
5990 unsigned(ParameterPack), TTPDecl);
5991 llvm::FoldingSetInsertToken Token;
5992 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
5993
5994 if (TypeParm)
5995 return QualType(TypeParm, 0);
5996
5997 if (TTPDecl) {
5998 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
5999 TypeParm = new (*this, alignof(TemplateTypeParmType))
6000 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6001 } else
6002 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6003 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6004
6005 Types.push_back(TypeParm);
6006 TemplateTypeParmTypes.insert(TypeParm, Token);
6007
6008 return QualType(TypeParm, 0);
6009}
6010
6013 switch (Keyword) {
6014 // These are just themselves.
6020 return Keyword;
6021
6022 // These are equivalent.
6025
6026 // These are functionally equivalent, so relying on their equivalence is
6027 // IFNDR. By making them equivalent, we disallow overloading, which at least
6028 // can produce a diagnostic.
6031 }
6032 llvm_unreachable("unexpected keyword kind");
6033}
6034
6036 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6037 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6038 TemplateName Name, SourceLocation NameLoc,
6039 const TemplateArgumentListInfo &SpecifiedArgs,
6040 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6042 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6043
6046 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6047 SpecifiedArgs);
6048 return TSI;
6049}
6050
6053 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6054 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6055 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6056 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6057 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6058 SpecifiedArgVec.push_back(Arg.getArgument());
6059
6060 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6061 CanonicalArgs, Underlying);
6062}
6063
6064[[maybe_unused]] static bool
6066 for (const TemplateArgument &Arg : Args)
6067 if (Arg.isPackExpansion())
6068 return true;
6069 return false;
6070}
6071
6074 ArrayRef<TemplateArgument> Args) const {
6075 assert(Template ==
6076 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6078 Template.getAsDependentTemplateName()));
6079#ifndef NDEBUG
6080 for (const auto &Arg : Args)
6081 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6082#endif
6083
6084 llvm::FoldingSetNodeID ID;
6085 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6086 *this);
6087 llvm::FoldingSetInsertToken Token;
6088 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6089 return QualType(T, 0);
6090
6091 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6092 sizeof(TemplateArgument) * Args.size(),
6093 alignof(TemplateSpecializationType));
6094 auto *Spec =
6095 new (Mem) TemplateSpecializationType(Keyword, Template,
6096 /*IsAlias=*/false, Args, QualType());
6097 assert(Spec->isDependentType() &&
6098 "canonical template specialization must be dependent");
6099 Types.push_back(Spec);
6100 TemplateSpecializationTypes.insert(Spec, Token);
6101 return QualType(Spec, 0);
6102}
6103
6106 ArrayRef<TemplateArgument> SpecifiedArgs,
6107 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6108 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6109 bool IsTypeAlias = TD && TD->isTypeAlias();
6110 if (Underlying.isNull()) {
6111 TemplateName CanonTemplate =
6112 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6113 ElaboratedTypeKeyword CanonKeyword =
6114 CanonTemplate.getAsDependentTemplateName()
6117 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6119 if (CanonicalArgs.empty()) {
6120 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6121 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6122 CanonicalArgs = CanonArgsVec;
6123 } else {
6124 NonCanonical |= !llvm::equal(
6125 SpecifiedArgs, CanonicalArgs,
6126 [](const TemplateArgument &A, const TemplateArgument &B) {
6127 return A.structurallyEquals(B);
6128 });
6129 }
6130
6131 // We can get here with an alias template when the specialization
6132 // contains a pack expansion that does not match up with a parameter
6133 // pack, or a builtin template which cannot be resolved due to dependency.
6134 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6135 hasAnyPackExpansions(CanonicalArgs)) &&
6136 "Caller must compute aliased type");
6137 IsTypeAlias = false;
6138
6140 CanonKeyword, CanonTemplate, CanonicalArgs);
6141 if (!NonCanonical)
6142 return Underlying;
6143 }
6144 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6145 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6146 (IsTypeAlias ? sizeof(QualType) : 0),
6147 alignof(TemplateSpecializationType));
6148 auto *Spec = new (Mem) TemplateSpecializationType(
6149 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6150 Types.push_back(Spec);
6151 return QualType(Spec, 0);
6152}
6153
6156 llvm::FoldingSetInsertToken Token;
6157 ParenType *T = ParenTypes.lookup(InnerType, Token);
6158 if (T)
6159 return QualType(T, 0);
6160
6161 QualType Canon = InnerType;
6162 if (!Canon.isCanonical()) {
6163 Canon = getCanonicalType(InnerType);
6164 assert(!ParenTypes.lookup(InnerType, Token) &&
6165 "Paren canonical type broken");
6166 }
6167
6168 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6169 Types.push_back(T);
6170 ParenTypes.insert(T, Token);
6171 return QualType(T, 0);
6172}
6173
6176 const IdentifierInfo *MacroII) const {
6177 QualType Canon = UnderlyingTy;
6178 if (!Canon.isCanonical())
6179 Canon = getCanonicalType(UnderlyingTy);
6180
6181 auto *newType = new (*this, alignof(MacroQualifiedType))
6182 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6183 Types.push_back(newType);
6184 return QualType(newType, 0);
6185}
6186
6189 const IdentifierInfo *Name) const {
6190 llvm::FoldingSetNodeID ID;
6191 DependentNameType::Profile(ID, Keyword, NNS, Name);
6192
6193 llvm::FoldingSetInsertToken Token;
6194 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6195 return QualType(T, 0);
6196
6197 ElaboratedTypeKeyword CanonKeyword =
6199 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6200
6201 QualType Canon;
6202 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6203 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6204 [[maybe_unused]] DependentNameType *T =
6205 DependentNameTypes.lookup(ID, Token);
6206 assert(!T && "broken canonicalization");
6207 assert(Canon.isCanonical());
6208 }
6209
6210 DependentNameType *T = new (*this, alignof(DependentNameType))
6211 DependentNameType(Keyword, NNS, Name, Canon);
6212 Types.push_back(T);
6213 DependentNameTypes.insert(T, Token);
6214 return QualType(T, 0);
6215}
6216
6218 TemplateArgument Arg;
6219 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6221 if (TTP->isParameterPack())
6222 ArgType = getPackExpansionType(ArgType, std::nullopt);
6223
6225 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6226 QualType T =
6227 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6228 // For class NTTPs, ensure we include the 'const' so the type matches that
6229 // of a real template argument.
6230 // FIXME: It would be more faithful to model this as something like an
6231 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6233 if (T->isRecordType()) {
6234 // C++ [temp.param]p8: An id-expression naming a non-type
6235 // template-parameter of class type T denotes a static storage duration
6236 // object of type const T.
6237 T.addConst();
6238 VK = VK_LValue;
6239 } else {
6240 VK = Expr::getValueKindForType(NTTP->getType());
6241 }
6242 Expr *E = new (*this)
6243 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6244 T, VK, NTTP->getLocation());
6245
6246 if (NTTP->isParameterPack())
6247 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6248 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6249 } else {
6250 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6252 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6253 TemplateName(TTP));
6254 if (TTP->isParameterPack())
6255 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6256 else
6257 Arg = TemplateArgument(Name);
6258 }
6259
6260 if (Param->isTemplateParameterPack())
6261 Arg =
6262 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6263
6264 return Arg;
6265}
6266
6268 UnsignedOrNone NumExpansions,
6269 bool ExpectPackInType) const {
6270 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6271 "Pack expansions must expand one or more parameter packs");
6272
6273 auto Key = std::make_pair(Pattern, NumExpansions.toInternalRepresentation());
6274
6275 llvm::FoldingSetInsertToken Token;
6276 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6277 if (T)
6278 return QualType(T, 0);
6279
6280 QualType Canon;
6281 if (!Pattern.isCanonical()) {
6282 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6283 /*ExpectPackInType=*/false);
6284
6285 // Find the insert position again, in case we inserted an element into
6286 // PackExpansionTypes and invalidated our insert position.
6287 PackExpansionTypes.lookup(Key, Token);
6288 }
6289
6290 T = new (*this, alignof(PackExpansionType))
6291 PackExpansionType(Pattern, Canon, NumExpansions);
6292 Types.push_back(T);
6293 PackExpansionTypes.insert(T, Token);
6294 return QualType(T, 0);
6295}
6296
6297/// CmpProtocolNames - Comparison predicate for sorting protocols
6298/// alphabetically.
6299static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6300 ObjCProtocolDecl *const *RHS) {
6301 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6302}
6303
6305 if (Protocols.empty()) return true;
6306
6307 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6308 return false;
6309
6310 for (unsigned i = 1; i != Protocols.size(); ++i)
6311 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6312 Protocols[i]->getCanonicalDecl() != Protocols[i])
6313 return false;
6314 return true;
6315}
6316
6317static void
6319 // Sort protocols, keyed by name.
6320 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6321
6322 // Canonicalize.
6323 for (ObjCProtocolDecl *&P : Protocols)
6324 P = P->getCanonicalDecl();
6325
6326 // Remove duplicates.
6327 auto ProtocolsEnd = llvm::unique(Protocols);
6328 Protocols.erase(ProtocolsEnd, Protocols.end());
6329}
6330
6332 ObjCProtocolDecl * const *Protocols,
6333 unsigned NumProtocols) const {
6334 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6335 /*isKindOf=*/false);
6336}
6337
6339 QualType baseType,
6340 ArrayRef<QualType> typeArgs,
6342 bool isKindOf) const {
6343 // If the base type is an interface and there aren't any protocols or
6344 // type arguments to add, then the interface type will do just fine.
6345 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6346 isa<ObjCInterfaceType>(baseType))
6347 return baseType;
6348
6349 // Look in the folding set for an existing type.
6350 llvm::FoldingSetNodeID ID;
6351 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6352 llvm::FoldingSetInsertToken Token;
6353 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6354 return QualType(QT, 0);
6355
6356 // Determine the type arguments to be used for canonicalization,
6357 // which may be explicitly specified here or written on the base
6358 // type.
6359 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6360 if (effectiveTypeArgs.empty()) {
6361 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6362 effectiveTypeArgs = baseObject->getTypeArgs();
6363 }
6364
6365 // Build the canonical type, which has the canonical base type and a
6366 // sorted-and-uniqued list of protocols and the type arguments
6367 // canonicalized.
6368 QualType canonical;
6369 bool typeArgsAreCanonical = llvm::all_of(
6370 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6371 bool protocolsSorted = areSortedAndUniqued(protocols);
6372 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6373 // Determine the canonical type arguments.
6374 ArrayRef<QualType> canonTypeArgs;
6375 SmallVector<QualType, 4> canonTypeArgsVec;
6376 if (!typeArgsAreCanonical) {
6377 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6378 for (auto typeArg : effectiveTypeArgs)
6379 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6380 canonTypeArgs = canonTypeArgsVec;
6381 } else {
6382 canonTypeArgs = effectiveTypeArgs;
6383 }
6384
6385 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6386 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6387 if (!protocolsSorted) {
6388 canonProtocolsVec.append(protocols.begin(), protocols.end());
6389 SortAndUniqueProtocols(canonProtocolsVec);
6390 canonProtocols = canonProtocolsVec;
6391 } else {
6392 canonProtocols = protocols;
6393 }
6394
6395 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6396 canonProtocols, isKindOf);
6397
6398 // Regenerate Token.
6399 ObjCObjectTypes.lookup(ID, Token);
6400 }
6401
6402 unsigned size = sizeof(ObjCObjectTypeImpl);
6403 size += typeArgs.size() * sizeof(QualType);
6404 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6405 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6406 auto *T =
6407 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6408 isKindOf);
6409
6410 Types.push_back(T);
6411 ObjCObjectTypes.insert(T, Token);
6412 return QualType(T, 0);
6413}
6414
6415/// Apply Objective-C protocol qualifiers to the given type.
6416/// If this is for the canonical type of a type parameter, we can apply
6417/// protocol qualifiers on the ObjCObjectPointerType.
6420 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6421 bool allowOnPointerType) const {
6422 hasError = false;
6423
6424 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6425 return getObjCTypeParamType(objT->getDecl(), protocols);
6426 }
6427
6428 // Apply protocol qualifiers to ObjCObjectPointerType.
6429 if (allowOnPointerType) {
6430 if (const auto *objPtr =
6431 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6432 const ObjCObjectType *objT = objPtr->getObjectType();
6433 // Merge protocol lists and construct ObjCObjectType.
6435 protocolsVec.append(objT->qual_begin(),
6436 objT->qual_end());
6437 protocolsVec.append(protocols.begin(), protocols.end());
6438 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6440 objT->getBaseType(),
6441 objT->getTypeArgsAsWritten(),
6442 protocols,
6443 objT->isKindOfTypeAsWritten());
6445 }
6446 }
6447
6448 // Apply protocol qualifiers to ObjCObjectType.
6449 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6450 // FIXME: Check for protocols to which the class type is already
6451 // known to conform.
6452
6453 return getObjCObjectType(objT->getBaseType(),
6454 objT->getTypeArgsAsWritten(),
6455 protocols,
6456 objT->isKindOfTypeAsWritten());
6457 }
6458
6459 // If the canonical type is ObjCObjectType, ...
6460 if (type->isObjCObjectType()) {
6461 // Silently overwrite any existing protocol qualifiers.
6462 // TODO: determine whether that's the right thing to do.
6463
6464 // FIXME: Check for protocols to which the class type is already
6465 // known to conform.
6466 return getObjCObjectType(type, {}, protocols, false);
6467 }
6468
6469 // id<protocol-list>
6470 if (type->isObjCIdType()) {
6471 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6472 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6473 objPtr->isKindOfType());
6475 }
6476
6477 // Class<protocol-list>
6478 if (type->isObjCClassType()) {
6479 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6480 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6481 objPtr->isKindOfType());
6483 }
6484
6485 hasError = true;
6486 return type;
6487}
6488
6491 ArrayRef<ObjCProtocolDecl *> protocols) const {
6492 // We canonicalize to the underlying type.
6493 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6494 if (!protocols.empty()) {
6495 // Apply the protocol qualifers.
6496 bool hasError;
6498 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6499 assert(!hasError && "Error when apply protocol qualifier to bound type");
6500 }
6501
6502 // Key on the canonical type the node is constructed with, which is what
6503 // Profile() reports; the decl's underlying type can be updated later.
6504 auto Key = std::make_tuple(Decl, Canonical, protocols);
6505 llvm::FoldingSetInsertToken Token;
6506 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6507 return QualType(TypeParam, 0);
6508
6509 unsigned size = sizeof(ObjCTypeParamType);
6510 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6511 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6512 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6513
6514 Types.push_back(newType);
6515 ObjCTypeParamTypes.insert(newType, Token);
6516 return QualType(newType, 0);
6517}
6518
6520 ObjCTypeParamDecl *New) const {
6521 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6522 // Update TypeForDecl after updating TypeSourceInfo.
6523 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6525 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6526 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6527 New->TypeForDecl = UpdatedTy.getTypePtr();
6528}
6529
6530/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6531/// protocol list adopt all protocols in QT's qualified-id protocol
6532/// list.
6534 ObjCInterfaceDecl *IC) {
6535 if (!QT->isObjCQualifiedIdType())
6536 return false;
6537
6538 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6539 // If both the right and left sides have qualifiers.
6540 for (auto *Proto : OPT->quals()) {
6541 if (!IC->ClassImplementsProtocol(Proto, false))
6542 return false;
6543 }
6544 return true;
6545 }
6546 return false;
6547}
6548
6549/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6550/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6551/// of protocols.
6553 ObjCInterfaceDecl *IDecl) {
6554 if (!QT->isObjCQualifiedIdType())
6555 return false;
6556 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6557 if (!OPT)
6558 return false;
6559 if (!IDecl->hasDefinition())
6560 return false;
6562 CollectInheritedProtocols(IDecl, InheritedProtocols);
6563 if (InheritedProtocols.empty())
6564 return false;
6565 // Check that if every protocol in list of id<plist> conforms to a protocol
6566 // of IDecl's, then bridge casting is ok.
6567 bool Conforms = false;
6568 for (auto *Proto : OPT->quals()) {
6569 Conforms = false;
6570 for (auto *PI : InheritedProtocols) {
6571 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6572 Conforms = true;
6573 break;
6574 }
6575 }
6576 if (!Conforms)
6577 break;
6578 }
6579 if (Conforms)
6580 return true;
6581
6582 for (auto *PI : InheritedProtocols) {
6583 // If both the right and left sides have qualifiers.
6584 bool Adopts = false;
6585 for (auto *Proto : OPT->quals()) {
6586 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6587 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6588 break;
6589 }
6590 if (!Adopts)
6591 return false;
6592 }
6593 return true;
6594}
6595
6596/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6597/// the given object type.
6599 llvm::FoldingSetInsertToken Token;
6600 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(ObjectT, Token))
6601 return QualType(QT, 0);
6602
6603 // Find the canonical object type.
6604 QualType Canonical;
6605 if (!ObjectT.isCanonical())
6606 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6607
6608 // No match.
6609 void *Mem =
6611 auto *QType =
6612 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6613
6614 Types.push_back(QType);
6615 ObjCObjectPointerTypes.insert(QType, Token);
6616 return QualType(QType, 0);
6617}
6618
6619/// getObjCInterfaceType - Return the unique reference to the type for the
6620/// specified ObjC interface decl. The list of protocols is optional.
6622 ObjCInterfaceDecl *PrevDecl) const {
6623 if (Decl->TypeForDecl)
6624 return QualType(Decl->TypeForDecl, 0);
6625
6626 if (PrevDecl) {
6627 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6628 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6629 return QualType(PrevDecl->TypeForDecl, 0);
6630 }
6631
6632 // Prefer the definition, if there is one.
6633 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6634 Decl = Def;
6635
6636 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6637 auto *T = new (Mem) ObjCInterfaceType(Decl);
6638 Decl->TypeForDecl = T;
6639 Types.push_back(T);
6640 return QualType(T, 0);
6641}
6642
6643/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6644/// TypeOfExprType AST's (since expression's are never shared). For example,
6645/// multiple declarations that refer to "typeof(x)" all contain different
6646/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6647/// on canonical type's (which are always unique).
6649 TypeOfExprType *toe;
6650 if (tofExpr->isTypeDependent()) {
6651 llvm::FoldingSetNodeID ID;
6652 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6653 Kind == TypeOfKind::Unqualified);
6654
6655 llvm::FoldingSetInsertToken Token;
6656 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6657 if (Canon) {
6658 // We already have a "canonical" version of an identical, dependent
6659 // typeof(expr) type. Use that as our canonical type.
6660 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6661 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6662 } else {
6663 // Build a new, canonical typeof(expr) type.
6664 Canon = new (*this, alignof(DependentTypeOfExprType))
6665 DependentTypeOfExprType(*this, tofExpr, Kind);
6666 DependentTypeOfExprTypes.insert(Canon, Token);
6667 toe = Canon;
6668 }
6669 } else {
6670 QualType Canonical = getCanonicalType(tofExpr->getType());
6671 toe = new (*this, alignof(TypeOfExprType))
6672 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6673 }
6674 Types.push_back(toe);
6675 return QualType(toe, 0);
6676}
6677
6678/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6679/// TypeOfType nodes. The only motivation to unique these nodes would be
6680/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6681/// an issue. This doesn't affect the type checker, since it operates
6682/// on canonical types (which are always unique).
6684 QualType Canonical = getCanonicalType(tofType);
6685 auto *tot = new (*this, alignof(TypeOfType))
6686 TypeOfType(*this, tofType, Canonical, Kind);
6687 Types.push_back(tot);
6688 return QualType(tot, 0);
6689}
6690
6691/// getReferenceQualifiedType - Given an expr, will return the type for
6692/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6693/// and class member access into account.
6695 // C++11 [dcl.type.simple]p4:
6696 // [...]
6697 QualType T = E->getType();
6698 switch (E->getValueKind()) {
6699 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6700 // type of e;
6701 case VK_XValue:
6702 return getRValueReferenceType(T);
6703 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6704 // type of e;
6705 case VK_LValue:
6706 return getLValueReferenceType(T);
6707 // - otherwise, decltype(e) is the type of e.
6708 case VK_PRValue:
6709 return T;
6710 }
6711 llvm_unreachable("Unknown value kind");
6712}
6713
6714/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6715/// nodes. This would never be helpful, since each such type has its own
6716/// expression, and would not give a significant memory saving, since there
6717/// is an Expr tree under each such type.
6719 // C++11 [temp.type]p2:
6720 // If an expression e involves a template parameter, decltype(e) denotes a
6721 // unique dependent type. Two such decltype-specifiers refer to the same
6722 // type only if their expressions are equivalent (14.5.6.1).
6723 QualType CanonType;
6724 if (!E->isInstantiationDependent()) {
6725 CanonType = getCanonicalType(UnderlyingType);
6726 } else if (!UnderlyingType.isNull()) {
6727 CanonType = getDecltypeType(E, QualType());
6728 } else {
6729 llvm::FoldingSetNodeID ID;
6730 DependentDecltypeType::Profile(ID, *this, E);
6731
6732 llvm::FoldingSetInsertToken Token;
6733 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6734 return QualType(Canon, 0);
6735
6736 // Build a new, canonical decltype(expr) type.
6737 auto *DT =
6738 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6739 DependentDecltypeTypes.insert(DT, Token);
6740 Types.push_back(DT);
6741 return QualType(DT, 0);
6742 }
6743 auto *DT = new (*this, alignof(DecltypeType))
6744 DecltypeType(E, UnderlyingType, CanonType);
6745 Types.push_back(DT);
6746 return QualType(DT, 0);
6747}
6748
6750 bool FullySubstituted,
6751 ArrayRef<QualType> Expansions,
6752 UnsignedOrNone Index) const {
6753 QualType Canonical;
6754 if (FullySubstituted && Index) {
6755 Canonical = getCanonicalType(Expansions[*Index]);
6756 } else {
6757 llvm::FoldingSetNodeID ID;
6758 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6759 FullySubstituted, Expansions);
6760 llvm::FoldingSetInsertToken Token;
6761 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6762 if (!Canon) {
6763 void *Mem = Allocate(
6764 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6766 Canon =
6767 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6768 IndexExpr, FullySubstituted, Expansions);
6769 DependentPackIndexingTypes.insert(Canon, Token);
6770 }
6771 Canonical = QualType(Canon, 0);
6772 }
6773
6774 void *Mem =
6775 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6777 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6778 FullySubstituted, Expansions);
6779 Types.push_back(T);
6780 return QualType(T, 0);
6781}
6782
6783/// getUnaryTransformationType - We don't unique these, since the memory
6784/// savings are minimal and these are rare.
6787 UnaryTransformType::UTTKind Kind) const {
6788 // Clear UnderlyingType for a dependent base before building the ID: that is
6789 // what the node is constructed with, and what Profile() reports.
6790 if (BaseType->isDependentType()) {
6791 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6792 UnderlyingType = QualType();
6793 }
6794
6795 auto Key = std::make_tuple(BaseType, UnderlyingType, Kind);
6796
6797 llvm::FoldingSetInsertToken Token;
6798 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6799 return QualType(UT, 0);
6800
6801 QualType CanonType;
6802 if (!BaseType->isDependentType()) {
6803 CanonType = UnderlyingType.getCanonicalType();
6804 } else {
6805 if (QualType CanonBase = BaseType.getCanonicalType();
6806 BaseType != CanonBase) {
6807 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6808 assert(CanonType.isCanonical());
6809 }
6810 }
6811
6812 auto *UT = new (*this, alignof(UnaryTransformType))
6813 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6814 UnaryTransformTypes.insert(UT, Token);
6815 Types.push_back(UT);
6816 return QualType(UT, 0);
6817}
6818
6819/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6820/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6821/// canonical deduced-but-dependent 'auto' type.
6825 TemplateName TypeConstraintConcept,
6826 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6828 TypeConstraintConcept.isNull()) {
6829 assert(DeducedAsType.isNull() && "");
6830 assert(TypeConstraintArgs.empty() && "");
6831 return getAutoDeductType();
6832 }
6833
6834 // Look in the folding set for an existing type.
6835 llvm::FoldingSetNodeID ID;
6836 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6837 TypeConstraintConcept, TypeConstraintArgs);
6838 if (auto const AT_iter = AutoTypes.find_as(ID); AT_iter != AutoTypes.end())
6839 return QualType(AT_iter->getSecond(), 0);
6840
6841 if (DK == DeducedKind::Deduced) {
6842 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6843 } else {
6844 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6845 if (!TypeConstraintConcept.isNull()) {
6846 bool AnyNonCanonArgs = false;
6847 TemplateName CanonicalConcept =
6848 getCanonicalTemplateName(TypeConstraintConcept);
6849 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6850 *this, TypeConstraintArgs, AnyNonCanonArgs);
6851 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6852 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6853 CanonicalConceptArgs);
6854 }
6855 }
6856
6857 void *Mem = Allocate(sizeof(AutoType) +
6858 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6859 alignof(AutoType));
6860 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6861 TypeConstraintConcept, TypeConstraintArgs);
6862#ifndef NDEBUG
6863 llvm::FoldingSetNodeID InsertedID;
6864 AT->Profile(InsertedID, *this);
6865 assert(InsertedID == ID && "ID does not match");
6866#endif
6867 Types.push_back(AT);
6868 AutoTypes.try_emplace(ID.Intern(BumpAlloc), AT);
6869 return QualType(AT, 0);
6870}
6871
6873 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6874
6875 // Remove a type-constraint from a top-level auto or decltype(auto).
6876 if (auto *AT = CanonT->getAs<AutoType>()) {
6877 if (!AT->isConstrained())
6878 return T;
6879 return getQualifiedType(
6880 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6881 T.getQualifiers());
6882 }
6883
6884 // FIXME: We only support constrained auto at the top level in the type of a
6885 // non-type template parameter at the moment. Once we lift that restriction,
6886 // we'll need to recursively build types containing auto here.
6887 assert(!CanonT->getContainedAutoType() ||
6888 !CanonT->getContainedAutoType()->isConstrained());
6889 return T;
6890}
6891
6892/// Return the uniqued reference to the deduced template specialization type
6893/// which has been deduced to the given type, or to the canonical undeduced
6894/// such type, or the canonical deduced-but-dependent such type.
6897 TemplateName Template) const {
6898 // Look in the folding set for an existing type.
6899 llvm::FoldingSetInsertToken Token;
6900 llvm::FoldingSetNodeID ID;
6901 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6902 Template);
6903 if (DeducedTemplateSpecializationType *DTST =
6904 DeducedTemplateSpecializationTypes.lookup(ID, Token))
6905 return QualType(DTST, 0);
6906
6907 if (DK == DeducedKind::Deduced) {
6908 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6909 } else {
6910 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6911 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
6912 // FIXME: Can this be formed from a DependentTemplateName, such that the
6913 // keyword should be part of the canonical type?
6915 Template != CanonTemplateName) {
6917 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
6918 // Find the insertion position again.
6919 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
6920 DeducedTemplateSpecializationTypes.lookup(ID, Token);
6921 assert(!DTST && "broken canonicalization");
6922 }
6923 }
6924
6925 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
6926 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
6927
6928#ifndef NDEBUG
6929 llvm::FoldingSetNodeID TempID;
6930 DTST->Profile(TempID);
6931 assert(ID == TempID && "ID does not match");
6932#endif
6933 Types.push_back(DTST);
6934 DeducedTemplateSpecializationTypes.insert(DTST, Token);
6935 return QualType(DTST, 0);
6936}
6937
6938/// getAtomicType - Return the uniqued reference to the atomic type for
6939/// the given value type.
6941 // Unique pointers, to guarantee there is only one pointer of a particular
6942 // structure.
6943 llvm::FoldingSetInsertToken Token;
6944 if (AtomicType *AT = AtomicTypes.lookup(T, Token))
6945 return QualType(AT, 0);
6946
6947 // If the atomic value type isn't canonical, this won't be a canonical type
6948 // either, so fill in the canonical type field.
6949 QualType Canonical;
6950 if (!T.isCanonical()) {
6951 Canonical = getAtomicType(getCanonicalType(T));
6952
6953 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
6954 }
6955 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
6956 Types.push_back(New);
6957 AtomicTypes.insert(New, Token);
6958 return QualType(New, 0);
6959}
6960
6961/// getAutoDeductType - Get type pattern for deducing against 'auto'.
6963 if (AutoDeductTy.isNull())
6965 new (*this, alignof(AutoType))
6967 /*TypeConstraintConcept=*/TemplateName(),
6968 /*TypeConstraintArgs=*/{}),
6969 0);
6970 return AutoDeductTy;
6971}
6972
6973/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
6975 if (AutoRRefDeductTy.isNull())
6977 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
6978 return AutoRRefDeductTy;
6979}
6980
6981/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
6982/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
6983/// needs to agree with the definition in <stddef.h>.
6987
6989 return getFromTargetType(Target->getSizeType());
6990}
6991
6992/// Return the unique signed counterpart of the integer type
6993/// corresponding to size_t.
6997
6998/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
6999/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7003
7004/// Return the unique unsigned counterpart of "ptrdiff_t"
7005/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7006/// in the definition of %tu format specifier.
7008 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7009}
7010
7011/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7013 return getFromTargetType(Target->getIntMaxType());
7014}
7015
7016/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7018 return getFromTargetType(Target->getUIntMaxType());
7019}
7020
7021/// getSignedWCharType - Return the type of "signed wchar_t".
7022/// Used when in C++, as a GCC extension.
7024 // FIXME: derive from "Target" ?
7025 return WCharTy;
7026}
7027
7028/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7029/// Used when in C++, as a GCC extension.
7031 // FIXME: derive from "Target" ?
7032 return UnsignedIntTy;
7033}
7034
7036 return getFromTargetType(Target->getIntPtrType());
7037}
7038
7042
7043/// Return the unique type for "pid_t" defined in
7044/// <sys/types.h>. We need this to compute the correct type for vfork().
7046 return getFromTargetType(Target->getProcessIDType());
7047}
7048
7049//===----------------------------------------------------------------------===//
7050// Type Operators
7051//===----------------------------------------------------------------------===//
7052
7054 // Push qualifiers into arrays, and then discard any remaining
7055 // qualifiers.
7056 T = getCanonicalType(T);
7058 const Type *Ty = T.getTypePtr();
7062 } else if (isa<ArrayType>(Ty)) {
7064 } else if (isa<FunctionType>(Ty)) {
7065 Result = getPointerType(QualType(Ty, 0));
7066 } else {
7067 Result = QualType(Ty, 0);
7068 }
7069
7071}
7072
7074 Qualifiers &quals) const {
7075 SplitQualType splitType = type.getSplitUnqualifiedType();
7076
7077 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7078 // the unqualified desugared type and then drops it on the floor.
7079 // We then have to strip that sugar back off with
7080 // getUnqualifiedDesugaredType(), which is silly.
7081 const auto *AT =
7082 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7083
7084 // If we don't have an array, just use the results in splitType.
7085 if (!AT) {
7086 quals = splitType.Quals;
7087 return QualType(splitType.Ty, 0);
7088 }
7089
7090 // Otherwise, recurse on the array's element type.
7091 QualType elementType = AT->getElementType();
7092 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7093
7094 // If that didn't change the element type, AT has no qualifiers, so we
7095 // can just use the results in splitType.
7096 if (elementType == unqualElementType) {
7097 assert(quals.empty()); // from the recursive call
7098 quals = splitType.Quals;
7099 return QualType(splitType.Ty, 0);
7100 }
7101
7102 // Otherwise, add in the qualifiers from the outermost type, then
7103 // build the type back up.
7104 quals.addConsistentQualifiers(splitType.Quals);
7105
7106 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7107 return getConstantArrayType(unqualElementType, CAT->getSize(),
7108 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7109 }
7110
7111 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7112 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7113 }
7114
7115 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7116 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7117 VAT->getSizeModifier(),
7118 VAT->getIndexTypeCVRQualifiers());
7119 }
7120
7121 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7122 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7123 DSAT->getSizeModifier(), 0);
7124}
7125
7126/// Attempt to unwrap two types that may both be array types with the same bound
7127/// (or both be array types of unknown bound) for the purpose of comparing the
7128/// cv-decomposition of two types per C++ [conv.qual].
7129///
7130/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7131/// C++20 [conv.qual], if permitted by the current language mode.
7133 bool AllowPiMismatch) const {
7134 while (true) {
7135 auto *AT1 = getAsArrayType(T1);
7136 if (!AT1)
7137 return;
7138
7139 auto *AT2 = getAsArrayType(T2);
7140 if (!AT2)
7141 return;
7142
7143 // If we don't have two array types with the same constant bound nor two
7144 // incomplete array types, we've unwrapped everything we can.
7145 // C++20 also permits one type to be a constant array type and the other
7146 // to be an incomplete array type.
7147 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7148 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7149 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7150 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7151 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7153 return;
7154 } else if (isa<IncompleteArrayType>(AT1)) {
7155 if (!(isa<IncompleteArrayType>(AT2) ||
7156 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7158 return;
7159 } else {
7160 return;
7161 }
7162
7163 T1 = AT1->getElementType();
7164 T2 = AT2->getElementType();
7165 }
7166}
7167
7168/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7169///
7170/// If T1 and T2 are both pointer types of the same kind, or both array types
7171/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7172/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7173///
7174/// This function will typically be called in a loop that successively
7175/// "unwraps" pointer and pointer-to-member types to compare them at each
7176/// level.
7177///
7178/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7179/// C++20 [conv.qual], if permitted by the current language mode.
7180///
7181/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7182/// pair of types that can't be unwrapped further.
7184 bool AllowPiMismatch) const {
7185 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7186
7187 const auto *T1PtrType = T1->getAs<PointerType>();
7188 const auto *T2PtrType = T2->getAs<PointerType>();
7189 if (T1PtrType && T2PtrType) {
7190 T1 = T1PtrType->getPointeeType();
7191 T2 = T2PtrType->getPointeeType();
7192 return true;
7193 }
7194
7195 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7196 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7197 T1MPType && T2MPType) {
7198 // Compare the qualifiers of the canonical type, as the non-canonical type
7199 // may have qualifiers pointing to a base or derived class.
7200 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7201 return false;
7202 // Get the pointee types of the non-canonical type, in order to preserve
7203 // their sugar.
7204 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7205 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7206 return true;
7207 }
7208
7209 if (getLangOpts().ObjC) {
7210 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7211 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7212 if (T1OPType && T2OPType) {
7213 T1 = T1OPType->getPointeeType();
7214 T2 = T2OPType->getPointeeType();
7215 return true;
7216 }
7217 }
7218
7219 // FIXME: Block pointers, too?
7220
7221 return false;
7222}
7223
7225 while (true) {
7226 Qualifiers Quals;
7227 T1 = getUnqualifiedArrayType(T1, Quals);
7228 T2 = getUnqualifiedArrayType(T2, Quals);
7229 if (hasSameType(T1, T2))
7230 return true;
7231 if (!UnwrapSimilarTypes(T1, T2))
7232 return false;
7233 }
7234}
7235
7237 while (true) {
7238 Qualifiers Quals1, Quals2;
7239 T1 = getUnqualifiedArrayType(T1, Quals1);
7240 T2 = getUnqualifiedArrayType(T2, Quals2);
7241
7242 Quals1.removeCVRQualifiers();
7243 Quals2.removeCVRQualifiers();
7244 if (Quals1 != Quals2)
7245 return false;
7246
7247 if (hasSameType(T1, T2))
7248 return true;
7249
7250 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7251 return false;
7252 }
7253}
7254
7257 SourceLocation NameLoc) const {
7258 switch (Name.getKind()) {
7261 // DNInfo work in progress: CHECKME: what about DNLoc?
7263 NameLoc);
7264
7267 // DNInfo work in progress: CHECKME: what about DNLoc?
7268 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7269 }
7270
7273 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7274 }
7275
7279 DeclarationName DName;
7280 if (const IdentifierInfo *II = TN.getIdentifier()) {
7281 DName = DeclarationNames.getIdentifier(II);
7282 return DeclarationNameInfo(DName, NameLoc);
7283 } else {
7284 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7285 // DNInfo work in progress: FIXME: source locations?
7286 DeclarationNameLoc DNLoc =
7288 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7289 }
7290 }
7291
7295 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7296 NameLoc);
7297 }
7298
7303 NameLoc);
7304 }
7307 NameLoc);
7310 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7311 }
7314 return getNameForTemplate(PI->getPattern(), NameLoc);
7315 }
7316 }
7317
7318 llvm_unreachable("bad template name kind!");
7319}
7320
7321const TemplateArgument *
7323 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7324 if (!TP->hasDefaultArgument())
7325 return nullptr;
7326 return &TP->getDefaultArgument().getArgument();
7327 };
7328 switch (P->getKind()) {
7329 case NamedDecl::TemplateTypeParm:
7330 return handleParam(cast<TemplateTypeParmDecl>(P));
7331 case NamedDecl::NonTypeTemplateParm:
7332 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7333 case NamedDecl::TemplateTemplateParm:
7334 return handleParam(cast<TemplateTemplateParmDecl>(P));
7335 default:
7336 llvm_unreachable("Unexpected template parameter kind");
7337 }
7338}
7339
7341 bool IgnoreDeduced) const {
7342 while (std::optional<TemplateName> UnderlyingOrNone =
7343 Name.desugar(IgnoreDeduced))
7344 Name = *UnderlyingOrNone;
7345
7346 switch (Name.getKind()) {
7349 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7351
7352 // The canonical template name is the canonical template declaration.
7353 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7354 }
7355
7357 // An assumed template is just a name, so it is already canonical.
7358 return Name;
7359
7361 llvm_unreachable("cannot canonicalize overloaded template");
7362
7365 assert(DTN && "Non-dependent template names must refer to template decls.");
7366 NestedNameSpecifier Qualifier = DTN->getQualifier();
7367 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7368 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7369 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7370 /*HasTemplateKeyword=*/true});
7371 return Name;
7372 }
7373
7377 TemplateArgument canonArgPack =
7380 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7381 subst->getIndex(), subst->getFinal());
7382 }
7383
7386 SmallVector<TemplateName, 4> CanonExpansions;
7387 for (TemplateName T : PI->getExpansions())
7388 CanonExpansions.push_back(getCanonicalTemplateName(T, IgnoreDeduced));
7390 getCanonicalTemplateName(PI->getPattern(), IgnoreDeduced),
7391 PI->getIndexExpr(), PI->isFullySubstituted(), CanonExpansions);
7392 }
7394 assert(IgnoreDeduced == false);
7396 DefaultArguments DefArgs = DTS->getDefaultArguments();
7397 TemplateName Underlying = DTS->getUnderlying();
7398
7399 TemplateName CanonUnderlying =
7400 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7401 bool NonCanonical = CanonUnderlying != Underlying;
7402 auto CanonArgs =
7403 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7404
7405 ArrayRef<NamedDecl *> Params =
7406 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7407 assert(CanonArgs.size() <= Params.size());
7408 // A deduced template name which deduces the same default arguments already
7409 // declared in the underlying template is the same template as the
7410 // underlying template. We need need to note any arguments which differ from
7411 // the corresponding declaration. If any argument differs, we must build a
7412 // deduced template name.
7413 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7415 if (!A)
7416 break;
7417 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7418 TemplateArgument &CanonDefArg = CanonArgs[I];
7419 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7420 continue;
7421 // Keep popping from the back any deault arguments which are the same.
7422 if (I == int(CanonArgs.size() - 1))
7423 CanonArgs.pop_back();
7424 NonCanonical = true;
7425 }
7426 return NonCanonical ? getDeducedTemplateName(
7427 CanonUnderlying,
7428 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7429 : Name;
7430 }
7434 llvm_unreachable("always sugar node");
7435 }
7436
7437 llvm_unreachable("bad template name!");
7438}
7439
7441 const TemplateName &Y,
7442 bool IgnoreDeduced) const {
7443 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7444 getCanonicalTemplateName(Y, IgnoreDeduced);
7445}
7446
7448 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7449 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7450 return false;
7452 return false;
7453 return true;
7454}
7455
7456bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7457 if (!XCE != !YCE)
7458 return false;
7459
7460 if (!XCE)
7461 return true;
7462
7463 llvm::FoldingSetNodeID XCEID, YCEID;
7464 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7465 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7466 return XCEID == YCEID;
7467}
7468
7470 const TypeConstraint *YTC) const {
7471 if (!XTC != !YTC)
7472 return false;
7473
7474 if (!XTC)
7475 return true;
7476
7479 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7480 return false;
7483 return false;
7485 if (XTC->getConceptReference()
7487 ->NumTemplateArgs !=
7489 return false;
7490
7491 // Compare slowly by profiling.
7492 //
7493 // We couldn't compare the profiling result for the template
7494 // args here. Consider the following example in different modules:
7495 //
7496 // template <__integer_like _Tp, C<_Tp> Sentinel>
7497 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7498 // return __t;
7499 // }
7500 //
7501 // When we compare the profiling result for `C<_Tp>` in different
7502 // modules, it will compare the type of `_Tp` in different modules.
7503 // However, the type of `_Tp` in different modules refer to different
7504 // types here naturally. So we couldn't compare the profiling result
7505 // for the template args directly.
7508}
7509
7511 const NamedDecl *Y) const {
7512 if (X->getKind() != Y->getKind())
7513 return false;
7514
7515 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7516 auto *TY = cast<TemplateTypeParmDecl>(Y);
7517 if (TX->isParameterPack() != TY->isParameterPack())
7518 return false;
7519 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7520 return false;
7521 return isSameTypeConstraint(TX->getTypeConstraint(),
7522 TY->getTypeConstraint());
7523 }
7524
7525 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7526 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7527 return TX->isParameterPack() == TY->isParameterPack() &&
7528 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7529 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7530 TY->getPlaceholderTypeConstraint());
7531 }
7532
7534 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7535 return TX->isParameterPack() == TY->isParameterPack() &&
7536 isSameTemplateParameterList(TX->getTemplateParameters(),
7537 TY->getTemplateParameters());
7538}
7539
7541 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7542 if (X->size() != Y->size())
7543 return false;
7544
7545 for (unsigned I = 0, N = X->size(); I != N; ++I)
7546 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7547 return false;
7548
7549 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7550}
7551
7553 const NamedDecl *Y) const {
7554 // If the type parameter isn't the same already, we don't need to check the
7555 // default argument further.
7556 if (!isSameTemplateParameter(X, Y))
7557 return false;
7558
7559 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7560 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7561 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7562 return false;
7563
7564 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7565 TTPY->getDefaultArgument().getArgument().getAsType());
7566 }
7567
7568 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7569 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7570 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7571 return false;
7572
7573 Expr *DefaultArgumentX =
7574 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7575 Expr *DefaultArgumentY =
7576 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7577 llvm::FoldingSetNodeID XID, YID;
7578 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7579 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7580 return XID == YID;
7581 }
7582
7583 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7584 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7585
7586 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7587 return false;
7588
7589 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7590 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7591 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7592}
7593
7595 const NestedNameSpecifier Y) {
7596 if (X == Y)
7597 return true;
7598 if (!X || !Y)
7599 return false;
7600
7601 auto Kind = X.getKind();
7602 if (Kind != Y.getKind())
7603 return false;
7604
7605 // FIXME: For namespaces and types, we're permitted to check that the entity
7606 // is named via the same tokens. We should probably do so.
7607 switch (Kind) {
7609 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7610 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7611 if (!declaresSameEntity(NamespaceX->getNamespace(),
7612 NamespaceY->getNamespace()))
7613 return false;
7614 return isSameQualifier(PrefixX, PrefixY);
7615 }
7617 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7618 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7619 return false;
7620 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7621 }
7625 return true;
7626 }
7627 llvm_unreachable("unhandled qualifier kind");
7628}
7629
7630static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7631 if (!A->getASTContext().getLangOpts().CUDA)
7632 return true; // Target attributes are overloadable in CUDA compilation only.
7633 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7634 return false;
7635 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7636 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7637 return true; // unattributed and __host__ functions are the same.
7638}
7639
7640/// Determine whether the attributes we can overload on are identical for A and
7641/// B. Will ignore any overloadable attrs represented in the type of A and B.
7643 const FunctionDecl *B) {
7644 // Note that pass_object_size attributes are represented in the function's
7645 // ExtParameterInfo, so we don't need to check them here.
7646
7647 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7648 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7649 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7650
7651 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7652 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7653 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7654
7655 // Return false if the number of enable_if attributes is different.
7656 if (!Cand1A || !Cand2A)
7657 return false;
7658
7659 Cand1ID.clear();
7660 Cand2ID.clear();
7661
7662 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7663 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7664
7665 // Return false if any of the enable_if expressions of A and B are
7666 // different.
7667 if (Cand1ID != Cand2ID)
7668 return false;
7669 }
7670 return hasSameCudaAttrs(A, B);
7671}
7672
7673bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7674 // Caution: this function is called by the AST reader during deserialization,
7675 // so it cannot rely on AST invariants being met. Non-trivial accessors
7676 // should be avoided, along with any traversal of redeclaration chains.
7677
7678 if (X == Y)
7679 return true;
7680
7681 if (X->getDeclName() != Y->getDeclName())
7682 return false;
7683
7684 // Must be in the same context.
7685 //
7686 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7687 // could be two different declarations of the same function. (We will fix the
7688 // semantic DC to refer to the primary definition after merging.)
7689 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7691 return false;
7692
7693 // If either X or Y are local to the owning module, they are only possible to
7694 // be the same entity if they are in the same module.
7695 if (X->isModuleLocal() || Y->isModuleLocal())
7696 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7697 return false;
7698
7699 // Two typedefs refer to the same entity if they have the same underlying
7700 // type.
7701 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7702 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7703 return hasSameType(TypedefX->getUnderlyingType(),
7704 TypedefY->getUnderlyingType());
7705
7706 // Must have the same kind.
7707 if (X->getKind() != Y->getKind())
7708 return false;
7709
7710 // Objective-C classes and protocols with the same name always match.
7712 return true;
7713
7715 // No need to handle these here: we merge them when adding them to the
7716 // template.
7717 return false;
7718 }
7719
7720 // Compatible tags match.
7721 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7722 const auto *TagY = cast<TagDecl>(Y);
7723 return (TagX->getTagKind() == TagY->getTagKind()) ||
7724 ((TagX->getTagKind() == TagTypeKind::Struct ||
7725 TagX->getTagKind() == TagTypeKind::Class ||
7726 TagX->getTagKind() == TagTypeKind::Interface) &&
7727 (TagY->getTagKind() == TagTypeKind::Struct ||
7728 TagY->getTagKind() == TagTypeKind::Class ||
7729 TagY->getTagKind() == TagTypeKind::Interface));
7730 }
7731
7732 // Functions with the same type and linkage match.
7733 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7734 // functions, etc.
7735 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7736 const auto *FuncY = cast<FunctionDecl>(Y);
7737 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7738 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7739 if (CtorX->getInheritedConstructor() &&
7740 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7741 CtorY->getInheritedConstructor().getConstructor()))
7742 return false;
7743 }
7744
7745 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7746 return false;
7747
7748 // Multiversioned functions with different feature strings are represented
7749 // as separate declarations.
7750 if (FuncX->isMultiVersion()) {
7751 const auto *TAX = FuncX->getAttr<TargetAttr>();
7752 const auto *TAY = FuncY->getAttr<TargetAttr>();
7753 assert(TAX && TAY && "Multiversion Function without target attribute");
7754
7755 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7756 return false;
7757 }
7758
7759 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7760 // not the same entity if they are constrained.
7761 if ((FuncX->isMemberLikeConstrainedFriend() ||
7762 FuncY->isMemberLikeConstrainedFriend()) &&
7763 !FuncX->getLexicalDeclContext()->Equals(
7764 FuncY->getLexicalDeclContext())) {
7765 return false;
7766 }
7767
7768 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7769 FuncY->getTrailingRequiresClause()))
7770 return false;
7771
7772 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7773 // Map to the first declaration that we've already merged into this one.
7774 // The TSI of redeclarations might not match (due to calling conventions
7775 // being inherited onto the type but not the TSI), but the TSI type of
7776 // the first declaration of the function should match across modules.
7777 FD = FD->getCanonicalDecl();
7778 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7779 : FD->getType();
7780 };
7781 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7782 if (!hasSameType(XT, YT)) {
7783 // We can get functions with different types on the redecl chain in C++17
7784 // if they have differing exception specifications and at least one of
7785 // the excpetion specs is unresolved.
7786 auto *XFPT = XT->getAs<FunctionProtoType>();
7787 auto *YFPT = YT->getAs<FunctionProtoType>();
7788 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7789 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7792 return true;
7793 return false;
7794 }
7795
7796 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7797 hasSameOverloadableAttrs(FuncX, FuncY);
7798 }
7799
7800 // Variables with the same type and linkage match.
7801 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7802 const auto *VarY = cast<VarDecl>(Y);
7803 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7804 // During deserialization, we might compare variables before we load
7805 // their types. Assume the types will end up being the same.
7806 if (VarX->getType().isNull() || VarY->getType().isNull())
7807 return true;
7808
7809 if (hasSameType(VarX->getType(), VarY->getType()))
7810 return true;
7811
7812 // We can get decls with different types on the redecl chain. Eg.
7813 // template <typename T> struct S { static T Var[]; }; // #1
7814 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7815 // Only? happens when completing an incomplete array type. In this case
7816 // when comparing #1 and #2 we should go through their element type.
7817 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7818 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7819 if (!VarXTy || !VarYTy)
7820 return false;
7821 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7822 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7823 }
7824 return false;
7825 }
7826
7827 // Namespaces with the same name and inlinedness match.
7828 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7829 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7830 return NamespaceX->isInline() == NamespaceY->isInline();
7831 }
7832
7833 // Identical template names and kinds match if their template parameter lists
7834 // and patterns match.
7835 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7836 const auto *TemplateY = cast<TemplateDecl>(Y);
7837
7838 // ConceptDecl wouldn't be the same if their constraint expression differs.
7839 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7840 const auto *ConceptY = cast<ConceptDecl>(Y);
7841 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7842 ConceptY->getConstraintExpr()))
7843 return false;
7844 }
7845
7846 return isSameEntity(TemplateX->getTemplatedDecl(),
7847 TemplateY->getTemplatedDecl()) &&
7848 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7849 TemplateY->getTemplateParameters());
7850 }
7851
7852 // Fields with the same name and the same type match.
7853 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7854 const auto *FDY = cast<FieldDecl>(Y);
7855 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7856 return hasSameType(FDX->getType(), FDY->getType());
7857 }
7858
7859 // Indirect fields with the same target field match.
7860 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7861 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7862 return IFDX->getAnonField()->getCanonicalDecl() ==
7863 IFDY->getAnonField()->getCanonicalDecl();
7864 }
7865
7866 // Enumerators with the same name match.
7868 // FIXME: Also check the value is odr-equivalent.
7869 return true;
7870
7871 // Using shadow declarations with the same target match.
7872 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7873 const auto *USY = cast<UsingShadowDecl>(Y);
7874 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7875 }
7876
7877 // Using declarations with the same qualifier match. (We already know that
7878 // the name matches.)
7879 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7880 const auto *UY = cast<UsingDecl>(Y);
7881 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7882 UX->hasTypename() == UY->hasTypename() &&
7883 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7884 }
7885 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7886 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7887 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7888 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7889 }
7890 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7891 return isSameQualifier(
7892 UX->getQualifier(),
7893 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7894 }
7895
7896 // Using-pack declarations are only created by instantiation, and match if
7897 // they're instantiated from matching UnresolvedUsing...Decls.
7898 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7899 return declaresSameEntity(
7900 UX->getInstantiatedFromUsingDecl(),
7901 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7902 }
7903
7904 // Namespace alias definitions with the same target match.
7905 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7906 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7907 return NAX->getNamespace()->Equals(NAY->getNamespace());
7908 }
7909
7910 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7911 const auto *UY = cast<UsingEnumDecl>(Y);
7912 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7913 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7914 }
7915
7916 return false;
7917}
7918
7921 switch (Arg.getKind()) {
7923 return Arg;
7924
7926 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
7927 Arg.getIsDefaulted());
7928
7930 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
7932 Arg.getIsDefaulted());
7933 }
7934
7937 /*isNullPtr*/ true, Arg.getIsDefaulted());
7938
7941 Arg.getIsDefaulted());
7942
7944 return TemplateArgument(
7947
7950
7952 return TemplateArgument(*this,
7955
7958 /*isNullPtr*/ false, Arg.getIsDefaulted());
7959
7961 bool AnyNonCanonArgs = false;
7962 auto CanonArgs = ::getCanonicalTemplateArguments(
7963 *this, Arg.pack_elements(), AnyNonCanonArgs);
7964 if (!AnyNonCanonArgs)
7965 return Arg;
7967 const_cast<ASTContext &>(*this), CanonArgs);
7968 NewArg.setIsDefaulted(Arg.getIsDefaulted());
7969 return NewArg;
7970 }
7971 }
7972
7973 // Silence GCC warning
7974 llvm_unreachable("Unhandled template argument kind");
7975}
7976
7978 const TemplateArgument &Arg2) const {
7979 if (Arg1.getKind() != Arg2.getKind())
7980 return false;
7981
7982 switch (Arg1.getKind()) {
7984 llvm_unreachable("Comparing NULL template argument");
7985
7987 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
7988
7990 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
7992
7994 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
7995
8000
8002 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8003 Arg2.getAsIntegral());
8004
8006 return Arg1.structurallyEquals(Arg2);
8007
8009 llvm::FoldingSetNodeID ID1, ID2;
8010 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8011 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8012 return ID1 == ID2;
8013 }
8014
8016 return llvm::equal(
8017 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8018 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8019 return isSameTemplateArgument(Arg1, Arg2);
8020 });
8021 }
8022
8023 llvm_unreachable("Unhandled template argument kind");
8024}
8025
8027 // Handle the non-qualified case efficiently.
8028 if (!T.hasLocalQualifiers()) {
8029 // Handle the common positive case fast.
8030 if (const auto *AT = dyn_cast<ArrayType>(T))
8031 return AT;
8032 }
8033
8034 // Handle the common negative case fast.
8035 if (!isa<ArrayType>(T.getCanonicalType()))
8036 return nullptr;
8037
8038 // Apply any qualifiers from the array type to the element type. This
8039 // implements C99 6.7.3p8: "If the specification of an array type includes
8040 // any type qualifiers, the element type is so qualified, not the array type."
8041
8042 // If we get here, we either have type qualifiers on the type, or we have
8043 // sugar such as a typedef in the way. If we have type qualifiers on the type
8044 // we must propagate them down into the element type.
8045
8046 SplitQualType split = T.getSplitDesugaredType();
8047 Qualifiers qs = split.Quals;
8048
8049 // If we have a simple case, just return now.
8050 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8051 if (!ATy || qs.empty())
8052 return ATy;
8053
8054 // Otherwise, we have an array and we have qualifiers on it. Push the
8055 // qualifiers into the array element type and return a new array type.
8056 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8057
8058 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8059 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8060 CAT->getSizeExpr(),
8061 CAT->getSizeModifier(),
8062 CAT->getIndexTypeCVRQualifiers()));
8063 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8065 IAT->getSizeModifier(),
8066 IAT->getIndexTypeCVRQualifiers()));
8067
8068 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8070 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8071 DSAT->getIndexTypeCVRQualifiers()));
8072
8073 const auto *VAT = cast<VariableArrayType>(ATy);
8074 return cast<ArrayType>(
8075 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8076 VAT->getIndexTypeCVRQualifiers()));
8077}
8078
8080 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8081 return getLValueReferenceType(T);
8082 if (getLangOpts().HLSL && T->isConstantArrayType())
8083 return getArrayParameterType(T);
8084 if (T->isArrayType() || T->isFunctionType())
8085 return getDecayedType(T);
8086 return T;
8087}
8088
8092 return T.getUnqualifiedType();
8093}
8094
8096 // C++ [except.throw]p3:
8097 // A throw-expression initializes a temporary object, called the exception
8098 // object, the type of which is determined by removing any top-level
8099 // cv-qualifiers from the static type of the operand of throw and adjusting
8100 // the type from "array of T" or "function returning T" to "pointer to T"
8101 // or "pointer to function returning T", [...]
8103 if (T->isArrayType() || T->isFunctionType())
8104 T = getDecayedType(T);
8105 return T.getUnqualifiedType();
8106}
8107
8108/// getArrayDecayedType - Return the properly qualified result of decaying the
8109/// specified array type to a pointer. This operation is non-trivial when
8110/// handling typedefs etc. The canonical type of "T" must be an array type,
8111/// this returns a pointer to a properly qualified element of the array.
8112///
8113/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8115 // Get the element type with 'getAsArrayType' so that we don't lose any
8116 // typedefs in the element type of the array. This also handles propagation
8117 // of type qualifiers from the array type into the element type if present
8118 // (C99 6.7.3p8).
8119 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8120 assert(PrettyArrayType && "Not an array type!");
8121
8122 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8123
8124 // int x[restrict 4] -> int *restrict
8126 PrettyArrayType->getIndexTypeQualifiers());
8127
8128 // int x[_Nullable] -> int * _Nullable
8129 if (auto Nullability = Ty->getNullability()) {
8130 Result = getAttributedType(*Nullability, Result, Result);
8131 }
8132 return Result;
8133}
8134
8136 return getBaseElementType(array->getElementType());
8137}
8138
8140 Qualifiers qs;
8141 while (true) {
8142 SplitQualType split = type.getSplitDesugaredType();
8143 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8144 if (!array) break;
8145
8146 type = array->getElementType();
8148 }
8149
8150 return getQualifiedType(type, qs);
8151}
8152
8154 uint64_t ElementCount = 1;
8155 do {
8156 ElementCount *= CA->getZExtSize();
8157 CA = dyn_cast_if_present<ConstantArrayType>(
8159 } while (CA);
8160 return ElementCount;
8161}
8162
8163uint64_t
8165 if (!AILE)
8166 return 0;
8167
8168 uint64_t ElementCount = 1;
8169
8170 do {
8171 ElementCount *= AILE->getArraySize().getZExtValue();
8172 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8173 } while (AILE);
8174
8175 return ElementCount;
8176}
8177
8178/// getFloatingRank - Return a relative rank for floating point types.
8179/// This routine will assert if passed a built-in type that isn't a float.
8181 if (const auto *CT = T->getAs<ComplexType>())
8182 return getFloatingRank(CT->getElementType());
8183
8184 switch (T->castAs<BuiltinType>()->getKind()) {
8185 default: llvm_unreachable("getFloatingRank(): not a floating type");
8186 case BuiltinType::Float16: return Float16Rank;
8187 case BuiltinType::Half: return HalfRank;
8188 case BuiltinType::Float: return FloatRank;
8189 case BuiltinType::Double: return DoubleRank;
8190 case BuiltinType::LongDouble: return LongDoubleRank;
8191 case BuiltinType::Float128: return Float128Rank;
8192 case BuiltinType::BFloat16: return BFloat16Rank;
8193 case BuiltinType::Ibm128: return Ibm128Rank;
8194 }
8195}
8196
8197/// getFloatingTypeOrder - Compare the rank of the two specified floating
8198/// point types, ignoring the domain of the type (i.e. 'double' ==
8199/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8200/// LHS < RHS, return -1.
8202 FloatingRank LHSR = getFloatingRank(LHS);
8203 FloatingRank RHSR = getFloatingRank(RHS);
8204
8205 if (LHSR == RHSR)
8206 return 0;
8207 if (LHSR > RHSR)
8208 return 1;
8209 return -1;
8210}
8211
8214 return 0;
8215 return getFloatingTypeOrder(LHS, RHS);
8216}
8217
8218/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8219/// routine will assert if passed a built-in type that isn't an integer or enum,
8220/// or if it is not canonicalized.
8221unsigned ASTContext::getIntegerRank(const Type *T) const {
8222 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8223
8224 // Results in this 'losing' to any type of the same size, but winning if
8225 // larger.
8226 if (const auto *EIT = dyn_cast<BitIntType>(T))
8227 return 0 + (EIT->getNumBits() << 3);
8228
8229 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8230 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8231
8232 switch (cast<BuiltinType>(T)->getKind()) {
8233 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8234 case BuiltinType::Bool:
8235 return 1 + (getIntWidth(BoolTy) << 3);
8236 case BuiltinType::Char_S:
8237 case BuiltinType::Char_U:
8238 case BuiltinType::SChar:
8239 case BuiltinType::UChar:
8240 return 2 + (getIntWidth(CharTy) << 3);
8241 case BuiltinType::Short:
8242 case BuiltinType::UShort:
8243 return 3 + (getIntWidth(ShortTy) << 3);
8244 case BuiltinType::Int:
8245 case BuiltinType::UInt:
8246 return 4 + (getIntWidth(IntTy) << 3);
8247 case BuiltinType::Long:
8248 case BuiltinType::ULong:
8249 return 5 + (getIntWidth(LongTy) << 3);
8250 case BuiltinType::LongLong:
8251 case BuiltinType::ULongLong:
8252 return 6 + (getIntWidth(LongLongTy) << 3);
8253 case BuiltinType::Int128:
8254 case BuiltinType::UInt128:
8255 return 7 + (getIntWidth(Int128Ty) << 3);
8256
8257 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8258 // their underlying types" [c++20 conv.rank]
8259 case BuiltinType::Char8:
8260 return getIntegerRank(UnsignedCharTy.getTypePtr());
8261 case BuiltinType::Char16:
8262 return getIntegerRank(
8263 getFromTargetType(Target->getChar16Type()).getTypePtr());
8264 case BuiltinType::Char32:
8265 return getIntegerRank(
8266 getFromTargetType(Target->getChar32Type()).getTypePtr());
8267 case BuiltinType::WChar_S:
8268 case BuiltinType::WChar_U:
8269 return getIntegerRank(
8270 getFromTargetType(Target->getWCharType()).getTypePtr());
8271 }
8272}
8273
8274/// Whether this is a promotable bitfield reference according
8275/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8276///
8277/// \returns the type this bit-field will promote to, or NULL if no
8278/// promotion occurs.
8280 if (E->isTypeDependent() || E->isValueDependent())
8281 return {};
8282
8283 // C++ [conv.prom]p5:
8284 // If the bit-field has an enumerated type, it is treated as any other
8285 // value of that type for promotion purposes.
8287 return {};
8288
8289 // FIXME: We should not do this unless E->refersToBitField() is true. This
8290 // matters in C where getSourceBitField() will find bit-fields for various
8291 // cases where the source expression is not a bit-field designator.
8292
8293 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8294 if (!Field)
8295 return {};
8296
8297 QualType FT = Field->getType();
8298
8299 uint64_t BitWidth = Field->getBitWidthValue();
8300 uint64_t IntSize = getTypeSize(IntTy);
8301 // C++ [conv.prom]p5:
8302 // A prvalue for an integral bit-field can be converted to a prvalue of type
8303 // int if int can represent all the values of the bit-field; otherwise, it
8304 // can be converted to unsigned int if unsigned int can represent all the
8305 // values of the bit-field. If the bit-field is larger yet, no integral
8306 // promotion applies to it.
8307 // C11 6.3.1.1/2:
8308 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8309 // If an int can represent all values of the original type (as restricted by
8310 // the width, for a bit-field), the value is converted to an int; otherwise,
8311 // it is converted to an unsigned int.
8312 //
8313 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8314 // We perform that promotion here to match GCC and C++.
8315 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8316 // greater than that of 'int'. We perform that promotion to match GCC.
8317 //
8318 // C23 6.3.1.1p2:
8319 // The value from a bit-field of a bit-precise integer type is converted to
8320 // the corresponding bit-precise integer type. (The rest is the same as in
8321 // C11.)
8322 if (QualType QT = Field->getType(); QT->isBitIntType())
8323 return QT;
8324
8325 if (BitWidth < IntSize)
8326 return IntTy;
8327
8328 if (BitWidth == IntSize)
8329 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8330
8331 // Bit-fields wider than int are not subject to promotions, and therefore act
8332 // like the base type. GCC has some weird bugs in this area that we
8333 // deliberately do not follow (GCC follows a pre-standard resolution to
8334 // C's DR315 which treats bit-width as being part of the type, and this leaks
8335 // into their semantics in some cases).
8336 return {};
8337}
8338
8339/// getPromotedIntegerType - Returns the type that Promotable will
8340/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8341/// integer type.
8343 assert(!Promotable.isNull());
8344 assert(isPromotableIntegerType(Promotable));
8345 if (const auto *ED = Promotable->getAsEnumDecl())
8346 return ED->getPromotionType();
8347
8348 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8349 // qualifier.
8350 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8351 QualType PromotedUnderlying =
8352 getPromotedIntegerType(OBT->getUnderlyingType());
8353 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8354 }
8355
8356 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8357 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8358 // (3.9.1) can be converted to a prvalue of the first of the following
8359 // types that can represent all the values of its underlying type:
8360 // int, unsigned int, long int, unsigned long int, long long int, or
8361 // unsigned long long int [...]
8362 // FIXME: Is there some better way to compute this?
8363 if (BT->getKind() == BuiltinType::WChar_S ||
8364 BT->getKind() == BuiltinType::WChar_U ||
8365 BT->getKind() == BuiltinType::Char8 ||
8366 BT->getKind() == BuiltinType::Char16 ||
8367 BT->getKind() == BuiltinType::Char32) {
8368 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8369 uint64_t FromSize = getTypeSize(BT);
8370 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8372 for (const auto &PT : PromoteTypes) {
8373 uint64_t ToSize = getTypeSize(PT);
8374 if (FromSize < ToSize ||
8375 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8376 return PT;
8377 }
8378 llvm_unreachable("char type should fit into long long");
8379 }
8380 }
8381
8382 // At this point, we should have a signed or unsigned integer type.
8383 if (Promotable->isSignedIntegerType())
8384 return IntTy;
8385 uint64_t PromotableSize = getIntWidth(Promotable);
8386 uint64_t IntSize = getIntWidth(IntTy);
8387 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8388 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8389}
8390
8391/// Recurses in pointer/array types until it finds an objc retainable
8392/// type and returns its ownership.
8394 while (!T.isNull()) {
8395 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8396 return T.getObjCLifetime();
8397 if (T->isArrayType())
8399 else if (const auto *PT = T->getAs<PointerType>())
8400 T = PT->getPointeeType();
8401 else if (const auto *RT = T->getAs<ReferenceType>())
8402 T = RT->getPointeeType();
8403 else
8404 break;
8405 }
8406
8407 return Qualifiers::OCL_None;
8408}
8409
8410static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8411 // Incomplete enum types are not treated as integer types.
8412 // FIXME: In C++, enum types are never integer types.
8413 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8414 if (ED->isComplete() && !ED->isScoped())
8415 return ED->getIntegerType().getTypePtr();
8416 return nullptr;
8417}
8418
8419/// getIntegerTypeOrder - Returns the highest ranked integer type:
8420/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8421/// LHS < RHS, return -1.
8423 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8424 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8425
8426 // Unwrap enums to their underlying type.
8427 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8428 LHSC = getIntegerTypeForEnum(ET);
8429 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8430 RHSC = getIntegerTypeForEnum(ET);
8431
8432 if (LHSC == RHSC) return 0;
8433
8434 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8435 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8436
8437 unsigned LHSRank = getIntegerRank(LHSC);
8438 unsigned RHSRank = getIntegerRank(RHSC);
8439
8440 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8441 if (LHSRank == RHSRank) return 0;
8442 return LHSRank > RHSRank ? 1 : -1;
8443 }
8444
8445 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8446 if (LHSUnsigned) {
8447 // If the unsigned [LHS] type is larger, return it.
8448 if (LHSRank >= RHSRank)
8449 return 1;
8450
8451 // If the signed type can represent all values of the unsigned type, it
8452 // wins. Because we are dealing with 2's complement and types that are
8453 // powers of two larger than each other, this is always safe.
8454 return -1;
8455 }
8456
8457 // If the unsigned [RHS] type is larger, return it.
8458 if (RHSRank >= LHSRank)
8459 return -1;
8460
8461 // If the signed type can represent all values of the unsigned type, it
8462 // wins. Because we are dealing with 2's complement and types that are
8463 // powers of two larger than each other, this is always safe.
8464 return 1;
8465}
8466
8468 if (CFConstantStringTypeDecl)
8469 return CFConstantStringTypeDecl;
8470
8471 assert(!CFConstantStringTagDecl &&
8472 "tag and typedef should be initialized together");
8473 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8474 CFConstantStringTagDecl->startDefinition();
8475
8476 struct {
8477 QualType Type;
8478 const char *Name;
8479 } Fields[5];
8480 unsigned Count = 0;
8481
8482 /// Objective-C ABI
8483 ///
8484 /// typedef struct __NSConstantString_tag {
8485 /// const int *isa;
8486 /// int flags;
8487 /// const char *str;
8488 /// long length;
8489 /// } __NSConstantString;
8490 ///
8491 /// Swift ABI (4.1, 4.2)
8492 ///
8493 /// typedef struct __NSConstantString_tag {
8494 /// uintptr_t _cfisa;
8495 /// uintptr_t _swift_rc;
8496 /// _Atomic(uint64_t) _cfinfoa;
8497 /// const char *_ptr;
8498 /// uint32_t _length;
8499 /// } __NSConstantString;
8500 ///
8501 /// Swift ABI (5.0)
8502 ///
8503 /// typedef struct __NSConstantString_tag {
8504 /// uintptr_t _cfisa;
8505 /// uintptr_t _swift_rc;
8506 /// _Atomic(uint64_t) _cfinfoa;
8507 /// const char *_ptr;
8508 /// uintptr_t _length;
8509 /// } __NSConstantString;
8510
8511 const auto CFRuntime = getLangOpts().CFRuntime;
8512 if (static_cast<unsigned>(CFRuntime) <
8513 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8514 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8515 Fields[Count++] = { IntTy, "flags" };
8516 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8517 Fields[Count++] = { LongTy, "length" };
8518 } else {
8519 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8520 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8521 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8522 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8525 Fields[Count++] = { IntTy, "_ptr" };
8526 else
8527 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8528 }
8529
8530 // Create fields
8531 for (unsigned i = 0; i < Count; ++i) {
8532 FieldDecl *Field =
8533 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8534 SourceLocation(), &Idents.get(Fields[i].Name),
8535 Fields[i].Type, /*TInfo=*/nullptr,
8536 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8537 Field->setAccess(AS_public);
8538 CFConstantStringTagDecl->addDecl(Field);
8539 }
8540
8541 CFConstantStringTagDecl->completeDefinition();
8542 // This type is designed to be compatible with NSConstantString, but cannot
8543 // use the same name, since NSConstantString is an interface.
8544 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8545 CFConstantStringTypeDecl =
8546 buildImplicitTypedef(tagType, "__NSConstantString");
8547
8548 return CFConstantStringTypeDecl;
8549}
8550
8552 if (!CFConstantStringTagDecl)
8553 getCFConstantStringDecl(); // Build the tag and the typedef.
8554 return CFConstantStringTagDecl;
8555}
8556
8557// getCFConstantStringType - Return the type used for constant CFStrings.
8562
8564 if (ObjCSuperType.isNull()) {
8565 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8566 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8567 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8568 }
8569 return ObjCSuperType;
8570}
8571
8573 const auto *TT = T->castAs<TypedefType>();
8574 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8575 CFConstantStringTagDecl = TT->castAsRecordDecl();
8576}
8577
8579 if (BlockDescriptorType)
8580 return getCanonicalTagType(BlockDescriptorType);
8581
8582 RecordDecl *RD;
8583 // FIXME: Needs the FlagAppleBlock bit.
8584 RD = buildImplicitRecord("__block_descriptor");
8585 RD->startDefinition();
8586
8587 QualType FieldTypes[] = {
8590 };
8591
8592 static const char *const FieldNames[] = {
8593 "reserved",
8594 "Size"
8595 };
8596
8597 for (size_t i = 0; i < 2; ++i) {
8599 *this, RD, SourceLocation(), SourceLocation(),
8600 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8601 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8602 Field->setAccess(AS_public);
8603 RD->addDecl(Field);
8604 }
8605
8606 RD->completeDefinition();
8607
8608 BlockDescriptorType = RD;
8609
8610 return getCanonicalTagType(BlockDescriptorType);
8611}
8612
8614 if (BlockDescriptorExtendedType)
8615 return getCanonicalTagType(BlockDescriptorExtendedType);
8616
8617 RecordDecl *RD;
8618 // FIXME: Needs the FlagAppleBlock bit.
8619 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8620 RD->startDefinition();
8621
8622 QualType FieldTypes[] = {
8627 };
8628
8629 static const char *const FieldNames[] = {
8630 "reserved",
8631 "Size",
8632 "CopyFuncPtr",
8633 "DestroyFuncPtr"
8634 };
8635
8636 for (size_t i = 0; i < 4; ++i) {
8638 *this, RD, SourceLocation(), SourceLocation(),
8639 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8640 /*BitWidth=*/nullptr,
8641 /*Mutable=*/false, ICIS_NoInit);
8642 Field->setAccess(AS_public);
8643 RD->addDecl(Field);
8644 }
8645
8646 RD->completeDefinition();
8647
8648 BlockDescriptorExtendedType = RD;
8649 return getCanonicalTagType(BlockDescriptorExtendedType);
8650}
8651
8653 const auto *BT = dyn_cast<BuiltinType>(T);
8654
8655 if (!BT) {
8656 if (isa<PipeType>(T))
8657 return OCLTK_Pipe;
8658
8659 return OCLTK_Default;
8660 }
8661
8662 switch (BT->getKind()) {
8663#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8664 case BuiltinType::Id: \
8665 return OCLTK_Image;
8666#include "clang/Basic/OpenCLImageTypes.def"
8667
8668 case BuiltinType::OCLClkEvent:
8669 return OCLTK_ClkEvent;
8670
8671 case BuiltinType::OCLEvent:
8672 return OCLTK_Event;
8673
8674 case BuiltinType::OCLQueue:
8675 return OCLTK_Queue;
8676
8677 case BuiltinType::OCLReserveID:
8678 return OCLTK_ReserveID;
8679
8680 case BuiltinType::OCLSampler:
8681 return OCLTK_Sampler;
8682
8683 default:
8684 return OCLTK_Default;
8685 }
8686}
8687
8689 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8690}
8691
8692/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8693/// requires copy/dispose. Note that this must match the logic
8694/// in buildByrefHelpers.
8696 const VarDecl *D) {
8697 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8698 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8699 if (!copyExpr && record->hasTrivialDestructor()) return false;
8700
8701 return true;
8702 }
8703
8705 return true;
8706
8707 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8708 // move or destroy.
8710 return true;
8711
8712 if (!Ty->isObjCRetainableType()) return false;
8713
8714 Qualifiers qs = Ty.getQualifiers();
8715
8716 // If we have lifetime, that dominates.
8717 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8718 switch (lifetime) {
8719 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8720
8721 // These are just bits as far as the runtime is concerned.
8724 return false;
8725
8726 // These cases should have been taken care of when checking the type's
8727 // non-triviality.
8730 llvm_unreachable("impossible");
8731 }
8732 llvm_unreachable("fell out of lifetime switch!");
8733 }
8734 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8736}
8737
8739 Qualifiers::ObjCLifetime &LifeTime,
8740 bool &HasByrefExtendedLayout) const {
8741 if (!getLangOpts().ObjC ||
8742 getLangOpts().getGC() != LangOptions::NonGC)
8743 return false;
8744
8745 HasByrefExtendedLayout = false;
8746 if (Ty->isRecordType()) {
8747 HasByrefExtendedLayout = true;
8748 LifeTime = Qualifiers::OCL_None;
8749 } else if ((LifeTime = Ty.getObjCLifetime())) {
8750 // Honor the ARC qualifiers.
8751 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8752 // The MRR rule.
8754 } else {
8755 LifeTime = Qualifiers::OCL_None;
8756 }
8757 return true;
8758}
8759
8761 assert(Target && "Expected target to be initialized");
8762 const llvm::Triple &T = Target->getTriple();
8763 // Windows is LLP64 rather than LP64
8764 if (T.isOSWindows() && T.isArch64Bit())
8765 return UnsignedLongLongTy;
8766 return UnsignedLongTy;
8767}
8768
8770 assert(Target && "Expected target to be initialized");
8771 const llvm::Triple &T = Target->getTriple();
8772 // Windows is LLP64 rather than LP64
8773 if (T.isOSWindows() && T.isArch64Bit())
8774 return LongLongTy;
8775 return LongTy;
8776}
8777
8779 if (!ObjCInstanceTypeDecl)
8780 ObjCInstanceTypeDecl =
8781 buildImplicitTypedef(getObjCIdType(), "instancetype");
8782 return ObjCInstanceTypeDecl;
8783}
8784
8785// This returns true if a type has been typedefed to BOOL:
8786// typedef <type> BOOL;
8788 if (const auto *TT = dyn_cast<TypedefType>(T))
8789 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8790 return II->isStr("BOOL");
8791
8792 return false;
8793}
8794
8795/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8796/// purpose.
8798 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8799 return CharUnits::Zero();
8800
8802
8803 // Make all integer and enum types at least as large as an int
8804 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8805 sz = std::max(sz, getTypeSizeInChars(IntTy));
8806 // Treat arrays as pointers, since that's how they're passed in.
8807 else if (type->isArrayType())
8809 return sz;
8810}
8811
8818
8821 if (!VD->isInline())
8823
8824 // In almost all cases, it's a weak definition.
8825 auto *First = VD->getFirstDecl();
8826 if (First->isInlineSpecified() || !First->isStaticDataMember())
8828
8829 // If there's a file-context declaration in this translation unit, it's a
8830 // non-discardable definition.
8831 for (auto *D : VD->redecls())
8833 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8835
8836 // If we've not seen one yet, we don't know.
8838}
8839
8840static std::string charUnitsToString(const CharUnits &CU) {
8841 return llvm::itostr(CU.getQuantity());
8842}
8843
8844/// getObjCEncodingForBlock - Return the encoded type for this block
8845/// declaration.
8847 std::string S;
8848
8849 const BlockDecl *Decl = Expr->getBlockDecl();
8850 QualType BlockTy =
8852 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8853 // Encode result type.
8854 if (getLangOpts().EncodeExtendedBlockSig)
8856 true /*Extended*/);
8857 else
8858 getObjCEncodingForType(BlockReturnTy, S);
8859 // Compute size of all parameters.
8860 // Start with computing size of a pointer in number of bytes.
8861 // FIXME: There might(should) be a better way of doing this computation!
8863 CharUnits ParmOffset = PtrSize;
8864 for (auto *PI : Decl->parameters()) {
8865 QualType PType = PI->getType();
8867 if (sz.isZero())
8868 continue;
8869 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8870 ParmOffset += sz;
8871 }
8872 // Size of the argument frame
8873 S += charUnitsToString(ParmOffset);
8874 // Block pointer and offset.
8875 S += "@?0";
8876
8877 // Argument types.
8878 ParmOffset = PtrSize;
8879 for (auto *PVDecl : Decl->parameters()) {
8880 QualType PType = PVDecl->getOriginalType();
8881 if (const auto *AT =
8882 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8883 // Use array's original type only if it has known number of
8884 // elements.
8885 if (!isa<ConstantArrayType>(AT))
8886 PType = PVDecl->getType();
8887 } else if (PType->isFunctionType())
8888 PType = PVDecl->getType();
8889 if (getLangOpts().EncodeExtendedBlockSig)
8891 S, true /*Extended*/);
8892 else
8893 getObjCEncodingForType(PType, S);
8894 S += charUnitsToString(ParmOffset);
8895 ParmOffset += getObjCEncodingTypeSize(PType);
8896 }
8897
8898 return S;
8899}
8900
8901std::string
8903 std::string S;
8904 // Encode result type.
8905 getObjCEncodingForType(Decl->getReturnType(), S);
8906 CharUnits ParmOffset;
8907 // Compute size of all parameters.
8908 for (auto *PI : Decl->parameters()) {
8909 QualType PType = PI->getType();
8911 if (sz.isZero())
8912 continue;
8913
8914 assert(sz.isPositive() &&
8915 "getObjCEncodingForFunctionDecl - Incomplete param type");
8916 ParmOffset += sz;
8917 }
8918 S += charUnitsToString(ParmOffset);
8919 ParmOffset = CharUnits::Zero();
8920
8921 // Argument types.
8922 for (auto *PVDecl : Decl->parameters()) {
8923 QualType PType = PVDecl->getOriginalType();
8924 if (const auto *AT =
8925 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8926 // Use array's original type only if it has known number of
8927 // elements.
8928 if (!isa<ConstantArrayType>(AT))
8929 PType = PVDecl->getType();
8930 } else if (PType->isFunctionType())
8931 PType = PVDecl->getType();
8932 getObjCEncodingForType(PType, S);
8933 S += charUnitsToString(ParmOffset);
8934 ParmOffset += getObjCEncodingTypeSize(PType);
8935 }
8936
8937 return S;
8938}
8939
8940/// getObjCEncodingForMethodParameter - Return the encoded type for a single
8941/// method parameter or return type. If Extended, include class names and
8942/// block object types.
8944 QualType T, std::string& S,
8945 bool Extended) const {
8946 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
8948 // Encode parameter type.
8949 ObjCEncOptions Options = ObjCEncOptions()
8950 .setExpandPointedToStructures()
8951 .setExpandStructures()
8952 .setIsOutermostType();
8953 if (Extended)
8954 Options.setEncodeBlockParameters().setEncodeClassNames();
8955 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
8956}
8957
8958/// getObjCEncodingForMethodDecl - Return the encoded type for this method
8959/// declaration.
8961 bool Extended) const {
8962 // FIXME: This is not very efficient.
8963 // Encode return type.
8964 std::string S;
8965 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
8966 Decl->getReturnType(), S, Extended);
8967 // Compute size of all parameters.
8968 // Start with computing size of a pointer in number of bytes.
8969 // FIXME: There might(should) be a better way of doing this computation!
8971 // The first two arguments (self and _cmd) are pointers; account for
8972 // their size.
8973 CharUnits ParmOffset = 2 * PtrSize;
8974 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8975 E = Decl->sel_param_end(); PI != E; ++PI) {
8976 QualType PType = (*PI)->getType();
8978 if (sz.isZero())
8979 continue;
8980
8981 assert(sz.isPositive() &&
8982 "getObjCEncodingForMethodDecl - Incomplete param type");
8983 ParmOffset += sz;
8984 }
8985 S += charUnitsToString(ParmOffset);
8986 S += "@0:";
8987 S += charUnitsToString(PtrSize);
8988
8989 // Argument types.
8990 ParmOffset = 2 * PtrSize;
8991 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
8992 E = Decl->sel_param_end(); PI != E; ++PI) {
8993 const ParmVarDecl *PVDecl = *PI;
8994 QualType PType = PVDecl->getOriginalType();
8995 if (const auto *AT =
8996 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8997 // Use array's original type only if it has known number of
8998 // elements.
8999 if (!isa<ConstantArrayType>(AT))
9000 PType = PVDecl->getType();
9001 } else if (PType->isFunctionType())
9002 PType = PVDecl->getType();
9004 PType, S, Extended);
9005 S += charUnitsToString(ParmOffset);
9006 ParmOffset += getObjCEncodingTypeSize(PType);
9007 }
9008
9009 return S;
9010}
9011
9014 const ObjCPropertyDecl *PD,
9015 const Decl *Container) const {
9016 if (!Container)
9017 return nullptr;
9018 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9019 for (auto *PID : CID->property_impls())
9020 if (PID->getPropertyDecl() == PD)
9021 return PID;
9022 } else {
9023 const auto *OID = cast<ObjCImplementationDecl>(Container);
9024 for (auto *PID : OID->property_impls())
9025 if (PID->getPropertyDecl() == PD)
9026 return PID;
9027 }
9028 return nullptr;
9029}
9030
9031/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9032/// property declaration. If non-NULL, Container must be either an
9033/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9034/// NULL when getting encodings for protocol properties.
9035/// Property attributes are stored as a comma-delimited C string. The simple
9036/// attributes readonly and bycopy are encoded as single characters. The
9037/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9038/// encoded as single characters, followed by an identifier. Property types
9039/// are also encoded as a parametrized attribute. The characters used to encode
9040/// these attributes are defined by the following enumeration:
9041/// @code
9042/// enum PropertyAttributes {
9043/// kPropertyReadOnly = 'R', // property is read-only.
9044/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9045/// kPropertyByref = '&', // property is a reference to the value last assigned
9046/// kPropertyDynamic = 'D', // property is dynamic
9047/// kPropertyGetter = 'G', // followed by getter selector name
9048/// kPropertySetter = 'S', // followed by setter selector name
9049/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9050/// kPropertyType = 'T' // followed by old-style type encoding.
9051/// kPropertyWeak = 'W' // 'weak' property
9052/// kPropertyStrong = 'P' // property GC'able
9053/// kPropertyNonAtomic = 'N' // property non-atomic
9054/// kPropertyOptional = '?' // property optional
9055/// };
9056/// @endcode
9057std::string
9059 const Decl *Container) const {
9060 // Collect information from the property implementation decl(s).
9061 bool Dynamic = false;
9062 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9063
9064 if (ObjCPropertyImplDecl *PropertyImpDecl =
9066 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9067 Dynamic = true;
9068 else
9069 SynthesizePID = PropertyImpDecl;
9070 }
9071
9072 // FIXME: This is not very efficient.
9073 std::string S = "T";
9074
9075 // Encode result type.
9076 // GCC has some special rules regarding encoding of properties which
9077 // closely resembles encoding of ivars.
9079
9080 if (PD->isOptional())
9081 S += ",?";
9082
9083 if (PD->isReadOnly()) {
9084 S += ",R";
9086 S += ",C";
9088 S += ",&";
9090 S += ",W";
9091 } else {
9092 switch (PD->getSetterKind()) {
9093 case ObjCPropertyDecl::Assign: break;
9094 case ObjCPropertyDecl::Copy: S += ",C"; break;
9095 case ObjCPropertyDecl::Retain: S += ",&"; break;
9096 case ObjCPropertyDecl::Weak: S += ",W"; break;
9097 }
9098 }
9099
9100 // It really isn't clear at all what this means, since properties
9101 // are "dynamic by default".
9102 if (Dynamic)
9103 S += ",D";
9104
9106 S += ",N";
9107
9109 S += ",G";
9110 S += PD->getGetterName().getAsString();
9111 }
9112
9114 S += ",S";
9115 S += PD->getSetterName().getAsString();
9116 }
9117
9118 if (SynthesizePID) {
9119 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9120 S += ",V";
9121 S += OID->getNameAsString();
9122 }
9123
9124 // FIXME: OBJCGC: weak & strong
9125 return S;
9126}
9127
9128/// getLegacyIntegralTypeEncoding -
9129/// Another legacy compatibility encoding: 32-bit longs are encoded as
9130/// 'l' or 'L' , but not always. For typedefs, we need to use
9131/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9133 if (PointeeTy->getAs<TypedefType>()) {
9134 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9135 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9136 PointeeTy = UnsignedIntTy;
9137 else
9138 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9139 PointeeTy = IntTy;
9140 }
9141 }
9142}
9143
9145 const FieldDecl *Field,
9146 QualType *NotEncodedT) const {
9147 // We follow the behavior of gcc, expanding structures which are
9148 // directly pointed to, and expanding embedded structures. Note that
9149 // these rules are sufficient to prevent recursive encoding of the
9150 // same type.
9151 getObjCEncodingForTypeImpl(T, S,
9152 ObjCEncOptions()
9153 .setExpandPointedToStructures()
9154 .setExpandStructures()
9155 .setIsOutermostType(),
9156 Field, NotEncodedT);
9157}
9158
9160 std::string& S) const {
9161 // Encode result type.
9162 // GCC has some special rules regarding encoding of properties which
9163 // closely resembles encoding of ivars.
9164 getObjCEncodingForTypeImpl(T, S,
9165 ObjCEncOptions()
9166 .setExpandPointedToStructures()
9167 .setExpandStructures()
9168 .setIsOutermostType()
9169 .setEncodingProperty(),
9170 /*Field=*/nullptr);
9171}
9172
9174 const BuiltinType *BT) {
9176 switch (kind) {
9177 case BuiltinType::Void: return 'v';
9178 case BuiltinType::Bool: return 'B';
9179 case BuiltinType::Char8:
9180 case BuiltinType::Char_U:
9181 case BuiltinType::UChar: return 'C';
9182 case BuiltinType::Char16:
9183 case BuiltinType::UShort: return 'S';
9184 case BuiltinType::Char32:
9185 case BuiltinType::UInt: return 'I';
9186 case BuiltinType::ULong:
9187 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9188 case BuiltinType::UInt128: return 'T';
9189 case BuiltinType::ULongLong: return 'Q';
9190 case BuiltinType::Char_S:
9191 case BuiltinType::SChar: return 'c';
9192 case BuiltinType::Short: return 's';
9193 case BuiltinType::WChar_S:
9194 case BuiltinType::WChar_U:
9195 case BuiltinType::Int: return 'i';
9196 case BuiltinType::Long:
9197 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9198 case BuiltinType::LongLong: return 'q';
9199 case BuiltinType::Int128: return 't';
9200 case BuiltinType::Float: return 'f';
9201 case BuiltinType::Double: return 'd';
9202 case BuiltinType::LongDouble: return 'D';
9203 case BuiltinType::NullPtr: return '*'; // like char*
9204
9205 case BuiltinType::BFloat16:
9206 case BuiltinType::Float16:
9207 case BuiltinType::Float128:
9208 case BuiltinType::Ibm128:
9209 case BuiltinType::Half:
9210 case BuiltinType::ShortAccum:
9211 case BuiltinType::Accum:
9212 case BuiltinType::LongAccum:
9213 case BuiltinType::UShortAccum:
9214 case BuiltinType::UAccum:
9215 case BuiltinType::ULongAccum:
9216 case BuiltinType::ShortFract:
9217 case BuiltinType::Fract:
9218 case BuiltinType::LongFract:
9219 case BuiltinType::UShortFract:
9220 case BuiltinType::UFract:
9221 case BuiltinType::ULongFract:
9222 case BuiltinType::SatShortAccum:
9223 case BuiltinType::SatAccum:
9224 case BuiltinType::SatLongAccum:
9225 case BuiltinType::SatUShortAccum:
9226 case BuiltinType::SatUAccum:
9227 case BuiltinType::SatULongAccum:
9228 case BuiltinType::SatShortFract:
9229 case BuiltinType::SatFract:
9230 case BuiltinType::SatLongFract:
9231 case BuiltinType::SatUShortFract:
9232 case BuiltinType::SatUFract:
9233 case BuiltinType::SatULongFract:
9234 // FIXME: potentially need @encodes for these!
9235 return ' ';
9236
9237#define SVE_TYPE(Name, Id, SingletonId) \
9238 case BuiltinType::Id:
9239#include "clang/Basic/AArch64ACLETypes.def"
9240#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9241#include "clang/Basic/RISCVVTypes.def"
9242#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9243#include "clang/Basic/WebAssemblyReferenceTypes.def"
9244#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9245#include "clang/Basic/AMDGPUTypes.def"
9246#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9247#include "clang/Basic/SPIRVTypes.def"
9248 {
9249 DiagnosticsEngine &Diags = C->getDiagnostics();
9250 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9251 << QualType(BT, 0);
9252 return ' ';
9253 }
9254
9255 case BuiltinType::ObjCId:
9256 case BuiltinType::ObjCClass:
9257 case BuiltinType::ObjCSel:
9258 llvm_unreachable("@encoding ObjC primitive type");
9259
9260 // OpenCL and placeholder types don't need @encodings.
9261#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9262 case BuiltinType::Id:
9263#include "clang/Basic/OpenCLImageTypes.def"
9264#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9265 case BuiltinType::Id:
9266#include "clang/Basic/OpenCLExtensionTypes.def"
9267 case BuiltinType::OCLEvent:
9268 case BuiltinType::OCLClkEvent:
9269 case BuiltinType::OCLQueue:
9270 case BuiltinType::OCLReserveID:
9271 case BuiltinType::OCLSampler:
9272 case BuiltinType::Dependent:
9273#define PPC_VECTOR_TYPE(Name, Id, Size) \
9274 case BuiltinType::Id:
9275#include "clang/Basic/PPCTypes.def"
9276#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9277#include "clang/Basic/HLSLIntangibleTypes.def"
9278#define BUILTIN_TYPE(KIND, ID)
9279#define PLACEHOLDER_TYPE(KIND, ID) \
9280 case BuiltinType::KIND:
9281#include "clang/AST/BuiltinTypes.def"
9282 llvm_unreachable("invalid builtin type for @encode");
9283 }
9284 llvm_unreachable("invalid BuiltinType::Kind value");
9285}
9286
9287static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9289
9290 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9291 if (!Enum->isFixed())
9292 return 'i';
9293
9294 // The encoding of a fixed enum type matches its fixed underlying type.
9295 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9297}
9298
9299static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9300 QualType T, const FieldDecl *FD) {
9301 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9302 S += 'b';
9303 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9304 // The GNU runtime requires more information; bitfields are encoded as b,
9305 // then the offset (in bits) of the first element, then the type of the
9306 // bitfield, then the size in bits. For example, in this structure:
9307 //
9308 // struct
9309 // {
9310 // int integer;
9311 // int flags:2;
9312 // };
9313 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9314 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9315 // information is not especially sensible, but we're stuck with it for
9316 // compatibility with GCC, although providing it breaks anything that
9317 // actually uses runtime introspection and wants to work on both runtimes...
9318 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9319 uint64_t Offset;
9320
9321 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9322 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9323 } else {
9324 const RecordDecl *RD = FD->getParent();
9325 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9326 Offset = RL.getFieldOffset(FD->getFieldIndex());
9327 }
9328
9329 S += llvm::utostr(Offset);
9330
9331 if (const auto *ET = T->getAsCanonical<EnumType>())
9332 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9333 else {
9334 const auto *BT = T->castAs<BuiltinType>();
9335 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9336 }
9337 }
9338 S += llvm::utostr(FD->getBitWidthValue());
9339}
9340
9341// Helper function for determining whether the encoded type string would include
9342// a template specialization type.
9344 bool VisitBasesAndFields) {
9345 T = T->getBaseElementTypeUnsafe();
9346
9347 if (auto *PT = T->getAs<PointerType>())
9349 PT->getPointeeType().getTypePtr(), false);
9350
9351 auto *CXXRD = T->getAsCXXRecordDecl();
9352
9353 if (!CXXRD)
9354 return false;
9355
9357 return true;
9358
9359 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9360 return false;
9361
9362 for (const auto &B : CXXRD->bases())
9363 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9364 true))
9365 return true;
9366
9367 for (auto *FD : CXXRD->fields())
9368 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9369 true))
9370 return true;
9371
9372 return false;
9373}
9374
9375// FIXME: Use SmallString for accumulating string.
9376void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9377 const ObjCEncOptions Options,
9378 const FieldDecl *FD,
9379 QualType *NotEncodedT) const {
9381 switch (CT->getTypeClass()) {
9382 case Type::Builtin:
9383 case Type::Enum:
9384 if (FD && FD->isBitField())
9385 return EncodeBitField(this, S, T, FD);
9386 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9387 S += getObjCEncodingForPrimitiveType(this, BT);
9388 else
9389 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9390 return;
9391
9392 case Type::Complex:
9393 S += 'j';
9394 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9395 ObjCEncOptions(),
9396 /*Field=*/nullptr);
9397 return;
9398
9399 case Type::Atomic:
9400 S += 'A';
9401 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9402 ObjCEncOptions(),
9403 /*Field=*/nullptr);
9404 return;
9405
9406 // encoding for pointer or reference types.
9407 case Type::Pointer:
9408 case Type::LValueReference:
9409 case Type::RValueReference: {
9410 QualType PointeeTy;
9411 if (isa<PointerType>(CT)) {
9412 const auto *PT = T->castAs<PointerType>();
9413 if (PT->isObjCSelType()) {
9414 S += ':';
9415 return;
9416 }
9417 PointeeTy = PT->getPointeeType();
9418 } else {
9419 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9420 }
9421
9422 bool isReadOnly = false;
9423 // For historical/compatibility reasons, the read-only qualifier of the
9424 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9425 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9426 // Also, do not emit the 'r' for anything but the outermost type!
9427 if (T->getAs<TypedefType>()) {
9428 if (Options.IsOutermostType() && T.isConstQualified()) {
9429 isReadOnly = true;
9430 S += 'r';
9431 }
9432 } else if (Options.IsOutermostType()) {
9433 QualType P = PointeeTy;
9434 while (auto PT = P->getAs<PointerType>())
9435 P = PT->getPointeeType();
9436 if (P.isConstQualified()) {
9437 isReadOnly = true;
9438 S += 'r';
9439 }
9440 }
9441 if (isReadOnly) {
9442 // Another legacy compatibility encoding. Some ObjC qualifier and type
9443 // combinations need to be rearranged.
9444 // Rewrite "in const" from "nr" to "rn"
9445 if (StringRef(S).ends_with("nr"))
9446 S.replace(S.end()-2, S.end(), "rn");
9447 }
9448
9449 if (PointeeTy->isCharType()) {
9450 // char pointer types should be encoded as '*' unless it is a
9451 // type that has been typedef'd to 'BOOL'.
9452 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9453 S += '*';
9454 return;
9455 }
9456 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9457 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9458 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9459 if (II == &Idents.get("objc_class")) {
9460 S += '#';
9461 return;
9462 }
9463 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9464 if (II == &Idents.get("objc_object")) {
9465 S += '@';
9466 return;
9467 }
9468 // If the encoded string for the class includes template names, just emit
9469 // "^v" for pointers to the class.
9470 if (getLangOpts().CPlusPlus &&
9471 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9473 RTy, Options.ExpandPointedToStructures()))) {
9474 S += "^v";
9475 return;
9476 }
9477 // fall through...
9478 }
9479 S += '^';
9481
9482 ObjCEncOptions NewOptions;
9483 if (Options.ExpandPointedToStructures())
9484 NewOptions.setExpandStructures();
9485 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9486 /*Field=*/nullptr, NotEncodedT);
9487 return;
9488 }
9489
9490 case Type::ConstantArray:
9491 case Type::IncompleteArray:
9492 case Type::VariableArray: {
9493 const auto *AT = cast<ArrayType>(CT);
9494
9495 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9496 // Incomplete arrays are encoded as a pointer to the array element.
9497 S += '^';
9498
9499 getObjCEncodingForTypeImpl(
9500 AT->getElementType(), S,
9501 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9502 } else {
9503 S += '[';
9504
9505 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9506 S += llvm::utostr(CAT->getZExtSize());
9507 else {
9508 //Variable length arrays are encoded as a regular array with 0 elements.
9510 "Unknown array type!");
9511 S += '0';
9512 }
9513
9514 getObjCEncodingForTypeImpl(
9515 AT->getElementType(), S,
9516 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9517 NotEncodedT);
9518 S += ']';
9519 }
9520 return;
9521 }
9522
9523 case Type::FunctionNoProto:
9524 case Type::FunctionProto:
9525 S += '?';
9526 return;
9527
9528 case Type::Record: {
9529 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9530 S += RDecl->isUnion() ? '(' : '{';
9531 // Anonymous structures print as '?'
9532 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9533 S += II->getName();
9534 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9535 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9536 llvm::raw_string_ostream OS(S);
9537 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9539 }
9540 } else {
9541 S += '?';
9542 }
9543 if (Options.ExpandStructures()) {
9544 S += '=';
9545 if (!RDecl->isUnion()) {
9546 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9547 } else {
9548 for (const auto *Field : RDecl->fields()) {
9549 if (FD) {
9550 S += '"';
9551 S += Field->getNameAsString();
9552 S += '"';
9553 }
9554
9555 // Special case bit-fields.
9556 if (Field->isBitField()) {
9557 getObjCEncodingForTypeImpl(Field->getType(), S,
9558 ObjCEncOptions().setExpandStructures(),
9559 Field);
9560 } else {
9561 QualType qt = Field->getType();
9563 getObjCEncodingForTypeImpl(
9564 qt, S,
9565 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9566 NotEncodedT);
9567 }
9568 }
9569 }
9570 }
9571 S += RDecl->isUnion() ? ')' : '}';
9572 return;
9573 }
9574
9575 case Type::BlockPointer: {
9576 const auto *BT = T->castAs<BlockPointerType>();
9577 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9578 if (Options.EncodeBlockParameters()) {
9579 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9580
9581 S += '<';
9582 // Block return type
9583 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9584 Options.forComponentType(), FD, NotEncodedT);
9585 // Block self
9586 S += "@?";
9587 // Block parameters
9588 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9589 for (const auto &I : FPT->param_types())
9590 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9591 NotEncodedT);
9592 }
9593 S += '>';
9594 }
9595 return;
9596 }
9597
9598 case Type::ObjCObject: {
9599 // hack to match legacy encoding of *id and *Class
9600 QualType Ty = getObjCObjectPointerType(CT);
9601 if (Ty->isObjCIdType()) {
9602 S += "{objc_object=}";
9603 return;
9604 }
9605 else if (Ty->isObjCClassType()) {
9606 S += "{objc_class=}";
9607 return;
9608 }
9609 // TODO: Double check to make sure this intentionally falls through.
9610 [[fallthrough]];
9611 }
9612
9613 case Type::ObjCInterface: {
9614 // Ignore protocol qualifiers when mangling at this level.
9615 // @encode(class_name)
9616 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9617 S += '{';
9618 S += OI->getObjCRuntimeNameAsString();
9619 if (Options.ExpandStructures()) {
9620 S += '=';
9621 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9622 DeepCollectObjCIvars(OI, true, Ivars);
9623 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9624 const FieldDecl *Field = Ivars[i];
9625 if (Field->isBitField())
9626 getObjCEncodingForTypeImpl(Field->getType(), S,
9627 ObjCEncOptions().setExpandStructures(),
9628 Field);
9629 else
9630 getObjCEncodingForTypeImpl(Field->getType(), S,
9631 ObjCEncOptions().setExpandStructures(), FD,
9632 NotEncodedT);
9633 }
9634 }
9635 S += '}';
9636 return;
9637 }
9638
9639 case Type::ObjCObjectPointer: {
9640 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9641 if (OPT->isObjCIdType()) {
9642 S += '@';
9643 return;
9644 }
9645
9646 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9647 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9648 // Since this is a binary compatibility issue, need to consult with
9649 // runtime folks. Fortunately, this is a *very* obscure construct.
9650 S += '#';
9651 return;
9652 }
9653
9654 if (OPT->isObjCQualifiedIdType()) {
9655 getObjCEncodingForTypeImpl(
9656 getObjCIdType(), S,
9657 Options.keepingOnly(ObjCEncOptions()
9658 .setExpandPointedToStructures()
9659 .setExpandStructures()),
9660 FD);
9661 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9662 // Note that we do extended encoding of protocol qualifier list
9663 // Only when doing ivar or property encoding.
9664 S += '"';
9665 for (const auto *I : OPT->quals()) {
9666 S += '<';
9667 S += I->getObjCRuntimeNameAsString();
9668 S += '>';
9669 }
9670 S += '"';
9671 }
9672 return;
9673 }
9674
9675 S += '@';
9676 if (OPT->getInterfaceDecl() &&
9677 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9678 S += '"';
9679 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9680 for (const auto *I : OPT->quals()) {
9681 S += '<';
9682 S += I->getObjCRuntimeNameAsString();
9683 S += '>';
9684 }
9685 S += '"';
9686 }
9687 return;
9688 }
9689
9690 // gcc just blithely ignores member pointers.
9691 // FIXME: we should do better than that. 'M' is available.
9692 case Type::MemberPointer:
9693 // This matches gcc's encoding, even though technically it is insufficient.
9694 //FIXME. We should do a better job than gcc.
9695 case Type::Vector:
9696 case Type::ExtVector:
9697 // Until we have a coherent encoding of these three types, issue warning.
9698 if (NotEncodedT)
9699 *NotEncodedT = T;
9700 return;
9701
9702 case Type::ConstantMatrix:
9703 if (NotEncodedT)
9704 *NotEncodedT = T;
9705 return;
9706
9707 case Type::BitInt:
9708 if (NotEncodedT)
9709 *NotEncodedT = T;
9710 return;
9711
9712 // We could see an undeduced auto type here during error recovery.
9713 // Just ignore it.
9714 case Type::Auto:
9715 case Type::DeducedTemplateSpecialization:
9716 return;
9717
9718 case Type::HLSLAttributedResource:
9719 case Type::HLSLInlineSpirv:
9720 case Type::OverflowBehavior:
9721 llvm_unreachable("unexpected type");
9722
9723 case Type::ArrayParameter:
9724 case Type::Pipe:
9725#define ABSTRACT_TYPE(KIND, BASE)
9726#define TYPE(KIND, BASE)
9727#define DEPENDENT_TYPE(KIND, BASE) \
9728 case Type::KIND:
9729#define NON_CANONICAL_TYPE(KIND, BASE) \
9730 case Type::KIND:
9731#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9732 case Type::KIND:
9733#include "clang/AST/TypeNodes.inc"
9734 llvm_unreachable("@encode for dependent type!");
9735 }
9736 llvm_unreachable("bad type kind!");
9737}
9738
9739void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9740 std::string &S,
9741 const FieldDecl *FD,
9742 bool includeVBases,
9743 QualType *NotEncodedT) const {
9744 assert(RDecl && "Expected non-null RecordDecl");
9745 assert(!RDecl->isUnion() && "Should not be called for unions");
9746 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9747 return;
9748
9749 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9750 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9751 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9752
9753 if (CXXRec) {
9754 for (const auto &BI : CXXRec->bases()) {
9755 if (!BI.isVirtual()) {
9756 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9757 if (base->isEmpty())
9758 continue;
9759 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9760 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9761 std::make_pair(offs, base));
9762 }
9763 }
9764 }
9765
9766 for (FieldDecl *Field : RDecl->fields()) {
9767 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9768 continue;
9769 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9770 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9771 std::make_pair(offs, Field));
9772 }
9773
9774 if (CXXRec && includeVBases) {
9775 for (const auto &BI : CXXRec->vbases()) {
9776 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9777 if (base->isEmpty())
9778 continue;
9779 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9780 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9781 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9782 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9783 std::make_pair(offs, base));
9784 }
9785 }
9786
9787 CharUnits size;
9788 if (CXXRec) {
9789 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9790 } else {
9791 size = layout.getSize();
9792 }
9793
9794#ifndef NDEBUG
9795 uint64_t CurOffs = 0;
9796#endif
9797 std::multimap<uint64_t, NamedDecl *>::iterator
9798 CurLayObj = FieldOrBaseOffsets.begin();
9799
9800 if (CXXRec && CXXRec->isDynamicClass() &&
9801 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9802 if (FD) {
9803 S += "\"_vptr$";
9804 std::string recname = CXXRec->getNameAsString();
9805 if (recname.empty()) recname = "?";
9806 S += recname;
9807 S += '"';
9808 }
9809 S += "^^?";
9810#ifndef NDEBUG
9811 CurOffs += getTypeSize(VoidPtrTy);
9812#endif
9813 }
9814
9815 if (!RDecl->hasFlexibleArrayMember()) {
9816 // Mark the end of the structure.
9817 uint64_t offs = toBits(size);
9818 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9819 std::make_pair(offs, nullptr));
9820 }
9821
9822 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9823#ifndef NDEBUG
9824 assert(CurOffs <= CurLayObj->first);
9825 if (CurOffs < CurLayObj->first) {
9826 uint64_t padding = CurLayObj->first - CurOffs;
9827 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9828 // packing/alignment of members is different that normal, in which case
9829 // the encoding will be out-of-sync with the real layout.
9830 // If the runtime switches to just consider the size of types without
9831 // taking into account alignment, we could make padding explicit in the
9832 // encoding (e.g. using arrays of chars). The encoding strings would be
9833 // longer then though.
9834 CurOffs += padding;
9835 }
9836#endif
9837
9838 NamedDecl *dcl = CurLayObj->second;
9839 if (!dcl)
9840 break; // reached end of structure.
9841
9842 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9843 // We expand the bases without their virtual bases since those are going
9844 // in the initial structure. Note that this differs from gcc which
9845 // expands virtual bases each time one is encountered in the hierarchy,
9846 // making the encoding type bigger than it really is.
9847 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9848 NotEncodedT);
9849 assert(!base->isEmpty());
9850#ifndef NDEBUG
9851 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9852#endif
9853 } else {
9854 const auto *field = cast<FieldDecl>(dcl);
9855 if (FD) {
9856 S += '"';
9857 S += field->getNameAsString();
9858 S += '"';
9859 }
9860
9861 if (field->isBitField()) {
9862 EncodeBitField(this, S, field->getType(), field);
9863#ifndef NDEBUG
9864 CurOffs += field->getBitWidthValue();
9865#endif
9866 } else {
9867 QualType qt = field->getType();
9869 getObjCEncodingForTypeImpl(
9870 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9871 FD, NotEncodedT);
9872#ifndef NDEBUG
9873 CurOffs += getTypeSize(field->getType());
9874#endif
9875 }
9876 }
9877 }
9878}
9879
9881 std::string& S) const {
9882 if (QT & Decl::OBJC_TQ_In)
9883 S += 'n';
9884 if (QT & Decl::OBJC_TQ_Inout)
9885 S += 'N';
9886 if (QT & Decl::OBJC_TQ_Out)
9887 S += 'o';
9888 if (QT & Decl::OBJC_TQ_Bycopy)
9889 S += 'O';
9890 if (QT & Decl::OBJC_TQ_Byref)
9891 S += 'R';
9892 if (QT & Decl::OBJC_TQ_Oneway)
9893 S += 'V';
9894}
9895
9897 if (!ObjCIdDecl) {
9900 ObjCIdDecl = buildImplicitTypedef(T, "id");
9901 }
9902 return ObjCIdDecl;
9903}
9904
9906 if (!ObjCSelDecl) {
9908 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9909 }
9910 return ObjCSelDecl;
9911}
9912
9914 if (!ObjCClassDecl) {
9917 ObjCClassDecl = buildImplicitTypedef(T, "Class");
9918 }
9919 return ObjCClassDecl;
9920}
9921
9923 if (!ObjCProtocolClassDecl) {
9924 ObjCProtocolClassDecl
9927 &Idents.get("Protocol"),
9928 /*typeParamList=*/nullptr,
9929 /*PrevDecl=*/nullptr,
9930 SourceLocation(), true);
9931 }
9932
9933 return ObjCProtocolClassDecl;
9934}
9935
9937 if (!getLangOpts().PointerAuthObjcInterfaceSel)
9938 return PointerAuthQualifier();
9940 getLangOpts().PointerAuthObjcInterfaceSelKey,
9941 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
9943 /*isIsaPointer=*/false,
9944 /*authenticatesNullValues=*/false);
9945}
9946
9947//===----------------------------------------------------------------------===//
9948// __builtin_va_list Construction Functions
9949//===----------------------------------------------------------------------===//
9950
9952 StringRef Name) {
9953 // typedef char* __builtin[_ms]_va_list;
9954 QualType T = Context->getPointerType(Context->CharTy);
9955 return Context->buildImplicitTypedef(T, Name);
9956}
9957
9959 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
9960}
9961
9963 // typedef char *__builtin_zos_va_list[2];
9964 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
9965 QualType T = Context->getPointerType(Context->CharTy);
9966 QualType ArrayType = Context->getConstantArrayType(
9967 T, Size, nullptr, ArraySizeModifier::Normal, 0);
9968 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
9969}
9970
9972 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
9973}
9974
9976 // typedef void* __builtin_va_list;
9977 QualType T = Context->getPointerType(Context->VoidTy);
9978 return Context->buildImplicitTypedef(T, "__builtin_va_list");
9979}
9980
9981static TypedefDecl *
9983 // struct __va_list
9984 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
9985 if (Context->getLangOpts().CPlusPlus) {
9986 // namespace std { struct __va_list {
9987 auto *NS = NamespaceDecl::Create(
9988 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
9989 /*Inline=*/false, SourceLocation(), SourceLocation(),
9990 &Context->Idents.get("std"),
9991 /*PrevDecl=*/nullptr, /*Nested=*/false);
9992 NS->setImplicit();
9994 }
9995
9996 VaListTagDecl->startDefinition();
9997
9998 const size_t NumFields = 5;
9999 QualType FieldTypes[NumFields];
10000 const char *FieldNames[NumFields];
10001
10002 // void *__stack;
10003 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10004 FieldNames[0] = "__stack";
10005
10006 // void *__gr_top;
10007 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10008 FieldNames[1] = "__gr_top";
10009
10010 // void *__vr_top;
10011 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10012 FieldNames[2] = "__vr_top";
10013
10014 // int __gr_offs;
10015 FieldTypes[3] = Context->IntTy;
10016 FieldNames[3] = "__gr_offs";
10017
10018 // int __vr_offs;
10019 FieldTypes[4] = Context->IntTy;
10020 FieldNames[4] = "__vr_offs";
10021
10022 // Create fields
10023 for (unsigned i = 0; i < NumFields; ++i) {
10024 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10028 &Context->Idents.get(FieldNames[i]),
10029 FieldTypes[i], /*TInfo=*/nullptr,
10030 /*BitWidth=*/nullptr,
10031 /*Mutable=*/false,
10032 ICIS_NoInit);
10033 Field->setAccess(AS_public);
10034 VaListTagDecl->addDecl(Field);
10035 }
10036 VaListTagDecl->completeDefinition();
10037 Context->VaListTagDecl = VaListTagDecl;
10038 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10039
10040 // } __builtin_va_list;
10041 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10042}
10043
10045 // typedef struct __va_list_tag {
10047
10048 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10049 VaListTagDecl->startDefinition();
10050
10051 const size_t NumFields = 5;
10052 QualType FieldTypes[NumFields];
10053 const char *FieldNames[NumFields];
10054
10055 // unsigned char gpr;
10056 FieldTypes[0] = Context->UnsignedCharTy;
10057 FieldNames[0] = "gpr";
10058
10059 // unsigned char fpr;
10060 FieldTypes[1] = Context->UnsignedCharTy;
10061 FieldNames[1] = "fpr";
10062
10063 // unsigned short reserved;
10064 FieldTypes[2] = Context->UnsignedShortTy;
10065 FieldNames[2] = "reserved";
10066
10067 // void* overflow_arg_area;
10068 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10069 FieldNames[3] = "overflow_arg_area";
10070
10071 // void* reg_save_area;
10072 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10073 FieldNames[4] = "reg_save_area";
10074
10075 // Create fields
10076 for (unsigned i = 0; i < NumFields; ++i) {
10077 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10080 &Context->Idents.get(FieldNames[i]),
10081 FieldTypes[i], /*TInfo=*/nullptr,
10082 /*BitWidth=*/nullptr,
10083 /*Mutable=*/false,
10084 ICIS_NoInit);
10085 Field->setAccess(AS_public);
10086 VaListTagDecl->addDecl(Field);
10087 }
10088 VaListTagDecl->completeDefinition();
10089 Context->VaListTagDecl = VaListTagDecl;
10090 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10091
10092 // } __va_list_tag;
10093 TypedefDecl *VaListTagTypedefDecl =
10094 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10095
10096 QualType VaListTagTypedefType =
10097 Context->getTypedefType(ElaboratedTypeKeyword::None,
10098 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10099
10100 // typedef __va_list_tag __builtin_va_list[1];
10101 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10102 QualType VaListTagArrayType = Context->getConstantArrayType(
10103 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10104 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10105}
10106
10107static TypedefDecl *
10109 // struct __va_list_tag {
10111 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10112 VaListTagDecl->startDefinition();
10113
10114 const size_t NumFields = 4;
10115 QualType FieldTypes[NumFields];
10116 const char *FieldNames[NumFields];
10117
10118 // unsigned gp_offset;
10119 FieldTypes[0] = Context->UnsignedIntTy;
10120 FieldNames[0] = "gp_offset";
10121
10122 // unsigned fp_offset;
10123 FieldTypes[1] = Context->UnsignedIntTy;
10124 FieldNames[1] = "fp_offset";
10125
10126 // void* overflow_arg_area;
10127 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10128 FieldNames[2] = "overflow_arg_area";
10129
10130 // void* reg_save_area;
10131 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10132 FieldNames[3] = "reg_save_area";
10133
10134 // Create fields
10135 for (unsigned i = 0; i < NumFields; ++i) {
10136 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10140 &Context->Idents.get(FieldNames[i]),
10141 FieldTypes[i], /*TInfo=*/nullptr,
10142 /*BitWidth=*/nullptr,
10143 /*Mutable=*/false,
10144 ICIS_NoInit);
10145 Field->setAccess(AS_public);
10146 VaListTagDecl->addDecl(Field);
10147 }
10148 VaListTagDecl->completeDefinition();
10149 Context->VaListTagDecl = VaListTagDecl;
10150 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10151
10152 // };
10153
10154 // typedef struct __va_list_tag __builtin_va_list[1];
10155 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10156 QualType VaListTagArrayType = Context->getConstantArrayType(
10157 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10158 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10159}
10160
10161static TypedefDecl *
10163 // struct __va_list
10164 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10165 if (Context->getLangOpts().CPlusPlus) {
10166 // namespace std { struct __va_list {
10167 NamespaceDecl *NS;
10168 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10169 Context->getTranslationUnitDecl(),
10170 /*Inline=*/false, SourceLocation(),
10171 SourceLocation(), &Context->Idents.get("std"),
10172 /*PrevDecl=*/nullptr, /*Nested=*/false);
10173 NS->setImplicit();
10174 VaListDecl->setDeclContext(NS);
10175 }
10176
10177 VaListDecl->startDefinition();
10178
10179 // void * __ap;
10180 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10181 VaListDecl,
10184 &Context->Idents.get("__ap"),
10185 Context->getPointerType(Context->VoidTy),
10186 /*TInfo=*/nullptr,
10187 /*BitWidth=*/nullptr,
10188 /*Mutable=*/false,
10189 ICIS_NoInit);
10190 Field->setAccess(AS_public);
10191 VaListDecl->addDecl(Field);
10192
10193 // };
10194 VaListDecl->completeDefinition();
10195 Context->VaListTagDecl = VaListDecl;
10196
10197 // typedef struct __va_list __builtin_va_list;
10198 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10199 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10200}
10201
10202static TypedefDecl *
10204 // struct __va_list_tag {
10206 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10207 VaListTagDecl->startDefinition();
10208
10209 const size_t NumFields = 4;
10210 QualType FieldTypes[NumFields];
10211 const char *FieldNames[NumFields];
10212
10213 // long __gpr;
10214 FieldTypes[0] = Context->LongTy;
10215 FieldNames[0] = "__gpr";
10216
10217 // long __fpr;
10218 FieldTypes[1] = Context->LongTy;
10219 FieldNames[1] = "__fpr";
10220
10221 // void *__overflow_arg_area;
10222 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10223 FieldNames[2] = "__overflow_arg_area";
10224
10225 // void *__reg_save_area;
10226 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10227 FieldNames[3] = "__reg_save_area";
10228
10229 // Create fields
10230 for (unsigned i = 0; i < NumFields; ++i) {
10231 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10235 &Context->Idents.get(FieldNames[i]),
10236 FieldTypes[i], /*TInfo=*/nullptr,
10237 /*BitWidth=*/nullptr,
10238 /*Mutable=*/false,
10239 ICIS_NoInit);
10240 Field->setAccess(AS_public);
10241 VaListTagDecl->addDecl(Field);
10242 }
10243 VaListTagDecl->completeDefinition();
10244 Context->VaListTagDecl = VaListTagDecl;
10245 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10246
10247 // };
10248
10249 // typedef __va_list_tag __builtin_va_list[1];
10250 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10251 QualType VaListTagArrayType = Context->getConstantArrayType(
10252 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10253
10254 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10255}
10256
10258 // typedef struct __va_list_tag {
10260 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10261 VaListTagDecl->startDefinition();
10262
10263 const size_t NumFields = 3;
10264 QualType FieldTypes[NumFields];
10265 const char *FieldNames[NumFields];
10266
10267 // void *CurrentSavedRegisterArea;
10268 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10269 FieldNames[0] = "__current_saved_reg_area_pointer";
10270
10271 // void *SavedRegAreaEnd;
10272 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10273 FieldNames[1] = "__saved_reg_area_end_pointer";
10274
10275 // void *OverflowArea;
10276 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10277 FieldNames[2] = "__overflow_area_pointer";
10278
10279 // Create fields
10280 for (unsigned i = 0; i < NumFields; ++i) {
10282 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10283 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10284 /*TInfo=*/nullptr,
10285 /*BitWidth=*/nullptr,
10286 /*Mutable=*/false, ICIS_NoInit);
10287 Field->setAccess(AS_public);
10288 VaListTagDecl->addDecl(Field);
10289 }
10290 VaListTagDecl->completeDefinition();
10291 Context->VaListTagDecl = VaListTagDecl;
10292 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10293
10294 // } __va_list_tag;
10295 TypedefDecl *VaListTagTypedefDecl =
10296 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10297
10298 QualType VaListTagTypedefType =
10299 Context->getTypedefType(ElaboratedTypeKeyword::None,
10300 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10301
10302 // typedef __va_list_tag __builtin_va_list[1];
10303 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10304 QualType VaListTagArrayType = Context->getConstantArrayType(
10305 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10306
10307 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10308}
10309
10310static TypedefDecl *
10312 // typedef struct __va_list_tag {
10313 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10314
10315 VaListTagDecl->startDefinition();
10316
10317 // int* __va_stk;
10318 // int* __va_reg;
10319 // int __va_ndx;
10320 constexpr size_t NumFields = 3;
10321 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10322 Context->getPointerType(Context->IntTy),
10323 Context->IntTy};
10324 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10325
10326 // Create fields
10327 for (unsigned i = 0; i < NumFields; ++i) {
10330 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10331 /*BitWidth=*/nullptr,
10332 /*Mutable=*/false, ICIS_NoInit);
10333 Field->setAccess(AS_public);
10334 VaListTagDecl->addDecl(Field);
10335 }
10336 VaListTagDecl->completeDefinition();
10337 Context->VaListTagDecl = VaListTagDecl;
10338 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10339
10340 // } __va_list_tag;
10341 TypedefDecl *VaListTagTypedefDecl =
10342 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10343
10344 return VaListTagTypedefDecl;
10345}
10346
10349 switch (Kind) {
10351 return CreateCharPtrBuiltinVaListDecl(Context);
10353 return CreateVoidPtrBuiltinVaListDecl(Context);
10355 return CreateAArch64ABIBuiltinVaListDecl(Context);
10357 return CreatePowerABIBuiltinVaListDecl(Context);
10359 return CreateX86_64ABIBuiltinVaListDecl(Context);
10361 return CreateAAPCSABIBuiltinVaListDecl(Context);
10363 return CreateSystemZBuiltinVaListDecl(Context);
10365 return CreateHexagonBuiltinVaListDecl(Context);
10367 return CreateXtensaABIBuiltinVaListDecl(Context);
10368 }
10369
10370 llvm_unreachable("Unhandled __builtin_va_list type kind");
10371}
10372
10374 if (!BuiltinVaListDecl) {
10375 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10376 assert(BuiltinVaListDecl->isImplicit());
10377 }
10378
10379 return BuiltinVaListDecl;
10380}
10381
10383 // Force the creation of VaListTagDecl by building the __builtin_va_list
10384 // declaration.
10385 if (!VaListTagDecl)
10386 (void)getBuiltinVaListDecl();
10387
10388 return VaListTagDecl;
10389}
10390
10392 if (!BuiltinMSVaListDecl)
10393 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10394
10395 return BuiltinMSVaListDecl;
10396}
10397
10399 if (!BuiltinZOSVaListDecl)
10400 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10401
10402 return BuiltinZOSVaListDecl;
10403}
10404
10406 // Allow redecl custom type checking builtin for HLSL.
10407 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10408 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10409 return true;
10410 // Allow redecl custom type checking builtin for SPIR-V.
10411 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10412 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10413 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10414 return true;
10415 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10416}
10417
10419 assert(ObjCConstantStringType.isNull() &&
10420 "'NSConstantString' type already set!");
10421
10422 ObjCConstantStringType = getObjCInterfaceType(Decl);
10423}
10424
10425/// Retrieve the template name that corresponds to a non-empty
10426/// lookup.
10429 UnresolvedSetIterator End) const {
10430 unsigned size = End - Begin;
10431 assert(size > 1 && "set is not overloaded!");
10432
10433 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10434 size * sizeof(FunctionTemplateDecl*));
10435 auto *OT = new (memory) OverloadedTemplateStorage(size);
10436
10437 NamedDecl **Storage = OT->getStorage();
10438 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10439 NamedDecl *D = *I;
10440 assert(isa<FunctionTemplateDecl>(D) ||
10444 *Storage++ = D;
10445 }
10446
10447 return TemplateName(OT);
10448}
10449
10450/// Retrieve a template name representing an unqualified-id that has been
10451/// assumed to name a template for ADL purposes.
10453 auto *OT = new (*this) AssumedTemplateStorage(Name);
10454 return TemplateName(OT);
10455}
10456
10457/// Retrieve the template name that represents a qualified
10458/// template name such as \c std::vector.
10460 bool TemplateKeyword,
10461 TemplateName Template) const {
10462 assert(Template.getKind() == TemplateName::Template ||
10464
10465 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10466 assert(!Qualifier && "unexpected qualified template template parameter");
10467 assert(TemplateKeyword == false);
10468 return Template;
10469 }
10470
10471 // FIXME: Canonicalization?
10472 llvm::FoldingSetNodeID ID;
10473 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10474
10475 llvm::FoldingSetInsertToken Token;
10476 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10477 if (!QTN) {
10478 QTN = new (*this, alignof(QualifiedTemplateName))
10479 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10480 QualifiedTemplateNames.insert(QTN, Token);
10481 }
10482
10483 return TemplateName(QTN);
10484}
10485
10486/// Retrieve the template name that represents a dependent
10487/// template name such as \c MetaFun::template operator+.
10490 llvm::FoldingSetNodeID ID;
10491 S.Profile(ID);
10492
10493 llvm::FoldingSetInsertToken Token;
10494 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10495 return TemplateName(QTN);
10496
10498 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10499 DependentTemplateNames.insert(QTN, Token);
10500 return TemplateName(QTN);
10501}
10502
10504 Decl *AssociatedDecl,
10505 unsigned Index,
10507 bool Final) const {
10508 llvm::FoldingSetNodeID ID;
10509 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10510 Index, PackIndex, Final);
10511
10512 llvm::FoldingSetInsertToken Token;
10514 SubstTemplateTemplateParms.lookup(ID, Token);
10515
10516 if (!subst) {
10517 subst = new (*this) SubstTemplateTemplateParmStorage(
10518 Replacement, AssociatedDecl, Index, PackIndex, Final);
10519 SubstTemplateTemplateParms.insert(subst, Token);
10520 }
10521
10522 return TemplateName(subst);
10523}
10524
10527 Decl *AssociatedDecl,
10528 unsigned Index, bool Final) const {
10529 auto &Self = const_cast<ASTContext &>(*this);
10530 llvm::FoldingSetNodeID ID;
10532 AssociatedDecl, Index, Final);
10533
10534 llvm::FoldingSetInsertToken Token;
10536 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10537
10538 if (!Subst) {
10539 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10540 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10541 SubstTemplateTemplateParmPacks.insert(Subst, Token);
10542 }
10543
10544 return TemplateName(Subst);
10545}
10546
10547/// Retrieve the template name that represents a template name
10548/// deduced from a specialization.
10551 DefaultArguments DefaultArgs) const {
10552 if (!DefaultArgs)
10553 return Underlying;
10554
10555 llvm::FoldingSetNodeID ID;
10556 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10557
10558 llvm::FoldingSetInsertToken Token;
10559 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10560 if (!DTS) {
10561 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10562 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10563 alignof(DeducedTemplateStorage));
10564 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10565 DeducedTemplates.insert(DTS, Token);
10566 }
10567 return TemplateName(DTS);
10568}
10569
10571 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10572 ArrayRef<TemplateName> Expansions) const {
10573 auto &Self = const_cast<ASTContext &>(*this);
10574 llvm::FoldingSetNodeID ID;
10575 PackIndexingTemplateStorage::Profile(ID, Self, Pattern, IndexExpr,
10576 FullySubstituted, Expansions);
10577
10578 llvm::FoldingSetInsertToken Token;
10579 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10580 if (!PI) {
10581 void *Mem =
10582 Allocate(PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10583 Expansions.size()),
10585 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10586 FullySubstituted, Expansions);
10587 PackIndexingTemplates.insert(PI, Token);
10588 }
10589 return TemplateName(PI);
10590}
10591
10592/// getFromTargetType - Given one of the integer types provided by
10593/// TargetInfo, produce the corresponding type. The unsigned @p Type
10594/// is actually a value of type @c TargetInfo::IntType.
10595CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10596 switch (Type) {
10597 case TargetInfo::NoInt: return {};
10600 case TargetInfo::SignedShort: return ShortTy;
10602 case TargetInfo::SignedInt: return IntTy;
10604 case TargetInfo::SignedLong: return LongTy;
10608 }
10609
10610 llvm_unreachable("Unhandled TargetInfo::IntType value");
10611}
10612
10613//===----------------------------------------------------------------------===//
10614// Type Predicates.
10615//===----------------------------------------------------------------------===//
10616
10617/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10618/// garbage collection attribute.
10619///
10621 if (getLangOpts().getGC() == LangOptions::NonGC)
10622 return Qualifiers::GCNone;
10623
10624 assert(getLangOpts().ObjC);
10625 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10626
10627 // Default behaviour under objective-C's gc is for ObjC pointers
10628 // (or pointers to them) be treated as though they were declared
10629 // as __strong.
10630 if (GCAttrs == Qualifiers::GCNone) {
10632 return Qualifiers::Strong;
10633 else if (Ty->isPointerType())
10635 } else {
10636 // It's not valid to set GC attributes on anything that isn't a
10637 // pointer.
10638#ifndef NDEBUG
10640 while (const auto *AT = dyn_cast<ArrayType>(CT))
10641 CT = AT->getElementType();
10642 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10643#endif
10644 }
10645 return GCAttrs;
10646}
10647
10648//===----------------------------------------------------------------------===//
10649// Type Compatibility Testing
10650//===----------------------------------------------------------------------===//
10651
10652/// areCompatVectorTypes - Return true if the two specified vector types are
10653/// compatible.
10654static bool areCompatVectorTypes(const VectorType *LHS,
10655 const VectorType *RHS) {
10656 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10657 return LHS->getElementType() == RHS->getElementType() &&
10658 LHS->getNumElements() == RHS->getNumElements();
10659}
10660
10661/// areCompatMatrixTypes - Return true if the two specified matrix types are
10662/// compatible.
10664 const ConstantMatrixType *RHS) {
10665 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10666 return LHS->getElementType() == RHS->getElementType() &&
10667 LHS->getNumRows() == RHS->getNumRows() &&
10668 LHS->getNumColumns() == RHS->getNumColumns();
10669}
10670
10672 QualType SecondVec) {
10673 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10674 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10675
10676 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10677 return true;
10678
10679 // Treat Neon vector types and most AltiVec vector types as if they are the
10680 // equivalent GCC vector types.
10681 const auto *First = FirstVec->castAs<VectorType>();
10682 const auto *Second = SecondVec->castAs<VectorType>();
10683 if (First->getNumElements() == Second->getNumElements() &&
10684 hasSameType(First->getElementType(), Second->getElementType()) &&
10685 First->getVectorKind() != VectorKind::AltiVecPixel &&
10686 First->getVectorKind() != VectorKind::AltiVecBool &&
10689 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10690 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10693 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10695 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10697 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10699 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10701 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10703 return true;
10704
10705 // In OpenCL, treat half and _Float16 vector types as compatible.
10706 if (getLangOpts().OpenCL &&
10707 First->getNumElements() == Second->getNumElements()) {
10708 QualType FirstElt = First->getElementType();
10709 QualType SecondElt = Second->getElementType();
10710
10711 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10712 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10713 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10714 First->getVectorKind() != VectorKind::AltiVecBool &&
10717 return true;
10718 }
10719 }
10720 return false;
10721}
10722
10728
10731 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10732 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10733
10734 if (!LHSOBT && !RHSOBT)
10736
10737 if (LHSOBT && RHSOBT) {
10738 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10741 }
10742
10743 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10744 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10745
10746 if (RHSOBT && !LHSOBT) {
10747 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10749 }
10750
10752}
10753
10754/// getRVVTypeSize - Return RVV vector register size.
10755static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10756 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10757 auto VScale = Context.getTargetInfo().getVScaleRange(
10758 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10759 if (!VScale)
10760 return 0;
10761
10762 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10763
10764 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10765 if (Info.ElementType == Context.BoolTy)
10766 EltSize = 1;
10767
10768 uint64_t MinElts = Info.EC.getKnownMinValue();
10769 return VScale->first * MinElts * EltSize;
10770}
10771
10773 QualType SecondType) {
10774 assert(
10775 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10776 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10777 "Expected RVV builtin type and vector type!");
10778
10779 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10780 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10781 if (const auto *VT = SecondType->getAs<VectorType>()) {
10782 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10784 return FirstType->isRVVVLSBuiltinType() &&
10785 Info.ElementType == BoolTy &&
10786 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10787 }
10788 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10790 return FirstType->isRVVVLSBuiltinType() &&
10791 Info.ElementType == BoolTy &&
10792 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10793 }
10794 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10796 return FirstType->isRVVVLSBuiltinType() &&
10797 Info.ElementType == BoolTy &&
10798 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10799 }
10800 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10802 return FirstType->isRVVVLSBuiltinType() &&
10803 Info.ElementType == BoolTy &&
10804 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10805 }
10806 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10807 VT->getVectorKind() == VectorKind::Generic)
10808 return FirstType->isRVVVLSBuiltinType() &&
10809 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10810 hasSameType(VT->getElementType(),
10811 getBuiltinVectorTypeInfo(BT).ElementType);
10812 }
10813 }
10814 return false;
10815 };
10816
10817 return IsValidCast(FirstType, SecondType) ||
10818 IsValidCast(SecondType, FirstType);
10819}
10820
10822 QualType SecondType) {
10823 assert(
10824 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10825 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10826 "Expected RVV builtin type and vector type!");
10827
10828 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10829 const auto *BT = FirstType->getAs<BuiltinType>();
10830 if (!BT)
10831 return false;
10832
10833 if (!BT->isRVVVLSBuiltinType())
10834 return false;
10835
10836 const auto *VecTy = SecondType->getAs<VectorType>();
10837 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10839 getLangOpts().getLaxVectorConversions();
10840
10841 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10842 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10843 return false;
10844
10845 // If -flax-vector-conversions=all is specified, the types are
10846 // certainly compatible.
10848 return true;
10849
10850 // If -flax-vector-conversions=integer is specified, the types are
10851 // compatible if the elements are integer types.
10853 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10854 FirstType->getRVVEltType(*this)->isIntegerType();
10855 }
10856
10857 return false;
10858 };
10859
10860 return IsLaxCompatible(FirstType, SecondType) ||
10861 IsLaxCompatible(SecondType, FirstType);
10862}
10863
10865 while (true) {
10866 // __strong id
10867 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10868 if (Attr->getAttrKind() == attr::ObjCOwnership)
10869 return true;
10870
10871 Ty = Attr->getModifiedType();
10872
10873 // X *__strong (...)
10874 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10875 Ty = Paren->getInnerType();
10876
10877 // We do not want to look through typedefs, typeof(expr),
10878 // typeof(type), or any other way that the type is somehow
10879 // abstracted.
10880 } else {
10881 return false;
10882 }
10883 }
10884}
10885
10886//===----------------------------------------------------------------------===//
10887// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10888//===----------------------------------------------------------------------===//
10889
10890/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10891/// inheritance hierarchy of 'rProto'.
10892bool
10894 ObjCProtocolDecl *rProto) const {
10895 if (declaresSameEntity(lProto, rProto))
10896 return true;
10897 for (auto *PI : rProto->protocols())
10898 if (ProtocolCompatibleWithProtocol(lProto, PI))
10899 return true;
10900 return false;
10901}
10902
10903/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10904/// Class<pr1, ...>.
10906 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10907 for (auto *lhsProto : lhs->quals()) {
10908 bool match = false;
10909 for (auto *rhsProto : rhs->quals()) {
10910 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10911 match = true;
10912 break;
10913 }
10914 }
10915 if (!match)
10916 return false;
10917 }
10918 return true;
10919}
10920
10921/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10922/// ObjCQualifiedIDType.
10924 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10925 bool compare) {
10926 // Allow id<P..> and an 'id' in all cases.
10927 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10928 return true;
10929
10930 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10931 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10933 return false;
10934
10935 if (lhs->isObjCQualifiedIdType()) {
10936 if (rhs->qual_empty()) {
10937 // If the RHS is a unqualified interface pointer "NSString*",
10938 // make sure we check the class hierarchy.
10939 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10940 for (auto *I : lhs->quals()) {
10941 // when comparing an id<P> on lhs with a static type on rhs,
10942 // see if static class implements all of id's protocols, directly or
10943 // through its super class and categories.
10944 if (!rhsID->ClassImplementsProtocol(I, true))
10945 return false;
10946 }
10947 }
10948 // If there are no qualifiers and no interface, we have an 'id'.
10949 return true;
10950 }
10951 // Both the right and left sides have qualifiers.
10952 for (auto *lhsProto : lhs->quals()) {
10953 bool match = false;
10954
10955 // when comparing an id<P> on lhs with a static type on rhs,
10956 // see if static class implements all of id's protocols, directly or
10957 // through its super class and categories.
10958 for (auto *rhsProto : rhs->quals()) {
10959 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10960 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
10961 match = true;
10962 break;
10963 }
10964 }
10965 // If the RHS is a qualified interface pointer "NSString<P>*",
10966 // make sure we check the class hierarchy.
10967 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
10968 for (auto *I : lhs->quals()) {
10969 // when comparing an id<P> on lhs with a static type on rhs,
10970 // see if static class implements all of id's protocols, directly or
10971 // through its super class and categories.
10972 if (rhsID->ClassImplementsProtocol(I, true)) {
10973 match = true;
10974 break;
10975 }
10976 }
10977 }
10978 if (!match)
10979 return false;
10980 }
10981
10982 return true;
10983 }
10984
10985 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
10986
10987 if (lhs->getInterfaceType()) {
10988 // If both the right and left sides have qualifiers.
10989 for (auto *lhsProto : lhs->quals()) {
10990 bool match = false;
10991
10992 // when comparing an id<P> on rhs with a static type on lhs,
10993 // see if static class implements all of id's protocols, directly or
10994 // through its super class and categories.
10995 // First, lhs protocols in the qualifier list must be found, direct
10996 // or indirect in rhs's qualifier list or it is a mismatch.
10997 for (auto *rhsProto : rhs->quals()) {
10998 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
10999 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11000 match = true;
11001 break;
11002 }
11003 }
11004 if (!match)
11005 return false;
11006 }
11007
11008 // Static class's protocols, or its super class or category protocols
11009 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11010 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11011 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11012 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11013 // This is rather dubious but matches gcc's behavior. If lhs has
11014 // no type qualifier and its class has no static protocol(s)
11015 // assume that it is mismatch.
11016 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11017 return false;
11018 for (auto *lhsProto : LHSInheritedProtocols) {
11019 bool match = false;
11020 for (auto *rhsProto : rhs->quals()) {
11021 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11022 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11023 match = true;
11024 break;
11025 }
11026 }
11027 if (!match)
11028 return false;
11029 }
11030 }
11031 return true;
11032 }
11033 return false;
11034}
11035
11036/// canAssignObjCInterfaces - Return true if the two interface types are
11037/// compatible for assignment from RHS to LHS. This handles validation of any
11038/// protocol qualifiers on the LHS or RHS.
11040 const ObjCObjectPointerType *RHSOPT) {
11041 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11042 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11043
11044 // If either type represents the built-in 'id' type, return true.
11045 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11046 return true;
11047
11048 // Function object that propagates a successful result or handles
11049 // __kindof types.
11050 auto finish = [&](bool succeeded) -> bool {
11051 if (succeeded)
11052 return true;
11053
11054 if (!RHS->isKindOfType())
11055 return false;
11056
11057 // Strip off __kindof and protocol qualifiers, then check whether
11058 // we can assign the other way.
11060 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11061 };
11062
11063 // Casts from or to id<P> are allowed when the other side has compatible
11064 // protocols.
11065 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11066 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11067 }
11068
11069 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11070 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11071 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11072 }
11073
11074 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11075 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11076 return true;
11077 }
11078
11079 // If we have 2 user-defined types, fall into that path.
11080 if (LHS->getInterface() && RHS->getInterface()) {
11081 return finish(canAssignObjCInterfaces(LHS, RHS));
11082 }
11083
11084 return false;
11085}
11086
11087/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11088/// for providing type-safety for objective-c pointers used to pass/return
11089/// arguments in block literals. When passed as arguments, passing 'A*' where
11090/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11091/// not OK. For the return type, the opposite is not OK.
11093 const ObjCObjectPointerType *LHSOPT,
11094 const ObjCObjectPointerType *RHSOPT,
11095 bool BlockReturnType) {
11096
11097 // Function object that propagates a successful result or handles
11098 // __kindof types.
11099 auto finish = [&](bool succeeded) -> bool {
11100 if (succeeded)
11101 return true;
11102
11103 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11104 if (!Expected->isKindOfType())
11105 return false;
11106
11107 // Strip off __kindof and protocol qualifiers, then check whether
11108 // we can assign the other way.
11110 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11111 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11112 BlockReturnType);
11113 };
11114
11115 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11116 return true;
11117
11118 if (LHSOPT->isObjCBuiltinType()) {
11119 return finish(RHSOPT->isObjCBuiltinType() ||
11120 RHSOPT->isObjCQualifiedIdType());
11121 }
11122
11123 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11124 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11125 // Use for block parameters previous type checking for compatibility.
11126 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11127 // Or corrected type checking as in non-compat mode.
11128 (!BlockReturnType &&
11129 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11130 else
11132 (BlockReturnType ? LHSOPT : RHSOPT),
11133 (BlockReturnType ? RHSOPT : LHSOPT), false));
11134 }
11135
11136 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11137 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11138 if (LHS && RHS) { // We have 2 user-defined types.
11139 if (LHS != RHS) {
11140 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11141 return finish(BlockReturnType);
11142 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11143 return finish(!BlockReturnType);
11144 }
11145 else
11146 return true;
11147 }
11148 return false;
11149}
11150
11151/// Comparison routine for Objective-C protocols to be used with
11152/// llvm::array_pod_sort.
11154 ObjCProtocolDecl * const *rhs) {
11155 return (*lhs)->getName().compare((*rhs)->getName());
11156}
11157
11158/// getIntersectionOfProtocols - This routine finds the intersection of set
11159/// of protocols inherited from two distinct objective-c pointer objects with
11160/// the given common base.
11161/// It is used to build composite qualifier list of the composite type of
11162/// the conditional expression involving two objective-c pointer objects.
11163static
11165 const ObjCInterfaceDecl *CommonBase,
11166 const ObjCObjectPointerType *LHSOPT,
11167 const ObjCObjectPointerType *RHSOPT,
11168 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11169
11170 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11171 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11172 assert(LHS->getInterface() && "LHS must have an interface base");
11173 assert(RHS->getInterface() && "RHS must have an interface base");
11174
11175 // Add all of the protocols for the LHS.
11177
11178 // Start with the protocol qualifiers.
11179 for (auto *proto : LHS->quals()) {
11180 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11181 }
11182
11183 // Also add the protocols associated with the LHS interface.
11184 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11185
11186 // Add all of the protocols for the RHS.
11188
11189 // Start with the protocol qualifiers.
11190 for (auto *proto : RHS->quals()) {
11191 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11192 }
11193
11194 // Also add the protocols associated with the RHS interface.
11195 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11196
11197 // Compute the intersection of the collected protocol sets.
11198 for (auto *proto : LHSProtocolSet) {
11199 if (RHSProtocolSet.count(proto))
11200 IntersectionSet.push_back(proto);
11201 }
11202
11203 // Compute the set of protocols that is implied by either the common type or
11204 // the protocols within the intersection.
11206 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11207
11208 // Remove any implied protocols from the list of inherited protocols.
11209 if (!ImpliedProtocols.empty()) {
11210 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11211 return ImpliedProtocols.contains(proto);
11212 });
11213 }
11214
11215 // Sort the remaining protocols by name.
11216 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11218}
11219
11220/// Determine whether the first type is a subtype of the second.
11222 QualType rhs) {
11223 // Common case: two object pointers.
11224 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11225 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11226 if (lhsOPT && rhsOPT)
11227 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11228
11229 // Two block pointers.
11230 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11231 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11232 if (lhsBlock && rhsBlock)
11233 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11234
11235 // If either is an unqualified 'id' and the other is a block, it's
11236 // acceptable.
11237 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11238 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11239 return true;
11240
11241 return false;
11242}
11243
11244// Check that the given Objective-C type argument lists are equivalent.
11246 const ObjCInterfaceDecl *iface,
11247 ArrayRef<QualType> lhsArgs,
11248 ArrayRef<QualType> rhsArgs,
11249 bool stripKindOf) {
11250 if (lhsArgs.size() != rhsArgs.size())
11251 return false;
11252
11253 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11254 if (!typeParams)
11255 return false;
11256
11257 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11258 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11259 continue;
11260
11261 switch (typeParams->begin()[i]->getVariance()) {
11263 if (!stripKindOf ||
11264 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11265 rhsArgs[i].stripObjCKindOfType(ctx))) {
11266 return false;
11267 }
11268 break;
11269
11271 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11272 return false;
11273 break;
11274
11276 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11277 return false;
11278 break;
11279 }
11280 }
11281
11282 return true;
11283}
11284
11286 const ObjCObjectPointerType *Lptr,
11287 const ObjCObjectPointerType *Rptr) {
11288 const ObjCObjectType *LHS = Lptr->getObjectType();
11289 const ObjCObjectType *RHS = Rptr->getObjectType();
11290 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11291 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11292
11293 if (!LDecl || !RDecl)
11294 return {};
11295
11296 // When either LHS or RHS is a kindof type, we should return a kindof type.
11297 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11298 // kindof(A).
11299 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11300
11301 // Follow the left-hand side up the class hierarchy until we either hit a
11302 // root or find the RHS. Record the ancestors in case we don't find it.
11303 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11304 LHSAncestors;
11305 while (true) {
11306 // Record this ancestor. We'll need this if the common type isn't in the
11307 // path from the LHS to the root.
11308 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11309
11310 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11311 // Get the type arguments.
11312 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11313 bool anyChanges = false;
11314 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11315 // Both have type arguments, compare them.
11316 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11317 LHS->getTypeArgs(), RHS->getTypeArgs(),
11318 /*stripKindOf=*/true))
11319 return {};
11320 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11321 // If only one has type arguments, the result will not have type
11322 // arguments.
11323 LHSTypeArgs = {};
11324 anyChanges = true;
11325 }
11326
11327 // Compute the intersection of protocols.
11329 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11330 Protocols);
11331 if (!Protocols.empty())
11332 anyChanges = true;
11333
11334 // If anything in the LHS will have changed, build a new result type.
11335 // If we need to return a kindof type but LHS is not a kindof type, we
11336 // build a new result type.
11337 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11338 QualType Result = getObjCInterfaceType(LHS->getInterface());
11339 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11340 anyKindOf || LHS->isKindOfType());
11342 }
11343
11344 return getObjCObjectPointerType(QualType(LHS, 0));
11345 }
11346
11347 // Find the superclass.
11348 QualType LHSSuperType = LHS->getSuperClassType();
11349 if (LHSSuperType.isNull())
11350 break;
11351
11352 LHS = LHSSuperType->castAs<ObjCObjectType>();
11353 }
11354
11355 // We didn't find anything by following the LHS to its root; now check
11356 // the RHS against the cached set of ancestors.
11357 while (true) {
11358 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11359 if (KnownLHS != LHSAncestors.end()) {
11360 LHS = KnownLHS->second;
11361
11362 // Get the type arguments.
11363 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11364 bool anyChanges = false;
11365 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11366 // Both have type arguments, compare them.
11367 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11368 LHS->getTypeArgs(), RHS->getTypeArgs(),
11369 /*stripKindOf=*/true))
11370 return {};
11371 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11372 // If only one has type arguments, the result will not have type
11373 // arguments.
11374 RHSTypeArgs = {};
11375 anyChanges = true;
11376 }
11377
11378 // Compute the intersection of protocols.
11380 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11381 Protocols);
11382 if (!Protocols.empty())
11383 anyChanges = true;
11384
11385 // If we need to return a kindof type but RHS is not a kindof type, we
11386 // build a new result type.
11387 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11388 QualType Result = getObjCInterfaceType(RHS->getInterface());
11389 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11390 anyKindOf || RHS->isKindOfType());
11392 }
11393
11394 return getObjCObjectPointerType(QualType(RHS, 0));
11395 }
11396
11397 // Find the superclass of the RHS.
11398 QualType RHSSuperType = RHS->getSuperClassType();
11399 if (RHSSuperType.isNull())
11400 break;
11401
11402 RHS = RHSSuperType->castAs<ObjCObjectType>();
11403 }
11404
11405 return {};
11406}
11407
11409 const ObjCObjectType *RHS) {
11410 assert(LHS->getInterface() && "LHS is not an interface type");
11411 assert(RHS->getInterface() && "RHS is not an interface type");
11412
11413 // Verify that the base decls are compatible: the RHS must be a subclass of
11414 // the LHS.
11415 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11416 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11417 if (!IsSuperClass)
11418 return false;
11419
11420 // If the LHS has protocol qualifiers, determine whether all of them are
11421 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11422 // LHS).
11423 if (LHS->getNumProtocols() > 0) {
11424 // OK if conversion of LHS to SuperClass results in narrowing of types
11425 // ; i.e., SuperClass may implement at least one of the protocols
11426 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11427 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11428 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11429 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11430 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11431 // qualifiers.
11432 for (auto *RHSPI : RHS->quals())
11433 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11434 // If there is no protocols associated with RHS, it is not a match.
11435 if (SuperClassInheritedProtocols.empty())
11436 return false;
11437
11438 for (const auto *LHSProto : LHS->quals()) {
11439 bool SuperImplementsProtocol = false;
11440 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11441 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11442 SuperImplementsProtocol = true;
11443 break;
11444 }
11445 if (!SuperImplementsProtocol)
11446 return false;
11447 }
11448 }
11449
11450 // If the LHS is specialized, we may need to check type arguments.
11451 if (LHS->isSpecialized()) {
11452 // Follow the superclass chain until we've matched the LHS class in the
11453 // hierarchy. This substitutes type arguments through.
11454 const ObjCObjectType *RHSSuper = RHS;
11455 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11456 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11457
11458 // If the RHS is specializd, compare type arguments.
11459 if (RHSSuper->isSpecialized() &&
11460 !sameObjCTypeArgs(*this, LHS->getInterface(),
11461 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11462 /*stripKindOf=*/true)) {
11463 return false;
11464 }
11465 }
11466
11467 return true;
11468}
11469
11471 // get the "pointed to" types
11472 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11473 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11474
11475 if (!LHSOPT || !RHSOPT)
11476 return false;
11477
11478 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11479 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11480}
11481
11484 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11485 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11486}
11487
11488/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11489/// both shall have the identically qualified version of a compatible type.
11490/// C99 6.2.7p1: Two types have compatible types if their types are the
11491/// same. See 6.7.[2,3,5] for additional rules.
11493 bool CompareUnqualified) {
11494 if (getLangOpts().CPlusPlus)
11495 return hasSameType(LHS, RHS);
11496
11497 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11498}
11499
11501 return typesAreCompatible(LHS, RHS);
11502}
11503
11505 return !mergeTypes(LHS, RHS, true).isNull();
11506}
11507
11508/// mergeTransparentUnionType - if T is a transparent union type and a member
11509/// of T is compatible with SubType, return the merged type, else return
11510/// QualType()
11512 bool OfBlockPointer,
11513 bool Unqualified) {
11514 if (const RecordType *UT = T->getAsUnionType()) {
11515 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11516 if (UD->hasAttr<TransparentUnionAttr>()) {
11517 for (const auto *I : UD->fields()) {
11518 QualType ET = I->getType().getUnqualifiedType();
11519 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11520 if (!MT.isNull())
11521 return MT;
11522 }
11523 }
11524 }
11525
11526 return {};
11527}
11528
11529/// mergeFunctionParameterTypes - merge two types which appear as function
11530/// parameter types
11532 bool OfBlockPointer,
11533 bool Unqualified) {
11534 // GNU extension: two types are compatible if they appear as a function
11535 // argument, one of the types is a transparent union type and the other
11536 // type is compatible with a union member
11537 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11538 Unqualified);
11539 if (!lmerge.isNull())
11540 return lmerge;
11541
11542 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11543 Unqualified);
11544 if (!rmerge.isNull())
11545 return rmerge;
11546
11547 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11548}
11549
11551 bool OfBlockPointer, bool Unqualified,
11552 bool AllowCXX,
11553 bool IsConditionalOperator) {
11554 const auto *lbase = lhs->castAs<FunctionType>();
11555 const auto *rbase = rhs->castAs<FunctionType>();
11556 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11557 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11558 bool allLTypes = true;
11559 bool allRTypes = true;
11560
11561 // Check return type
11562 QualType retType;
11563 if (OfBlockPointer) {
11564 QualType RHS = rbase->getReturnType();
11565 QualType LHS = lbase->getReturnType();
11566 bool UnqualifiedResult = Unqualified;
11567 if (!UnqualifiedResult)
11568 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11569 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11570 }
11571 else
11572 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11573 Unqualified);
11574 if (retType.isNull())
11575 return {};
11576
11577 if (Unqualified)
11578 retType = retType.getUnqualifiedType();
11579
11580 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11581 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11582 if (Unqualified) {
11583 LRetType = LRetType.getUnqualifiedType();
11584 RRetType = RRetType.getUnqualifiedType();
11585 }
11586
11587 if (getCanonicalType(retType) != LRetType)
11588 allLTypes = false;
11589 if (getCanonicalType(retType) != RRetType)
11590 allRTypes = false;
11591
11592 // FIXME: double check this
11593 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11594 // rbase->getRegParmAttr() != 0 &&
11595 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11596 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11597 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11598
11599 // Compatible functions must have compatible calling conventions
11600 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11601 return {};
11602
11603 // Regparm is part of the calling convention.
11604 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11605 return {};
11606 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11607 return {};
11608
11609 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11610 return {};
11611 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11612 return {};
11613 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11614 return {};
11615
11616 // When merging declarations, it's common for supplemental information like
11617 // attributes to only be present in one of the declarations, and we generally
11618 // want type merging to preserve the union of information. So a merged
11619 // function type should be noreturn if it was noreturn in *either* operand
11620 // type.
11621 //
11622 // But for the conditional operator, this is backwards. The result of the
11623 // operator could be either operand, and its type should conservatively
11624 // reflect that. So a function type in a composite type is noreturn only
11625 // if it's noreturn in *both* operand types.
11626 //
11627 // Arguably, noreturn is a kind of subtype, and the conditional operator
11628 // ought to produce the most specific common supertype of its operand types.
11629 // That would differ from this rule in contravariant positions. However,
11630 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11631 // as a practical matter, it would only affect C code that does abstraction of
11632 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11633 // say the least. So we use the simpler rule.
11634 bool NoReturn = IsConditionalOperator
11635 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11636 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11637 if (lbaseInfo.getNoReturn() != NoReturn)
11638 allLTypes = false;
11639 if (rbaseInfo.getNoReturn() != NoReturn)
11640 allRTypes = false;
11641
11642 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11643
11644 std::optional<FunctionEffectSet> MergedFX;
11645
11646 if (lproto && rproto) { // two C99 style function prototypes
11647 assert((AllowCXX ||
11648 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11649 "C++ shouldn't be here");
11650 // Compatible functions must have the same number of parameters
11651 if (lproto->getNumParams() != rproto->getNumParams())
11652 return {};
11653
11654 // Variadic and non-variadic functions aren't compatible
11655 if (lproto->isVariadic() != rproto->isVariadic())
11656 return {};
11657
11658 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11659 return {};
11660
11661 // Function protos with different 'cfi_salt' values aren't compatible.
11662 if (lproto->getExtraAttributeInfo().CFISalt !=
11663 rproto->getExtraAttributeInfo().CFISalt)
11664 return {};
11665
11666 // Function effects are handled similarly to noreturn, see above.
11667 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11668 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11669 if (LHSFX != RHSFX) {
11670 if (IsConditionalOperator)
11671 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11672 else {
11674 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11675 // Here we're discarding a possible error due to conflicts in the effect
11676 // sets. But we're not in a context where we can report it. The
11677 // operation does however guarantee maintenance of invariants.
11678 }
11679 if (*MergedFX != LHSFX)
11680 allLTypes = false;
11681 if (*MergedFX != RHSFX)
11682 allRTypes = false;
11683 }
11684
11686 bool canUseLeft, canUseRight;
11687 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11688 newParamInfos))
11689 return {};
11690
11691 if (!canUseLeft)
11692 allLTypes = false;
11693 if (!canUseRight)
11694 allRTypes = false;
11695
11696 // Check parameter type compatibility
11698 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11699 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11700 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11702 lParamType, rParamType, OfBlockPointer, Unqualified);
11703 if (paramType.isNull())
11704 return {};
11705
11706 if (Unqualified)
11707 paramType = paramType.getUnqualifiedType();
11708
11709 types.push_back(paramType);
11710 if (Unqualified) {
11711 lParamType = lParamType.getUnqualifiedType();
11712 rParamType = rParamType.getUnqualifiedType();
11713 }
11714
11715 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11716 allLTypes = false;
11717 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11718 allRTypes = false;
11719 }
11720
11721 if (allLTypes) return lhs;
11722 if (allRTypes) return rhs;
11723
11724 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11725 EPI.ExtInfo = einfo;
11726 EPI.ExtParameterInfos =
11727 newParamInfos.empty() ? nullptr : newParamInfos.data();
11728 if (MergedFX)
11729 EPI.FunctionEffects = *MergedFX;
11730 return getFunctionType(retType, types, EPI);
11731 }
11732
11733 if (lproto) allRTypes = false;
11734 if (rproto) allLTypes = false;
11735
11736 const FunctionProtoType *proto = lproto ? lproto : rproto;
11737 if (proto) {
11738 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11739 if (proto->isVariadic())
11740 return {};
11741 // Check that the types are compatible with the types that
11742 // would result from default argument promotions (C99 6.7.5.3p15).
11743 // The only types actually affected are promotable integer
11744 // types and floats, which would be passed as a different
11745 // type depending on whether the prototype is visible.
11746 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11747 QualType paramTy = proto->getParamType(i);
11748
11749 // Look at the converted type of enum types, since that is the type used
11750 // to pass enum values.
11751 if (const auto *ED = paramTy->getAsEnumDecl()) {
11752 paramTy = ED->getIntegerType();
11753 if (paramTy.isNull())
11754 return {};
11755 }
11756
11757 if (isPromotableIntegerType(paramTy) ||
11758 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11759 return {};
11760 }
11761
11762 if (allLTypes) return lhs;
11763 if (allRTypes) return rhs;
11764
11766 EPI.ExtInfo = einfo;
11767 if (MergedFX)
11768 EPI.FunctionEffects = *MergedFX;
11769 return getFunctionType(retType, proto->getParamTypes(), EPI);
11770 }
11771
11772 if (allLTypes) return lhs;
11773 if (allRTypes) return rhs;
11774 return getFunctionNoProtoType(retType, einfo);
11775}
11776
11777/// Given that we have an enum type and a non-enum type, try to merge them.
11778static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11779 QualType other, bool isBlockReturnType) {
11780 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11781 // a signed integer type, or an unsigned integer type.
11782 // Compatibility is based on the underlying type, not the promotion
11783 // type.
11784 QualType underlyingType =
11785 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11786 if (underlyingType.isNull())
11787 return {};
11788 if (Context.hasSameType(underlyingType, other))
11789 return other;
11790
11791 // In block return types, we're more permissive and accept any
11792 // integral type of the same size.
11793 if (isBlockReturnType && other->isIntegerType() &&
11794 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11795 return other;
11796
11797 return {};
11798}
11799
11801 // C17 and earlier and C++ disallow two tag definitions within the same TU
11802 // from being compatible.
11803 if (LangOpts.CPlusPlus || !LangOpts.C23)
11804 return {};
11805
11806 // Nameless tags are comparable only within outer definitions. At the top
11807 // level they are not comparable.
11808 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11809 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11810 return {};
11811
11812 // C23, on the other hand, requires the members to be "the same enough", so
11813 // we use a structural equivalence check.
11816 getLangOpts(), *this, *this, NonEquivalentDecls,
11817 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11818 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11819 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11820}
11821
11823 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11824 bool BlockReturnType, bool IsConditionalOperator) {
11825 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11826 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11827
11828 if (!LHSOBT && !RHSOBT)
11829 return std::nullopt;
11830
11831 if (LHSOBT) {
11832 if (RHSOBT) {
11833 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11834 return QualType();
11835
11836 QualType MergedUnderlying = mergeTypes(
11837 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11838 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11839
11840 if (MergedUnderlying.isNull())
11841 return QualType();
11842
11843 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11844 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11845 return getCommonSugaredType(LHS, RHS);
11847 LHSOBT->getBehaviorKind(),
11848 getCanonicalType(LHSOBT->getUnderlyingType()));
11849 }
11850
11851 // For different underlying types that successfully merge, wrap the
11852 // merged underlying type with the common overflow behavior
11853 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11854 MergedUnderlying);
11855 }
11856 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11857 Unqualified, BlockReturnType, IsConditionalOperator);
11858 }
11859
11860 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11861 Unqualified, BlockReturnType, IsConditionalOperator);
11862}
11863
11864QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11865 bool Unqualified, bool BlockReturnType,
11866 bool IsConditionalOperator) {
11867 // For C++ we will not reach this code with reference types (see below),
11868 // for OpenMP variant call overloading we might.
11869 //
11870 // C++ [expr]: If an expression initially has the type "reference to T", the
11871 // type is adjusted to "T" prior to any further analysis, the expression
11872 // designates the object or function denoted by the reference, and the
11873 // expression is an lvalue unless the reference is an rvalue reference and
11874 // the expression is a function call (possibly inside parentheses).
11875 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11876 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11877 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11878 LHS->getTypeClass() == RHS->getTypeClass())
11879 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11880 OfBlockPointer, Unqualified, BlockReturnType);
11881 if (LHSRefTy || RHSRefTy)
11882 return {};
11883
11884 if (std::optional<QualType> MergedOBT =
11885 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11886 BlockReturnType, IsConditionalOperator))
11887 return *MergedOBT;
11888
11889 if (Unqualified) {
11890 LHS = LHS.getUnqualifiedType();
11891 RHS = RHS.getUnqualifiedType();
11892 }
11893
11894 QualType LHSCan = getCanonicalType(LHS),
11895 RHSCan = getCanonicalType(RHS);
11896
11897 // If two types are identical, they are compatible.
11898 if (LHSCan == RHSCan)
11899 return LHS;
11900
11901 // If the qualifiers are different, the types aren't compatible... mostly.
11902 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11903 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11904 if (LQuals != RQuals) {
11905 // If any of these qualifiers are different, we have a type
11906 // mismatch.
11907 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11908 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11909 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11910 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11911 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11912 return {};
11913
11914 // Exactly one GC qualifier difference is allowed: __strong is
11915 // okay if the other type has no GC qualifier but is an Objective
11916 // C object pointer (i.e. implicitly strong by default). We fix
11917 // this by pretending that the unqualified type was actually
11918 // qualified __strong.
11919 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11920 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11921 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11922
11923 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11924 return {};
11925
11926 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11928 }
11929 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11931 }
11932 return {};
11933 }
11934
11935 // Okay, qualifiers are equal.
11936
11937 Type::TypeClass LHSClass = LHSCan->getTypeClass();
11938 Type::TypeClass RHSClass = RHSCan->getTypeClass();
11939
11940 // We want to consider the two function types to be the same for these
11941 // comparisons, just force one to the other.
11942 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
11943 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
11944
11945 // Same as above for arrays
11946 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
11947 LHSClass = Type::ConstantArray;
11948 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
11949 RHSClass = Type::ConstantArray;
11950
11951 // ObjCInterfaces are just specialized ObjCObjects.
11952 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
11953 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
11954
11955 // Canonicalize ExtVector -> Vector.
11956 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
11957 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
11958
11959 // If the canonical type classes don't match.
11960 if (LHSClass != RHSClass) {
11961 // Note that we only have special rules for turning block enum
11962 // returns into block int returns, not vice-versa.
11963 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
11964 return mergeEnumWithInteger(*this, ETy, RHS, false);
11965 }
11966 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
11967 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
11968 }
11969 // allow block pointer type to match an 'id' type.
11970 if (OfBlockPointer && !BlockReturnType) {
11971 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
11972 return LHS;
11973 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
11974 return RHS;
11975 }
11976 // Allow __auto_type to match anything; it merges to the type with more
11977 // information.
11978 if (const auto *AT = LHS->getAs<AutoType>()) {
11979 if (!AT->isDeduced() && AT->isGNUAutoType())
11980 return RHS;
11981 }
11982 if (const auto *AT = RHS->getAs<AutoType>()) {
11983 if (!AT->isDeduced() && AT->isGNUAutoType())
11984 return LHS;
11985 }
11986 return {};
11987 }
11988
11989 // The canonical type classes match.
11990 switch (LHSClass) {
11991#define TYPE(Class, Base)
11992#define ABSTRACT_TYPE(Class, Base)
11993#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
11994#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
11995#define DEPENDENT_TYPE(Class, Base) case Type::Class:
11996#include "clang/AST/TypeNodes.inc"
11997 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
11998
11999 case Type::Auto:
12000 case Type::DeducedTemplateSpecialization:
12001 case Type::LValueReference:
12002 case Type::RValueReference:
12003 case Type::MemberPointer:
12004 llvm_unreachable("C++ should never be in mergeTypes");
12005
12006 case Type::ObjCInterface:
12007 case Type::IncompleteArray:
12008 case Type::VariableArray:
12009 case Type::FunctionProto:
12010 case Type::ExtVector:
12011 case Type::OverflowBehavior:
12012 llvm_unreachable("Types are eliminated above");
12013
12014 case Type::Pointer:
12015 {
12016 // Merge two pointer types, while trying to preserve typedef info
12017 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12018 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12019 if (Unqualified) {
12020 LHSPointee = LHSPointee.getUnqualifiedType();
12021 RHSPointee = RHSPointee.getUnqualifiedType();
12022 }
12023 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12024 Unqualified);
12025 if (ResultType.isNull())
12026 return {};
12027 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12028 return LHS;
12029 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12030 return RHS;
12031 return getPointerType(ResultType);
12032 }
12033 case Type::BlockPointer:
12034 {
12035 // Merge two block pointer types, while trying to preserve typedef info
12036 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12037 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12038 if (Unqualified) {
12039 LHSPointee = LHSPointee.getUnqualifiedType();
12040 RHSPointee = RHSPointee.getUnqualifiedType();
12041 }
12042 if (getLangOpts().OpenCL) {
12043 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12044 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12045 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12046 // 6.12.5) thus the following check is asymmetric.
12047 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12048 return {};
12049 LHSPteeQual.removeAddressSpace();
12050 RHSPteeQual.removeAddressSpace();
12051 LHSPointee =
12052 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12053 RHSPointee =
12054 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12055 }
12056 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12057 Unqualified);
12058 if (ResultType.isNull())
12059 return {};
12060 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12061 return LHS;
12062 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12063 return RHS;
12064 return getBlockPointerType(ResultType);
12065 }
12066 case Type::Atomic:
12067 {
12068 // Merge two pointer types, while trying to preserve typedef info
12069 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12070 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12071 if (Unqualified) {
12072 LHSValue = LHSValue.getUnqualifiedType();
12073 RHSValue = RHSValue.getUnqualifiedType();
12074 }
12075 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12076 Unqualified);
12077 if (ResultType.isNull())
12078 return {};
12079 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12080 return LHS;
12081 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12082 return RHS;
12083 return getAtomicType(ResultType);
12084 }
12085 case Type::ConstantArray:
12086 {
12087 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12088 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12089 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12090 return {};
12091
12092 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12093 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12094 if (Unqualified) {
12095 LHSElem = LHSElem.getUnqualifiedType();
12096 RHSElem = RHSElem.getUnqualifiedType();
12097 }
12098
12099 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12100 if (ResultType.isNull())
12101 return {};
12102
12103 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12104 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12105
12106 // If either side is a variable array, and both are complete, check whether
12107 // the current dimension is definite.
12108 if (LVAT || RVAT) {
12109 auto SizeFetch = [this](const VariableArrayType* VAT,
12110 const ConstantArrayType* CAT)
12111 -> std::pair<bool,llvm::APInt> {
12112 if (VAT) {
12113 std::optional<llvm::APSInt> TheInt;
12114 Expr *E = VAT->getSizeExpr();
12115 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12116 return std::make_pair(true, *TheInt);
12117 return std::make_pair(false, llvm::APSInt());
12118 }
12119 if (CAT)
12120 return std::make_pair(true, CAT->getSize());
12121 return std::make_pair(false, llvm::APInt());
12122 };
12123
12124 bool HaveLSize, HaveRSize;
12125 llvm::APInt LSize, RSize;
12126 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12127 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12128 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12129 return {}; // Definite, but unequal, array dimension
12130 }
12131
12132 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12133 return LHS;
12134 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12135 return RHS;
12136 if (LCAT)
12137 return getConstantArrayType(ResultType, LCAT->getSize(),
12138 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12139 if (RCAT)
12140 return getConstantArrayType(ResultType, RCAT->getSize(),
12141 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12142 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12143 return LHS;
12144 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12145 return RHS;
12146 if (LVAT) {
12147 // FIXME: This isn't correct! But tricky to implement because
12148 // the array's size has to be the size of LHS, but the type
12149 // has to be different.
12150 return LHS;
12151 }
12152 if (RVAT) {
12153 // FIXME: This isn't correct! But tricky to implement because
12154 // the array's size has to be the size of RHS, but the type
12155 // has to be different.
12156 return RHS;
12157 }
12158 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12159 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12160 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12161 }
12162 case Type::FunctionNoProto:
12163 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12164 /*AllowCXX=*/false, IsConditionalOperator);
12165 case Type::Record:
12166 case Type::Enum:
12167 return mergeTagDefinitions(LHS, RHS);
12168 case Type::Builtin:
12169 // Only exactly equal builtin types are compatible, which is tested above.
12170 return {};
12171 case Type::Complex:
12172 // Distinct complex types are incompatible.
12173 return {};
12174 case Type::Vector:
12175 // FIXME: The merged type should be an ExtVector!
12176 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12177 RHSCan->castAs<VectorType>()))
12178 return LHS;
12179 return {};
12180 case Type::ConstantMatrix:
12182 RHSCan->castAs<ConstantMatrixType>()))
12183 return LHS;
12184 return {};
12185 case Type::ObjCObject: {
12186 // Check if the types are assignment compatible.
12187 // FIXME: This should be type compatibility, e.g. whether
12188 // "LHS x; RHS x;" at global scope is legal.
12190 RHS->castAs<ObjCObjectType>()))
12191 return LHS;
12192 return {};
12193 }
12194 case Type::ObjCObjectPointer:
12195 if (OfBlockPointer) {
12198 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12199 return LHS;
12200 return {};
12201 }
12204 return LHS;
12205 return {};
12206 case Type::Pipe:
12207 assert(LHS != RHS &&
12208 "Equivalent pipe types should have already been handled!");
12209 return {};
12210 case Type::ArrayParameter:
12211 assert(LHS != RHS &&
12212 "Equivalent ArrayParameter types should have already been handled!");
12213 return {};
12214 case Type::BitInt: {
12215 // Merge two bit-precise int types, while trying to preserve typedef info.
12216 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12217 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12218 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12219 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12220
12221 // Like unsigned/int, shouldn't have a type if they don't match.
12222 if (LHSUnsigned != RHSUnsigned)
12223 return {};
12224
12225 if (LHSBits != RHSBits)
12226 return {};
12227 return LHS;
12228 }
12229 case Type::HLSLAttributedResource: {
12230 const HLSLAttributedResourceType *LHSTy =
12231 LHS->castAs<HLSLAttributedResourceType>();
12232 const HLSLAttributedResourceType *RHSTy =
12233 RHS->castAs<HLSLAttributedResourceType>();
12234 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12235 LHSTy->getWrappedType()->isHLSLResourceType() &&
12236 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12237
12238 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12239 LHSTy->getContainedType() == RHSTy->getContainedType())
12240 return LHS;
12241 return {};
12242 }
12243 case Type::HLSLInlineSpirv:
12244 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12245 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12246
12247 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12248 LHSTy->getSize() == RHSTy->getSize() &&
12249 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12250 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12251 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12252 return {};
12253
12254 return LHS;
12255 }
12256 return {};
12257 }
12258
12259 llvm_unreachable("Invalid Type::Class!");
12260}
12261
12263 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12264 bool &CanUseFirst, bool &CanUseSecond,
12266 assert(NewParamInfos.empty() && "param info list not empty");
12267 CanUseFirst = CanUseSecond = true;
12268 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12269 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12270
12271 // Fast path: if the first type doesn't have ext parameter infos,
12272 // we match if and only if the second type also doesn't have them.
12273 if (!FirstHasInfo && !SecondHasInfo)
12274 return true;
12275
12276 bool NeedParamInfo = false;
12277 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12278 : SecondFnType->getExtParameterInfos().size();
12279
12280 for (size_t I = 0; I < E; ++I) {
12281 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12282 if (FirstHasInfo)
12283 FirstParam = FirstFnType->getExtParameterInfo(I);
12284 if (SecondHasInfo)
12285 SecondParam = SecondFnType->getExtParameterInfo(I);
12286
12287 // Cannot merge unless everything except the noescape flag matches.
12288 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12289 return false;
12290
12291 bool FirstNoEscape = FirstParam.isNoEscape();
12292 bool SecondNoEscape = SecondParam.isNoEscape();
12293 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12294 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12295 if (NewParamInfos.back().getOpaqueValue())
12296 NeedParamInfo = true;
12297 if (FirstNoEscape != IsNoEscape)
12298 CanUseFirst = false;
12299 if (SecondNoEscape != IsNoEscape)
12300 CanUseSecond = false;
12301 }
12302
12303 if (!NeedParamInfo)
12304 NewParamInfos.clear();
12305
12306 return true;
12307}
12308
12310 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12311 It->second = nullptr;
12312 for (auto *SubClass : ObjCSubClasses.lookup(D))
12313 ResetObjCLayout(SubClass);
12314 }
12315}
12316
12317/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12318/// 'RHS' attributes and returns the merged version; including for function
12319/// return types.
12321 QualType LHSCan = getCanonicalType(LHS),
12322 RHSCan = getCanonicalType(RHS);
12323 // If two types are identical, they are compatible.
12324 if (LHSCan == RHSCan)
12325 return LHS;
12326 if (RHSCan->isFunctionType()) {
12327 if (!LHSCan->isFunctionType())
12328 return {};
12329 QualType OldReturnType =
12330 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12331 QualType NewReturnType =
12332 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12333 QualType ResReturnType =
12334 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12335 if (ResReturnType.isNull())
12336 return {};
12337 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12338 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12339 // In either case, use OldReturnType to build the new function type.
12340 const auto *F = LHS->castAs<FunctionType>();
12341 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12342 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12343 EPI.ExtInfo = getFunctionExtInfo(LHS);
12344 QualType ResultType =
12345 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12346 return ResultType;
12347 }
12348 }
12349 return {};
12350 }
12351
12352 // If the qualifiers are different, the types can still be merged.
12353 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12354 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12355
12356 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12357 // Reject immediately, if anything but the GC qualifiers is different.
12358 return {};
12359 }
12360
12361 if (LQuals != RQuals) {
12362 // Exactly one GC qualifier difference is allowed: __strong is
12363 // okay if the other type has no GC qualifier but is an Objective
12364 // C object pointer (i.e. implicitly strong by default). We fix
12365 // this by pretending that the unqualified type was actually
12366 // qualified __strong.
12367 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12368 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12369 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12370
12371 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12372 return {};
12373
12374 if (GC_L == Qualifiers::Strong)
12375 return LHS;
12376 if (GC_R == Qualifiers::Strong)
12377 return RHS;
12378 return {};
12379 }
12380
12381 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12382 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12383 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12384 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12385 if (ResQT == LHSBaseQT)
12386 return LHS;
12387 if (ResQT == RHSBaseQT)
12388 return RHS;
12389 }
12390 return {};
12391}
12392
12393//===----------------------------------------------------------------------===//
12394// Integer Predicates
12395//===----------------------------------------------------------------------===//
12396
12398 if (const auto *ED = T->getAsEnumDecl())
12399 T = ED->getIntegerType();
12400 if (T->isBooleanType())
12401 return 1;
12402 if (const auto *EIT = T->getAs<BitIntType>())
12403 return EIT->getNumBits();
12404 // For builtin types, just use the standard type sizing method
12405 return (unsigned)getTypeSize(T);
12406}
12407
12409 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12410 T->isFixedPointType()) &&
12411 "Unexpected type");
12412
12413 // Turn <4 x signed int> -> <4 x unsigned int>
12414 if (const auto *VTy = T->getAs<VectorType>())
12415 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12416 VTy->getNumElements(), VTy->getVectorKind());
12417
12418 // For _BitInt, return an unsigned _BitInt with same width.
12419 if (const auto *EITy = T->getAs<BitIntType>())
12420 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12421
12422 // For the overflow behavior types, construct a new unsigned variant
12423 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12425 OBT->getBehaviorKind(),
12426 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12427
12428 // For enums, get the underlying integer type of the enum, and let the general
12429 // integer type signchanging code handle it.
12430 if (const auto *ED = T->getAsEnumDecl())
12431 T = ED->getIntegerType();
12432
12433 switch (T->castAs<BuiltinType>()->getKind()) {
12434 case BuiltinType::Char_U:
12435 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12436 case BuiltinType::Char_S:
12437 case BuiltinType::SChar:
12438 case BuiltinType::Char8:
12439 return UnsignedCharTy;
12440 case BuiltinType::Short:
12441 return UnsignedShortTy;
12442 case BuiltinType::Int:
12443 return UnsignedIntTy;
12444 case BuiltinType::Long:
12445 return UnsignedLongTy;
12446 case BuiltinType::LongLong:
12447 return UnsignedLongLongTy;
12448 case BuiltinType::Int128:
12449 return UnsignedInt128Ty;
12450 // wchar_t is special. It is either signed or not, but when it's signed,
12451 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12452 // version of its underlying type instead.
12453 case BuiltinType::WChar_S:
12454 return getUnsignedWCharType();
12455
12456 case BuiltinType::ShortAccum:
12457 return UnsignedShortAccumTy;
12458 case BuiltinType::Accum:
12459 return UnsignedAccumTy;
12460 case BuiltinType::LongAccum:
12461 return UnsignedLongAccumTy;
12462 case BuiltinType::SatShortAccum:
12464 case BuiltinType::SatAccum:
12465 return SatUnsignedAccumTy;
12466 case BuiltinType::SatLongAccum:
12468 case BuiltinType::ShortFract:
12469 return UnsignedShortFractTy;
12470 case BuiltinType::Fract:
12471 return UnsignedFractTy;
12472 case BuiltinType::LongFract:
12473 return UnsignedLongFractTy;
12474 case BuiltinType::SatShortFract:
12476 case BuiltinType::SatFract:
12477 return SatUnsignedFractTy;
12478 case BuiltinType::SatLongFract:
12480 default:
12481 assert((T->hasUnsignedIntegerRepresentation() ||
12482 T->isUnsignedFixedPointType()) &&
12483 "Unexpected signed integer or fixed point type");
12484 return T;
12485 }
12486}
12487
12489 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12490 T->isFixedPointType()) &&
12491 "Unexpected type");
12492
12493 // Turn <4 x unsigned int> -> <4 x signed int>
12494 if (const auto *VTy = T->getAs<VectorType>())
12495 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12496 VTy->getNumElements(), VTy->getVectorKind());
12497
12498 // For _BitInt, return a signed _BitInt with same width.
12499 if (const auto *EITy = T->getAs<BitIntType>())
12500 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12501
12502 // For enums, get the underlying integer type of the enum, and let the general
12503 // integer type signchanging code handle it.
12504 if (const auto *ED = T->getAsEnumDecl())
12505 T = ED->getIntegerType();
12506
12507 switch (T->castAs<BuiltinType>()->getKind()) {
12508 case BuiltinType::Char_S:
12509 // Plain `char` is mapped to `signed char` even if it's already signed
12510 case BuiltinType::Char_U:
12511 case BuiltinType::UChar:
12512 case BuiltinType::Char8:
12513 return SignedCharTy;
12514 case BuiltinType::UShort:
12515 return ShortTy;
12516 case BuiltinType::UInt:
12517 return IntTy;
12518 case BuiltinType::ULong:
12519 return LongTy;
12520 case BuiltinType::ULongLong:
12521 return LongLongTy;
12522 case BuiltinType::UInt128:
12523 return Int128Ty;
12524 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12525 // there's no matching "signed wchar_t". Therefore we return the signed
12526 // version of its underlying type instead.
12527 case BuiltinType::WChar_U:
12528 return getSignedWCharType();
12529
12530 case BuiltinType::UShortAccum:
12531 return ShortAccumTy;
12532 case BuiltinType::UAccum:
12533 return AccumTy;
12534 case BuiltinType::ULongAccum:
12535 return LongAccumTy;
12536 case BuiltinType::SatUShortAccum:
12537 return SatShortAccumTy;
12538 case BuiltinType::SatUAccum:
12539 return SatAccumTy;
12540 case BuiltinType::SatULongAccum:
12541 return SatLongAccumTy;
12542 case BuiltinType::UShortFract:
12543 return ShortFractTy;
12544 case BuiltinType::UFract:
12545 return FractTy;
12546 case BuiltinType::ULongFract:
12547 return LongFractTy;
12548 case BuiltinType::SatUShortFract:
12549 return SatShortFractTy;
12550 case BuiltinType::SatUFract:
12551 return SatFractTy;
12552 case BuiltinType::SatULongFract:
12553 return SatLongFractTy;
12554 default:
12555 assert(
12556 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12557 "Unexpected signed integer or fixed point type");
12558 return T;
12559 }
12560}
12561
12563
12566
12567//===----------------------------------------------------------------------===//
12568// Builtin Type Computation
12569//===----------------------------------------------------------------------===//
12570
12571/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12572/// pointer over the consumed characters. This returns the resultant type. If
12573/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12574/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12575/// a vector of "i*".
12576///
12577/// RequiresICE is filled in on return to indicate whether the value is required
12578/// to be an Integer Constant Expression.
12579static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12581 bool &RequiresICE,
12582 bool AllowTypeModifiers) {
12583 // Modifiers.
12584 int HowLong = 0;
12585 bool Signed = false, Unsigned = false;
12586 bool IsChar = false, IsShort = false;
12587 RequiresICE = false;
12588
12589 // Read the prefixed modifiers first.
12590 bool Done = false;
12591 #ifndef NDEBUG
12592 bool IsSpecial = false;
12593 #endif
12594 while (!Done) {
12595 switch (*Str++) {
12596 default: Done = true; --Str; break;
12597 case 'I':
12598 RequiresICE = true;
12599 break;
12600 case 'S':
12601 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12602 assert(!Signed && "Can't use 'S' modifier multiple times!");
12603 Signed = true;
12604 break;
12605 case 'U':
12606 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12607 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12608 Unsigned = true;
12609 break;
12610 case 'B':
12611 // This modifier represents int8 type (byte-width).
12612 assert(!IsSpecial &&
12613 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12614 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12615#ifndef NDEBUG
12616 IsSpecial = true;
12617#endif
12618 IsChar = true;
12619 break;
12620 case 'T':
12621 // This modifier represents int16 type (short-width).
12622 assert(!IsSpecial &&
12623 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12624 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12625#ifndef NDEBUG
12626 IsSpecial = true;
12627#endif
12628 IsShort = true;
12629 break;
12630 case 'L':
12631 assert(!IsSpecial &&
12632 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12633 assert(HowLong <= 2 && "Can't have LLLL modifier");
12634 ++HowLong;
12635 break;
12636 case 'N':
12637 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12638 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12639 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12640 #ifndef NDEBUG
12641 IsSpecial = true;
12642 #endif
12643 if (Context.getTargetInfo().getLongWidth() == 32)
12644 ++HowLong;
12645 break;
12646 case 'W':
12647 // This modifier represents int64 type.
12648 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12649 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12650 #ifndef NDEBUG
12651 IsSpecial = true;
12652 #endif
12653 switch (Context.getTargetInfo().getInt64Type()) {
12654 default:
12655 llvm_unreachable("Unexpected integer type");
12657 HowLong = 1;
12658 break;
12660 HowLong = 2;
12661 break;
12662 }
12663 break;
12664 case 'Z':
12665 // This modifier represents int32 type.
12666 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12667 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12668 #ifndef NDEBUG
12669 IsSpecial = true;
12670 #endif
12671 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12672 default:
12673 llvm_unreachable("Unexpected integer type");
12675 HowLong = 0;
12676 break;
12678 HowLong = 1;
12679 break;
12681 HowLong = 2;
12682 break;
12683 }
12684 break;
12685 case 'O':
12686 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12687 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12688 #ifndef NDEBUG
12689 IsSpecial = true;
12690 #endif
12691 if (Context.getLangOpts().OpenCL)
12692 HowLong = 1;
12693 else
12694 HowLong = 2;
12695 break;
12696 }
12697 }
12698
12699 QualType Type;
12700
12701 // Read the base type.
12702 switch (*Str++) {
12703 default:
12704 llvm_unreachable("Unknown builtin type letter!");
12705 case 'x':
12706 assert(HowLong == 0 && !Signed && !Unsigned &&
12707 "Bad modifiers used with 'x'!");
12708 Type = Context.Float16Ty;
12709 break;
12710 case 'y':
12711 assert(HowLong == 0 && !Signed && !Unsigned &&
12712 "Bad modifiers used with 'y'!");
12713 Type = Context.BFloat16Ty;
12714 break;
12715 case 'v':
12716 assert(HowLong == 0 && !Signed && !Unsigned &&
12717 "Bad modifiers used with 'v'!");
12718 Type = Context.VoidTy;
12719 break;
12720 case 'h':
12721 assert(HowLong == 0 && !Signed && !Unsigned &&
12722 "Bad modifiers used with 'h'!");
12723 Type = Context.HalfTy;
12724 break;
12725 case 'f':
12726 assert(HowLong == 0 && !Signed && !Unsigned &&
12727 "Bad modifiers used with 'f'!");
12728 Type = Context.FloatTy;
12729 break;
12730 case 'd':
12731 assert(HowLong < 3 && !Signed && !Unsigned &&
12732 "Bad modifiers used with 'd'!");
12733 if (HowLong == 1)
12734 Type = Context.LongDoubleTy;
12735 else if (HowLong == 2)
12736 Type = Context.Float128Ty;
12737 else
12738 Type = Context.DoubleTy;
12739 break;
12740 case 's':
12741 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12742 if (Unsigned)
12743 Type = Context.UnsignedShortTy;
12744 else
12745 Type = Context.ShortTy;
12746 break;
12747 case 'i':
12748 if (IsChar)
12749 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12750 else if (IsShort)
12751 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12752 else if (HowLong == 3)
12753 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12754 else if (HowLong == 2)
12755 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12756 else if (HowLong == 1)
12757 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12758 else
12759 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12760 break;
12761 case 'c':
12762 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12763 if (Signed)
12764 Type = Context.SignedCharTy;
12765 else if (Unsigned)
12766 Type = Context.UnsignedCharTy;
12767 else
12768 Type = Context.CharTy;
12769 break;
12770 case 'b': // boolean
12771 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12772 Type = Context.BoolTy;
12773 break;
12774 case 'z': // size_t.
12775 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12776 Type = Context.getSizeType();
12777 break;
12778 case 'w': // wchar_t.
12779 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12780 Type = Context.getWideCharType();
12781 break;
12782 case 'F':
12783 Type = Context.getCFConstantStringType();
12784 break;
12785 case 'G':
12786 Type = Context.getObjCIdType();
12787 break;
12788 case 'H':
12789 Type = Context.getObjCSelType();
12790 break;
12791 case 'M':
12792 Type = Context.getObjCSuperType();
12793 break;
12794 case 'a':
12795 Type = Context.getBuiltinVaListType();
12796 assert(!Type.isNull() && "builtin va list type not initialized!");
12797 break;
12798 case 'A':
12799 // This is a "reference" to a va_list; however, what exactly
12800 // this means depends on how va_list is defined. There are two
12801 // different kinds of va_list: ones passed by value, and ones
12802 // passed by reference. An example of a by-value va_list is
12803 // x86, where va_list is a char*. An example of by-ref va_list
12804 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12805 // we want this argument to be a char*&; for x86-64, we want
12806 // it to be a __va_list_tag*.
12807 Type = Context.getBuiltinVaListType();
12808 assert(!Type.isNull() && "builtin va list type not initialized!");
12809 if (Type->isArrayType())
12810 Type = Context.getArrayDecayedType(Type);
12811 else
12812 Type = Context.getLValueReferenceType(Type);
12813 break;
12814 case 'q': {
12815 char *End;
12816 unsigned NumElements = strtoul(Str, &End, 10);
12817 assert(End != Str && "Missing vector size");
12818 Str = End;
12819
12820 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12821 RequiresICE, false);
12822 assert(!RequiresICE && "Can't require vector ICE");
12823
12824 Type = Context.getScalableVectorType(ElementType, NumElements);
12825 break;
12826 }
12827 case 'Q': {
12828 switch (*Str++) {
12829 case 'a': {
12830 Type = Context.SveCountTy;
12831 break;
12832 }
12833 case 'b': {
12834 Type = Context.AMDGPUBufferRsrcTy;
12835 break;
12836 }
12837 case 'c': {
12838 Type = Context.AMDGPUFeaturePredicateTy;
12839 break;
12840 }
12841 case 't': {
12842 Type = Context.AMDGPUTextureTy;
12843 break;
12844 }
12845 case 'r': {
12846 Type = Context.HLSLResourceTy;
12847 break;
12848 }
12849 default:
12850 llvm_unreachable("Unexpected target builtin type");
12851 }
12852 break;
12853 }
12854 case 'V': {
12855 char *End;
12856 unsigned NumElements = strtoul(Str, &End, 10);
12857 assert(End != Str && "Missing vector size");
12858 Str = End;
12859
12860 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12861 RequiresICE, false);
12862 assert(!RequiresICE && "Can't require vector ICE");
12863
12864 // TODO: No way to make AltiVec vectors in builtins yet.
12865 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12866 break;
12867 }
12868 case 'E': {
12869 char *End;
12870
12871 unsigned NumElements = strtoul(Str, &End, 10);
12872 assert(End != Str && "Missing vector size");
12873
12874 Str = End;
12875
12876 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12877 false);
12878 Type = Context.getExtVectorType(ElementType, NumElements);
12879 break;
12880 }
12881 case 'X': {
12882 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12883 false);
12884 assert(!RequiresICE && "Can't require complex ICE");
12885 Type = Context.getComplexType(ElementType);
12886 break;
12887 }
12888 case 'Y':
12889 Type = Context.getPointerDiffType();
12890 break;
12891 case 'P':
12892 Type = Context.getFILEType();
12893 if (Type.isNull()) {
12895 return {};
12896 }
12897 break;
12898 case 'J':
12899 if (Signed)
12900 Type = Context.getsigjmp_bufType();
12901 else
12902 Type = Context.getjmp_bufType();
12903
12904 if (Type.isNull()) {
12906 return {};
12907 }
12908 break;
12909 case 'K':
12910 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12911 Type = Context.getucontext_tType();
12912
12913 if (Type.isNull()) {
12915 return {};
12916 }
12917 break;
12918 case 'p':
12919 Type = Context.getProcessIDType();
12920 break;
12921 case 'm':
12922 Type = Context.MFloat8Ty;
12923 break;
12924 }
12925
12926 // If there are modifiers and if we're allowed to parse them, go for it.
12927 Done = !AllowTypeModifiers;
12928 while (!Done) {
12929 switch (char c = *Str++) {
12930 default: Done = true; --Str; break;
12931 case '*':
12932 case '&': {
12933 // Both pointers and references can have their pointee types
12934 // qualified with an address space.
12935 char *End;
12936 unsigned AddrSpace = strtoul(Str, &End, 10);
12937 if (End != Str) {
12938 // Note AddrSpace == 0 is not the same as an unspecified address space.
12939 Type = Context.getAddrSpaceQualType(
12940 Type,
12941 Context.getLangASForBuiltinAddressSpace(AddrSpace));
12942 Str = End;
12943 }
12944 if (c == '*')
12945 Type = Context.getPointerType(Type);
12946 else
12947 Type = Context.getLValueReferenceType(Type);
12948 break;
12949 }
12950 // FIXME: There's no way to have a built-in with an rvalue ref arg.
12951 case 'C':
12952 Type = Type.withConst();
12953 break;
12954 case 'D':
12955 Type = Context.getVolatileType(Type);
12956 break;
12957 case 'R':
12958 Type = Type.withRestrict();
12959 break;
12960 }
12961 }
12962
12963 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
12964 "Integer constant 'I' type must be an integer");
12965
12966 return Type;
12967}
12968
12969// On some targets such as PowerPC, some of the builtins are defined with custom
12970// type descriptors for target-dependent types. These descriptors are decoded in
12971// other functions, but it may be useful to be able to fall back to default
12972// descriptor decoding to define builtins mixing target-dependent and target-
12973// independent types. This function allows decoding one type descriptor with
12974// default decoding.
12975QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
12976 GetBuiltinTypeError &Error, bool &RequireICE,
12977 bool AllowTypeModifiers) const {
12978 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
12979}
12980
12981/// GetBuiltinType - Return the type for the specified builtin.
12984 unsigned *IntegerConstantArgs) const {
12985 const char *TypeStr = BuiltinInfo.getTypeString(Id);
12986 if (TypeStr[0] == '\0') {
12988 return {};
12989 }
12990
12991 SmallVector<QualType, 8> ArgTypes;
12992
12993 bool RequiresICE = false;
12994 Error = GE_None;
12995 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
12996 RequiresICE, true);
12997 if (Error != GE_None)
12998 return {};
12999
13000 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13001
13002 while (TypeStr[0] && TypeStr[0] != '.') {
13003 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13004 if (Error != GE_None)
13005 return {};
13006
13007 // If this argument is required to be an IntegerConstantExpression and the
13008 // caller cares, fill in the bitmask we return.
13009 if (RequiresICE && IntegerConstantArgs)
13010 *IntegerConstantArgs |= 1 << ArgTypes.size();
13011
13012 // Do array -> pointer decay. The builtin should use the decayed type.
13013 if (Ty->isArrayType())
13014 Ty = getArrayDecayedType(Ty);
13015
13016 ArgTypes.push_back(Ty);
13017 }
13018
13019 if (Id == Builtin::BI__GetExceptionInfo)
13020 return {};
13021
13022 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13023 "'.' should only occur at end of builtin type list!");
13024
13025 bool Variadic = (TypeStr[0] == '.');
13026
13027 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13028 if (BuiltinInfo.isNoReturn(Id))
13029 EI = EI.withNoReturn(true);
13030
13031 // We really shouldn't be making a no-proto type here.
13032 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13033 return getFunctionNoProtoType(ResType, EI);
13034
13036 EPI.ExtInfo = EI;
13037 EPI.Variadic = Variadic;
13038 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13039 EPI.ExceptionSpec.Type =
13041
13042 return getFunctionType(ResType, ArgTypes, EPI);
13043}
13044
13046 const FunctionDecl *FD) {
13047 if (!FD->isExternallyVisible())
13048 return GVA_Internal;
13049
13050 // Non-user-provided functions get emitted as weak definitions with every
13051 // use, no matter whether they've been explicitly instantiated etc.
13052 if (!FD->isUserProvided())
13053 return GVA_DiscardableODR;
13054
13056 switch (FD->getTemplateSpecializationKind()) {
13057 case TSK_Undeclared:
13060 break;
13061
13063 return GVA_StrongODR;
13064
13065 // C++11 [temp.explicit]p10:
13066 // [ Note: The intent is that an inline function that is the subject of
13067 // an explicit instantiation declaration will still be implicitly
13068 // instantiated when used so that the body can be considered for
13069 // inlining, but that no out-of-line copy of the inline function would be
13070 // generated in the translation unit. -- end note ]
13073
13076 break;
13077 }
13078
13079 if (!FD->isInlined())
13080 return External;
13081
13082 if ((!Context.getLangOpts().CPlusPlus &&
13083 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13084 !FD->hasAttr<DLLExportAttr>()) ||
13085 FD->hasAttr<GNUInlineAttr>()) {
13086 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13087
13088 // GNU or C99 inline semantics. Determine whether this symbol should be
13089 // externally visible.
13090 if (auto *Def = FD->getDefinition();
13092 return External;
13093
13094 // C99 inline semantics, where the symbol is not externally visible.
13096 }
13097
13098 // Functions specified with extern and inline in -fms-compatibility mode
13099 // forcibly get emitted. While the body of the function cannot be later
13100 // replaced, the function definition cannot be discarded.
13101 if (FD->isMSExternInline())
13102 return GVA_StrongODR;
13103
13104 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13106 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13107 !FD->hasAttr<DLLExportAttr>()) {
13108 // Both Clang and MSVC implement inherited constructors as forwarding
13109 // thunks that delegate to the base constructor. Keep non-dllexport
13110 // inheriting constructor thunks internal since they are not needed
13111 // outside the translation unit.
13112 //
13113 // dllexport inherited constructors are exempted so they are externally
13114 // visible, matching MSVC's export behavior. Inherited constructors
13115 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13116 // cleanup types) are excluded from export in Sema to avoid silent
13117 // runtime mismatches.
13118 return GVA_Internal;
13119 }
13120
13121 return GVA_DiscardableODR;
13122}
13123
13125 const Decl *D, GVALinkage L) {
13126 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13127 // dllexport/dllimport on inline functions.
13128 if (D->hasAttr<DLLImportAttr>()) {
13129 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13131 } else if (D->hasAttr<DLLExportAttr>()) {
13132 if (L == GVA_DiscardableODR)
13133 return GVA_StrongODR;
13134 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13135 // Device-side functions with __global__ attribute must always be
13136 // visible externally so they can be launched from host.
13137 if (D->hasAttr<CUDAGlobalAttr>() &&
13138 (L == GVA_DiscardableODR || L == GVA_Internal))
13139 return GVA_StrongODR;
13140 // Single source offloading languages like CUDA/HIP need to be able to
13141 // access static device variables from host code of the same compilation
13142 // unit. This is done by externalizing the static variable with a shared
13143 // name between the host and device compilation which is the same for the
13144 // same compilation unit whereas different among different compilation
13145 // units.
13146 if (Context.shouldExternalize(D))
13147 return GVA_StrongExternal;
13148 }
13149 return L;
13150}
13151
13152/// Adjust the GVALinkage for a declaration based on what an external AST source
13153/// knows about whether there can be other definitions of this declaration.
13154static GVALinkage
13156 GVALinkage L) {
13157 ExternalASTSource *Source = Ctx.getExternalSource();
13158 if (!Source)
13159 return L;
13160
13161 switch (Source->hasExternalDefinitions(D)) {
13163 // Other translation units rely on us to provide the definition.
13164 if (L == GVA_DiscardableODR)
13165 return GVA_StrongODR;
13166 break;
13167
13170
13172 break;
13173 }
13174 return L;
13175}
13176
13182
13184 const VarDecl *VD) {
13185 // As an extension for interactive REPLs, make sure constant variables are
13186 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13187 // marking them as internal.
13188 if (Context.getLangOpts().CPlusPlus &&
13189 Context.getLangOpts().IncrementalExtensions &&
13190 VD->getType().isConstQualified() &&
13191 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13193 return GVA_DiscardableODR;
13194
13195 if (!VD->isExternallyVisible())
13196 return GVA_Internal;
13197
13198 if (VD->isStaticLocal()) {
13199 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13200 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13201 LexicalContext = LexicalContext->getLexicalParent();
13202
13203 // ObjC Blocks can create local variables that don't have a FunctionDecl
13204 // LexicalContext.
13205 if (!LexicalContext)
13206 return GVA_DiscardableODR;
13207
13208 // Otherwise, let the static local variable inherit its linkage from the
13209 // nearest enclosing function.
13210 auto StaticLocalLinkage =
13211 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13212
13213 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13214 // be emitted in any object with references to the symbol for the object it
13215 // contains, whether inline or out-of-line."
13216 // Similar behavior is observed with MSVC. An alternative ABI could use
13217 // StrongODR/AvailableExternally to match the function, but none are
13218 // known/supported currently.
13219 if (StaticLocalLinkage == GVA_StrongODR ||
13220 StaticLocalLinkage == GVA_AvailableExternally)
13221 return GVA_DiscardableODR;
13222 return StaticLocalLinkage;
13223 }
13224
13225 // MSVC treats in-class initialized static data members as definitions.
13226 // By giving them non-strong linkage, out-of-line definitions won't
13227 // cause link errors.
13228 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13229 return GVA_DiscardableODR;
13230
13231 // Most non-template variables have strong linkage; inline variables are
13232 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13233 GVALinkage StrongLinkage;
13234 switch (Context.getInlineVariableDefinitionKind(VD)) {
13236 StrongLinkage = GVA_StrongExternal;
13237 break;
13240 StrongLinkage = GVA_DiscardableODR;
13241 break;
13243 StrongLinkage = GVA_StrongODR;
13244 break;
13245 }
13246
13247 switch (VD->getTemplateSpecializationKind()) {
13248 case TSK_Undeclared:
13249 return StrongLinkage;
13250
13252 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13253 VD->isStaticDataMember()
13255 : StrongLinkage;
13256
13258 return GVA_StrongODR;
13259
13262
13264 return GVA_DiscardableODR;
13265 }
13266
13267 llvm_unreachable("Invalid Linkage!");
13268}
13269
13275
13277 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13278 if (!VD->isFileVarDecl())
13279 return false;
13280 // Global named register variables (GNU extension) are never emitted.
13281 if (VD->getStorageClass() == SC_Register)
13282 return false;
13283 if (VD->getDescribedVarTemplate() ||
13285 return false;
13286 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13287 // We never need to emit an uninstantiated function template.
13288 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13289 return false;
13290 } else if (isa<PragmaCommentDecl>(D))
13291 return true;
13293 return true;
13294 else if (isa<OMPRequiresDecl>(D))
13295 return true;
13296 else if (isa<OMPThreadPrivateDecl>(D))
13297 return !D->getDeclContext()->isDependentContext();
13298 else if (isa<OMPAllocateDecl>(D))
13299 return !D->getDeclContext()->isDependentContext();
13301 return !D->getDeclContext()->isDependentContext();
13302 else if (isa<ImportDecl>(D))
13303 return true;
13304 else
13305 return false;
13306
13307 // If this is a member of a class template, we do not need to emit it.
13309 return false;
13310
13311 // Weak references don't produce any output by themselves.
13312 if (D->hasAttr<WeakRefAttr>())
13313 return false;
13314
13315 // SYCL device compilation requires that functions defined with the
13316 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13317 // other entities are emitted only if they are used by a function
13318 // defined with one of those attributes.
13319 if (LangOpts.SYCLIsDevice)
13320 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13321 D->hasAttr<SYCLExternalAttr>());
13322
13323 // Aliases and used decls are required.
13324 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13325 return true;
13326
13327 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13328 // Forward declarations aren't required.
13329 if (!FD->doesThisDeclarationHaveABody())
13330 return FD->doesDeclarationForceExternallyVisibleDefinition();
13331
13332 // Constructors and destructors are required.
13333 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13334 return true;
13335
13336 // The key function for a class is required. This rule only comes
13337 // into play when inline functions can be key functions, though.
13338 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13339 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13340 const CXXRecordDecl *RD = MD->getParent();
13341 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13342 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13343 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13344 return true;
13345 }
13346 }
13347 }
13348
13350
13351 // static, static inline, always_inline, and extern inline functions can
13352 // always be deferred. Normal inline functions can be deferred in C99/C++.
13353 // Implicit template instantiations can also be deferred in C++.
13355 }
13356
13357 const auto *VD = cast<VarDecl>(D);
13358 assert(VD->isFileVarDecl() && "Expected file scoped var");
13359
13360 // If the decl is marked as `declare target to`, it should be emitted for the
13361 // host and for the device.
13362 if (LangOpts.OpenMP &&
13363 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13364 return true;
13365
13366 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13368 return false;
13369
13370 if (VD->shouldEmitInExternalSource())
13371 return false;
13372
13373 // Variables that can be needed in other TUs are required.
13376 return true;
13377
13378 // We never need to emit a variable that is available in another TU.
13380 return false;
13381
13382 // Variables that have destruction with side-effects are required.
13383 if (VD->needsDestruction(*this))
13384 return true;
13385
13386 // Variables that have initialization with side-effects are required.
13387 if (VD->hasInitWithSideEffects())
13388 return true;
13389
13390 // Likewise, variables with tuple-like bindings are required if their
13391 // bindings have side-effects.
13392 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13393 for (const auto *BD : DD->flat_bindings())
13394 if (const auto *BindingVD = BD->getHoldingVar())
13395 if (DeclMustBeEmitted(BindingVD))
13396 return true;
13397 }
13398
13399 return false;
13400}
13401
13403 const FunctionDecl *FD,
13404 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13405 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13406 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13407 FD = FD->getMostRecentDecl();
13408 // FIXME: The order of traversal here matters and depends on the order of
13409 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13410 // shouldn't rely on that.
13411 for (auto *CurDecl :
13413 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13414 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13415 SeenDecls.insert(CurFD).second) {
13416 Pred(CurFD);
13417 }
13418 }
13419}
13420
13422 bool IsCXXMethod) const {
13423 // Pass through to the C++ ABI object
13424 if (IsCXXMethod)
13425 return ABI->getDefaultMethodCallConv(IsVariadic);
13426
13427 switch (LangOpts.getDefaultCallingConv()) {
13429 break;
13431 return CC_C;
13433 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13434 return CC_X86FastCall;
13435 break;
13437 if (!IsVariadic)
13438 return CC_X86StdCall;
13439 break;
13441 // __vectorcall cannot be applied to variadic functions.
13442 if (!IsVariadic)
13443 return CC_X86VectorCall;
13444 break;
13446 // __regcall cannot be applied to variadic functions.
13447 if (!IsVariadic)
13448 return CC_X86RegCall;
13449 break;
13451 if (!IsVariadic)
13452 return CC_M68kRTD;
13453 break;
13454 }
13455 return Target->getDefaultCallingConv();
13456}
13457
13459 // Pass through to the C++ ABI object
13460 return ABI->isNearlyEmpty(RD);
13461}
13462
13464 if (!VTContext) {
13465 auto ABI = Target->getCXXABI();
13466 if (ABI.isMicrosoft())
13467 VTContext.reset(new MicrosoftVTableContext(*this));
13468 else {
13469 VTContext.reset(new ItaniumVTableContext(*this));
13470 }
13471 }
13472 return VTContext.get();
13473}
13474
13476 if (!T)
13477 T = Target;
13478 switch (T->getCXXABI().getKind()) {
13479 case TargetCXXABI::AppleARM64:
13480 case TargetCXXABI::Fuchsia:
13481 case TargetCXXABI::GenericAArch64:
13482 case TargetCXXABI::GenericItanium:
13483 case TargetCXXABI::GenericARM:
13484 case TargetCXXABI::GenericMIPS:
13485 case TargetCXXABI::iOS:
13486 case TargetCXXABI::WebAssembly:
13487 case TargetCXXABI::WatchOS:
13488 case TargetCXXABI::XL:
13490 case TargetCXXABI::Microsoft:
13492 }
13493 llvm_unreachable("Unsupported ABI");
13494}
13495
13497 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13498 "Device mangle context does not support Microsoft mangling.");
13499 switch (T.getCXXABI().getKind()) {
13500 case TargetCXXABI::AppleARM64:
13501 case TargetCXXABI::Fuchsia:
13502 case TargetCXXABI::GenericAArch64:
13503 case TargetCXXABI::GenericItanium:
13504 case TargetCXXABI::GenericARM:
13505 case TargetCXXABI::GenericMIPS:
13506 case TargetCXXABI::iOS:
13507 case TargetCXXABI::WebAssembly:
13508 case TargetCXXABI::WatchOS:
13509 case TargetCXXABI::XL:
13511 *this, getDiagnostics(),
13512 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13513 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13514 return RD->getDeviceLambdaManglingNumber();
13515 return std::nullopt;
13516 },
13517 /*IsAux=*/true);
13518 case TargetCXXABI::Microsoft:
13520 /*IsAux=*/true);
13521 }
13522 llvm_unreachable("Unsupported ABI");
13523}
13524
13526 // If the host and device have different C++ ABIs, mark it as the device
13527 // mangle context so that the mangling needs to retrieve the additional
13528 // device lambda mangling number instead of the regular host one.
13529 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13530 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13532 }
13533
13535}
13536
13537CXXABI::~CXXABI() = default;
13538
13540 return ASTRecordLayouts.getMemorySize() +
13541 llvm::capacity_in_bytes(ObjCLayouts) +
13542 llvm::capacity_in_bytes(KeyFunctions) +
13543 llvm::capacity_in_bytes(ObjCImpls) +
13544 llvm::capacity_in_bytes(BlockVarCopyInits) +
13545 llvm::capacity_in_bytes(DeclAttrs) +
13546 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13547 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13548 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13549 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13550 llvm::capacity_in_bytes(OverriddenMethods) +
13551 llvm::capacity_in_bytes(Types) +
13552 llvm::capacity_in_bytes(VariableArrayTypes);
13553}
13554
13555/// getIntTypeForBitwidth -
13556/// sets integer QualTy according to specified details:
13557/// bitwidth, signed/unsigned.
13558/// Returns empty type if there is no appropriate target types.
13560 unsigned Signed) const {
13562 CanQualType QualTy = getFromTargetType(Ty);
13563 if (!QualTy && DestWidth == 128)
13564 return Signed ? Int128Ty : UnsignedInt128Ty;
13565 return QualTy;
13566}
13567
13569 unsigned Signed) const {
13570 return getFromTargetType(
13571 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13572}
13573
13574/// getRealTypeForBitwidth -
13575/// sets floating point QualTy according to specified bitwidth.
13576/// Returns empty type if there is no appropriate target types.
13578 FloatModeKind ExplicitType) const {
13579 FloatModeKind Ty =
13580 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13581 switch (Ty) {
13583 return HalfTy;
13585 return FloatTy;
13587 return DoubleTy;
13589 return LongDoubleTy;
13591 return Float128Ty;
13593 return Ibm128Ty;
13595 return {};
13596 }
13597
13598 llvm_unreachable("Unhandled TargetInfo::RealType value");
13599}
13600
13601void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13602 if (Number <= 1)
13603 return;
13604
13605 MangleNumbers[ND] = Number;
13606
13607 if (Listener)
13608 Listener->AddedManglingNumber(ND, Number);
13609}
13610
13612 bool ForAuxTarget) const {
13613 auto I = MangleNumbers.find(ND);
13614 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13615 // CUDA/HIP host compilation encodes host and device mangling numbers
13616 // as lower and upper half of 32 bit integer.
13617 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13618 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13619 } else {
13620 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13621 "number for aux target");
13622 }
13623 return Res > 1 ? Res : 1;
13624}
13625
13626void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13627 if (Number <= 1)
13628 return;
13629
13630 StaticLocalNumbers[VD] = Number;
13631
13632 if (Listener)
13633 Listener->AddedStaticLocalNumbers(VD, Number);
13634}
13635
13637 auto I = StaticLocalNumbers.find(VD);
13638 return I != StaticLocalNumbers.end() ? I->second : 1;
13639}
13640
13642 bool IsDestroying) {
13643 if (!IsDestroying) {
13644 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13645 return;
13646 }
13647 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13648}
13649
13651 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13652}
13653
13655 bool IsTypeAware) {
13656 if (!IsTypeAware) {
13657 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13658 return;
13659 }
13660 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13661}
13662
13664 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13665}
13666
13668 FunctionDecl *OperatorDelete,
13669 OperatorDeleteKind K) const {
13670 switch (K) {
13672 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13673 break;
13675 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13676 OperatorDelete;
13677 break;
13679 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13680 OperatorDelete;
13681 break;
13683 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13684 OperatorDelete;
13685 break;
13686 }
13687}
13688
13690 OperatorDeleteKind K) const {
13691 switch (K) {
13693 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13695 return GlobalOperatorDeletesForVirtualDtor.contains(
13696 Dtor->getCanonicalDecl());
13698 return ArrayOperatorDeletesForVirtualDtor.contains(
13699 Dtor->getCanonicalDecl());
13701 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13702 Dtor->getCanonicalDecl());
13703 }
13704 return false;
13705}
13706
13709 OperatorDeleteKind K) const {
13710 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13711 switch (K) {
13713 if (OperatorDeletesForVirtualDtor.contains(Canon))
13714 return OperatorDeletesForVirtualDtor[Canon];
13715 return nullptr;
13717 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13718 return GlobalOperatorDeletesForVirtualDtor[Canon];
13719 return nullptr;
13721 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13722 return ArrayOperatorDeletesForVirtualDtor[Canon];
13723 return nullptr;
13725 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13726 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13727 return nullptr;
13728 }
13729 return nullptr;
13730}
13731
13733 const CXXRecordDecl *RD) {
13734 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13735 return false;
13736
13737 return MaybeRequireVectorDeletingDtor.count(RD);
13738}
13739
13741 const CXXRecordDecl *RD) {
13742 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13743 return;
13744
13745 MaybeRequireVectorDeletingDtor.insert(RD);
13746}
13747
13750 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13751 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13752 if (!MCtx)
13754 return *MCtx;
13755}
13756
13759 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13760 std::unique_ptr<MangleNumberingContext> &MCtx =
13761 ExtraMangleNumberingContexts[D];
13762 if (!MCtx)
13764 return *MCtx;
13765}
13766
13767std::unique_ptr<MangleNumberingContext>
13769 return ABI->createMangleNumberingContext();
13770}
13771
13772const CXXConstructorDecl *
13774 return ABI->getCopyConstructorForExceptionObject(
13776}
13777
13779 CXXConstructorDecl *CD) {
13780 return ABI->addCopyConstructorForExceptionObject(
13783}
13784
13786 TypedefNameDecl *DD) {
13787 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13788}
13789
13792 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13793}
13794
13796 DeclaratorDecl *DD) {
13797 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13798}
13799
13801 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13802}
13803
13805 ParamIndices[D] = index;
13806}
13807
13809 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13810 assert(I != ParamIndices.end() &&
13811 "ParmIndices lacks entry set by ParmVarDecl");
13812 return I->second;
13813}
13814
13816 unsigned Length) const {
13817 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13818 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13819 EltTy = EltTy.withConst();
13820
13821 EltTy = adjustStringLiteralBaseType(EltTy);
13822
13823 // Get an array type for the string, according to C99 6.4.5. This includes
13824 // the null terminator character.
13825 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13826 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13827}
13828
13831 StringLiteral *&Result = StringLiteralCache[Key];
13832 if (!Result)
13834 *this, Key, StringLiteralKind::Ordinary,
13835 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13836 SourceLocation());
13837 return Result;
13838}
13839
13840MSGuidDecl *
13842 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13843
13844 llvm::FoldingSetNodeID ID;
13845 MSGuidDecl::Profile(ID, Parts);
13846
13847 llvm::FoldingSetInsertToken Token;
13848 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13849 return Existing;
13850
13851 QualType GUIDType = getMSGuidType().withConst();
13852 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13853 MSGuidDecls.insert(New, Token);
13854 return New;
13855}
13856
13859 const APValue &APVal) const {
13860 llvm::FoldingSetNodeID ID;
13862
13863 llvm::FoldingSetInsertToken Token;
13864 if (UnnamedGlobalConstantDecl *Existing =
13865 UnnamedGlobalConstantDecls.lookup(ID, Token))
13866 return Existing;
13867
13869 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13870 UnnamedGlobalConstantDecls.insert(New, Token);
13871 return New;
13872}
13873
13876 assert(T->isRecordType() && "template param object of unexpected type");
13877
13878 // C++ [temp.param]p8:
13879 // [...] a static storage duration object of type 'const T' [...]
13880 T.addConst();
13881
13882 llvm::FoldingSetNodeID ID;
13884
13885 llvm::FoldingSetInsertToken Token;
13886 if (TemplateParamObjectDecl *Existing =
13887 TemplateParamObjectDecls.lookup(ID, Token))
13888 return Existing;
13889
13890 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13891 TemplateParamObjectDecls.insert(New, Token);
13892 return New;
13893}
13894
13896 const llvm::Triple &T = getTargetInfo().getTriple();
13897 if (!T.isOSDarwin())
13898 return false;
13899
13900 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13901 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13902 return false;
13903
13904 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13905 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13906 uint64_t Size = sizeChars.getQuantity();
13907 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13908 unsigned Align = alignChars.getQuantity();
13909 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13910 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13911}
13912
13913bool
13915 const ObjCMethodDecl *MethodImpl) {
13916 // No point trying to match an unavailable/deprecated mothod.
13917 if (MethodDecl->hasAttr<UnavailableAttr>()
13918 || MethodDecl->hasAttr<DeprecatedAttr>())
13919 return false;
13920 if (MethodDecl->getObjCDeclQualifier() !=
13921 MethodImpl->getObjCDeclQualifier())
13922 return false;
13923 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13924 return false;
13925
13926 if (MethodDecl->param_size() != MethodImpl->param_size())
13927 return false;
13928
13929 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13930 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13931 EF = MethodDecl->param_end();
13932 IM != EM && IF != EF; ++IM, ++IF) {
13933 const ParmVarDecl *DeclVar = (*IF);
13934 const ParmVarDecl *ImplVar = (*IM);
13935 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13936 return false;
13937 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
13938 return false;
13939 }
13940
13941 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
13942}
13943
13945 LangAS AS;
13947 AS = LangAS::Default;
13948 else
13949 AS = QT->getPointeeType().getAddressSpace();
13950
13952}
13953
13956}
13957
13958bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
13959 if (X == Y)
13960 return true;
13961 if (!X || !Y)
13962 return false;
13963 llvm::FoldingSetNodeID IDX, IDY;
13964 X->Profile(IDX, *this, /*Canonical=*/true);
13965 Y->Profile(IDY, *this, /*Canonical=*/true);
13966 return IDX == IDY;
13967}
13968
13969// The getCommon* helpers return, for given 'same' X and Y entities given as
13970// inputs, another entity which is also the 'same' as the inputs, but which
13971// is closer to the canonical form of the inputs, each according to a given
13972// criteria.
13973// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
13974// the regular ones.
13975
13977 if (!declaresSameEntity(X, Y))
13978 return nullptr;
13979 for (const Decl *DX : X->redecls()) {
13980 // If we reach Y before reaching the first decl, that means X is older.
13981 if (DX == Y)
13982 return X;
13983 // If we reach the first decl, then Y is older.
13984 if (DX->isFirstDecl())
13985 return Y;
13986 }
13987 llvm_unreachable("Corrupt redecls chain");
13988}
13989
13990template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13991static T *getCommonDecl(T *X, T *Y) {
13992 return cast_or_null<T>(
13993 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
13994 const_cast<Decl *>(cast_or_null<Decl>(Y))));
13995}
13996
13997template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
13998static T *getCommonDeclChecked(T *X, T *Y) {
13999 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14000 const_cast<Decl *>(cast<Decl>(Y))));
14001}
14002
14004 TemplateName Y,
14005 bool IgnoreDeduced = false) {
14006 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14007 return X;
14008 // FIXME: There are cases here where we could find a common template name
14009 // with more sugar. For example one could be a SubstTemplateTemplate*
14010 // replacing the other.
14011 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14012 if (CX.getAsVoidPointer() !=
14014 return TemplateName();
14015 return CX;
14016}
14017
14020 bool IgnoreDeduced) {
14021 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14022 assert(R.getAsVoidPointer() != nullptr);
14023 return R;
14024}
14025
14027 ArrayRef<QualType> Ys, bool Unqualified = false) {
14028 assert(Xs.size() == Ys.size());
14029 SmallVector<QualType, 8> Rs(Xs.size());
14030 for (size_t I = 0; I < Rs.size(); ++I)
14031 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14032 return Rs;
14033}
14034
14035template <class T>
14036static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14037 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14038 : SourceLocation();
14039}
14040
14042 const TemplateArgument &X,
14043 const TemplateArgument &Y) {
14044 if (X.getKind() != Y.getKind())
14045 return TemplateArgument();
14046
14047 switch (X.getKind()) {
14049 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14050 return TemplateArgument();
14051 return TemplateArgument(
14052 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14054 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14055 return TemplateArgument();
14056 return TemplateArgument(
14057 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14058 /*Unqualified=*/true);
14060 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14061 return TemplateArgument();
14062 // FIXME: Try to keep the common sugar.
14063 return X;
14065 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14066 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14067 if (!CTN.getAsVoidPointer())
14068 return TemplateArgument();
14069 return TemplateArgument(CTN);
14070 }
14072 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14074 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14075 if (!CTN.getAsVoidPointer())
14076 return TemplateName();
14077 auto NExpX = X.getNumTemplateExpansions();
14078 assert(NExpX == Y.getNumTemplateExpansions());
14079 return TemplateArgument(CTN, NExpX);
14080 }
14081 default:
14082 // FIXME: Handle the other argument kinds.
14083 return X;
14084 }
14085}
14086
14091 if (Xs.size() != Ys.size())
14092 return true;
14093 R.resize(Xs.size());
14094 for (size_t I = 0; I < R.size(); ++I) {
14095 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14096 if (R[I].isNull())
14097 return true;
14098 }
14099 return false;
14100}
14101
14106 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14107 assert(!Different);
14108 (void)Different;
14109 return R;
14110}
14111
14112template <class T>
14114 bool IsSame) {
14115 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14116 if (KX == KY)
14117 return KX;
14119 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14120 return KX;
14121}
14122
14123/// Returns a NestedNameSpecifier which has only the common sugar
14124/// present in both NNS1 and NNS2.
14127 NestedNameSpecifier NNS2, bool IsSame) {
14128 // If they are identical, all sugar is common.
14129 if (NNS1 == NNS2)
14130 return NNS1;
14131
14132 // IsSame implies both Qualifiers are equivalent.
14133 NestedNameSpecifier Canon = NNS1.getCanonical();
14134 if (Canon != NNS2.getCanonical()) {
14135 assert(!IsSame && "Should be the same NestedNameSpecifier");
14136 // If they are not the same, there is nothing to unify.
14137 return std::nullopt;
14138 }
14139
14140 NestedNameSpecifier R = std::nullopt;
14141 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14142 assert(Kind == NNS2.getKind());
14143 switch (Kind) {
14145 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14146 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14147 auto Kind = Namespace1->getKind();
14148 if (Kind != Namespace2->getKind() ||
14149 (Kind == Decl::NamespaceAlias &&
14150 !declaresSameEntity(Namespace1, Namespace2))) {
14152 Ctx,
14153 ::getCommonDeclChecked(Namespace1->getNamespace(),
14154 Namespace2->getNamespace()),
14155 /*Prefix=*/std::nullopt);
14156 break;
14157 }
14158 // The prefixes for namespaces are not significant, its declaration
14159 // identifies it uniquely.
14160 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14161 /*IsSame=*/false);
14162 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14163 Prefix);
14164 break;
14165 }
14167 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14168 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14169 /*Unqualified=*/true)
14170 .getTypePtr();
14172 break;
14173 }
14175 // FIXME: Can __super even be used with data members?
14176 // If it's only usable in functions, we will never see it here,
14177 // unless we save the qualifiers used in function types.
14178 // In that case, it might be possible NNS2 is a type,
14179 // in which case we should degrade the result to
14180 // a CXXRecordType.
14182 NNS2.getAsMicrosoftSuper()));
14183 break;
14184 }
14187 // These are singletons.
14188 llvm_unreachable("singletons did not compare equal");
14189 }
14190 assert(R.getCanonical() == Canon);
14191 return R;
14192}
14193
14194template <class T>
14196 const T *Y, bool IsSame) {
14197 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14198}
14199
14200template <class T>
14201static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14202 const T *Y) {
14203 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14204}
14205
14207 QualType X, QualType Y,
14208 Qualifiers &QX,
14209 Qualifiers &QY) {
14210 QualType R = Ctx.getCommonSugaredType(X, Y,
14211 /*Unqualified=*/true);
14212 // Qualifiers common to both element types.
14213 Qualifiers RQ = R.getQualifiers();
14214 // For each side, move to the top level any qualifiers which are not common to
14215 // both element types. The caller must assume top level qualifiers might
14216 // be different, even if they are the same type, and can be treated as sugar.
14217 QX += X.getQualifiers() - RQ;
14218 QY += Y.getQualifiers() - RQ;
14219 return R;
14220}
14221
14222template <class T>
14224 Qualifiers &QX, const T *Y,
14225 Qualifiers &QY) {
14226 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14227 Y->getElementType(), QX, QY);
14228}
14229
14230template <class T>
14231static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14232 const T *Y) {
14233 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14234}
14235
14236template <class T>
14237static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14238 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14239 return X->getSizeExpr();
14240}
14241
14242static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14243 assert(X->getSizeModifier() == Y->getSizeModifier());
14244 return X->getSizeModifier();
14245}
14246
14248 const ArrayType *Y) {
14249 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14250 return X->getIndexTypeCVRQualifiers();
14251}
14252
14253// Merges two type lists such that the resulting vector will contain
14254// each type (in a canonical sense) only once, in the order they appear
14255// from X to Y. If they occur in both X and Y, the result will contain
14256// the common sugared type between them.
14257static void mergeTypeLists(const ASTContext &Ctx,
14260 llvm::DenseMap<QualType, unsigned> Found;
14261 for (auto Ts : {X, Y}) {
14262 for (QualType T : Ts) {
14263 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14264 if (!Res.second) {
14265 QualType &U = Out[Res.first->second];
14266 U = Ctx.getCommonSugaredType(U, T);
14267 } else {
14268 Out.emplace_back(T);
14269 }
14270 }
14271 }
14272}
14273
14274FunctionProtoType::ExceptionSpecInfo
14277 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14278 bool AcceptDependent) const {
14279 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14280
14281 // If either of them can throw anything, that is the result.
14282 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14283 if (EST1 == I)
14284 return ESI1;
14285 if (EST2 == I)
14286 return ESI2;
14287 }
14288
14289 // If either of them is non-throwing, the result is the other.
14290 for (auto I :
14292 if (EST1 == I)
14293 return ESI2;
14294 if (EST2 == I)
14295 return ESI1;
14296 }
14297
14298 // If we're left with value-dependent computed noexcept expressions, we're
14299 // stuck. Before C++17, we can just drop the exception specification entirely,
14300 // since it's not actually part of the canonical type. And this should never
14301 // happen in C++17, because it would mean we were computing the composite
14302 // pointer type of dependent types, which should never happen.
14303 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14304 assert(AcceptDependent &&
14305 "computing composite pointer type of dependent types");
14307 }
14308
14309 // Switch over the possibilities so that people adding new values know to
14310 // update this function.
14311 switch (EST1) {
14312 case EST_None:
14313 case EST_DynamicNone:
14314 case EST_MSAny:
14315 case EST_BasicNoexcept:
14317 case EST_NoexceptFalse:
14318 case EST_NoexceptTrue:
14319 case EST_NoThrow:
14320 llvm_unreachable("These ESTs should be handled above");
14321
14322 case EST_Dynamic: {
14323 // This is the fun case: both exception specifications are dynamic. Form
14324 // the union of the two lists.
14325 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14326 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14327 ESI2.Exceptions);
14329 Result.Exceptions = ExceptionTypeStorage;
14330 return Result;
14331 }
14332
14333 case EST_Unevaluated:
14334 case EST_Uninstantiated:
14335 case EST_Unparsed:
14336 llvm_unreachable("shouldn't see unresolved exception specifications here");
14337 }
14338
14339 llvm_unreachable("invalid ExceptionSpecificationType");
14340}
14341
14343 Qualifiers &QX, const Type *Y,
14344 Qualifiers &QY) {
14345 Type::TypeClass TC = X->getTypeClass();
14346 assert(TC == Y->getTypeClass());
14347 switch (TC) {
14348#define UNEXPECTED_TYPE(Class, Kind) \
14349 case Type::Class: \
14350 llvm_unreachable("Unexpected " Kind ": " #Class);
14351
14352#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14353#define TYPE(Class, Base)
14354#include "clang/AST/TypeNodes.inc"
14355
14356#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14358 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14359 SUGAR_FREE_TYPE(DependentBitInt)
14361 SUGAR_FREE_TYPE(ObjCInterface)
14362 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14363 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14364 SUGAR_FREE_TYPE(UnresolvedUsing)
14365 SUGAR_FREE_TYPE(HLSLAttributedResource)
14366 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14367#undef SUGAR_FREE_TYPE
14368#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14369 NON_UNIQUE_TYPE(TypeOfExpr)
14370 NON_UNIQUE_TYPE(VariableArray)
14371#undef NON_UNIQUE_TYPE
14372
14373 UNEXPECTED_TYPE(TypeOf, "sugar")
14374
14375#undef UNEXPECTED_TYPE
14376
14377 case Type::Auto: {
14378 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14379 assert(AX->getDeducedKind() == AY->getDeducedKind());
14380 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14381 assert(AX->getKeyword() == AY->getKeyword());
14382 TemplateDecl *CD =
14383 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14384 AY->getTypeConstraintConcept().getAsTemplateDecl());
14386 if (CD &&
14387 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14388 AY->getTypeConstraintArguments())) {
14389 CD = nullptr; // The arguments differ, so make it unconstrained.
14390 As.clear();
14391 }
14392 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14393 TemplateName(CD), As);
14394 }
14395 case Type::IncompleteArray: {
14396 const auto *AX = cast<IncompleteArrayType>(X),
14398 return Ctx.getIncompleteArrayType(
14399 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14401 }
14402 case Type::DependentSizedArray: {
14403 const auto *AX = cast<DependentSizedArrayType>(X),
14405 return Ctx.getDependentSizedArrayType(
14406 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14407 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14409 }
14410 case Type::ConstantArray: {
14411 const auto *AX = cast<ConstantArrayType>(X),
14412 *AY = cast<ConstantArrayType>(Y);
14413 assert(AX->getSize() == AY->getSize());
14414 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14415 ? AX->getSizeExpr()
14416 : nullptr;
14417 return Ctx.getConstantArrayType(
14418 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14420 }
14421 case Type::ArrayParameter: {
14422 const auto *AX = cast<ArrayParameterType>(X),
14423 *AY = cast<ArrayParameterType>(Y);
14424 assert(AX->getSize() == AY->getSize());
14425 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14426 ? AX->getSizeExpr()
14427 : nullptr;
14428 auto ArrayTy = Ctx.getConstantArrayType(
14429 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14431 return Ctx.getArrayParameterType(ArrayTy);
14432 }
14433 case Type::Atomic: {
14434 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14435 return Ctx.getAtomicType(
14436 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14437 }
14438 case Type::Complex: {
14439 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14440 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14441 }
14442 case Type::Pointer: {
14443 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14444 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14445 }
14446 case Type::BlockPointer: {
14447 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14448 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14449 }
14450 case Type::ObjCObjectPointer: {
14451 const auto *PX = cast<ObjCObjectPointerType>(X),
14453 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14454 }
14455 case Type::MemberPointer: {
14456 const auto *PX = cast<MemberPointerType>(X),
14457 *PY = cast<MemberPointerType>(Y);
14458 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14459 PY->getMostRecentCXXRecordDecl()));
14460 return Ctx.getMemberPointerType(
14461 getCommonPointeeType(Ctx, PX, PY),
14462 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14463 PX->getMostRecentCXXRecordDecl());
14464 }
14465 case Type::LValueReference: {
14466 const auto *PX = cast<LValueReferenceType>(X),
14468 // FIXME: Preserve PointeeTypeAsWritten.
14469 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14470 PX->isSpelledAsLValue() ||
14471 PY->isSpelledAsLValue());
14472 }
14473 case Type::RValueReference: {
14474 const auto *PX = cast<RValueReferenceType>(X),
14476 // FIXME: Preserve PointeeTypeAsWritten.
14477 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14478 }
14479 case Type::DependentAddressSpace: {
14480 const auto *PX = cast<DependentAddressSpaceType>(X),
14482 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14483 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14484 PX->getAddrSpaceExpr(),
14485 getCommonAttrLoc(PX, PY));
14486 }
14487 case Type::FunctionNoProto: {
14488 const auto *FX = cast<FunctionNoProtoType>(X),
14490 assert(FX->getExtInfo() == FY->getExtInfo());
14491 return Ctx.getFunctionNoProtoType(
14492 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14493 FX->getExtInfo());
14494 }
14495 case Type::FunctionProto: {
14496 const auto *FX = cast<FunctionProtoType>(X),
14497 *FY = cast<FunctionProtoType>(Y);
14498 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14499 EPIY = FY->getExtProtoInfo();
14500 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14501 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14502 assert(!EPIX.ExtParameterInfos ||
14503 llvm::equal(
14504 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14505 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14506 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14507 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14508 assert(EPIX.Variadic == EPIY.Variadic);
14509
14510 // FIXME: Can we handle an empty EllipsisLoc?
14511 // Use emtpy EllipsisLoc if X and Y differ.
14512
14513 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14514
14515 QualType R =
14516 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14517 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14518 /*Unqualified=*/true);
14519
14520 SmallVector<QualType, 8> Exceptions;
14522 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14523 return Ctx.getFunctionType(R, P, EPIX);
14524 }
14525 case Type::ObjCObject: {
14526 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14527 assert(
14528 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14529 OY->getProtocols().begin(), OY->getProtocols().end(),
14530 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14531 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14532 }) &&
14533 "protocol lists must be the same");
14534 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14535 OY->getTypeArgsAsWritten());
14536 return Ctx.getObjCObjectType(
14537 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14538 OX->getProtocols(),
14539 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14540 }
14541 case Type::ConstantMatrix: {
14542 const auto *MX = cast<ConstantMatrixType>(X),
14543 *MY = cast<ConstantMatrixType>(Y);
14544 assert(MX->getNumRows() == MY->getNumRows());
14545 assert(MX->getNumColumns() == MY->getNumColumns());
14546 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14547 MX->getNumRows(), MX->getNumColumns());
14548 }
14549 case Type::DependentSizedMatrix: {
14550 const auto *MX = cast<DependentSizedMatrixType>(X),
14552 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14553 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14554 return Ctx.getDependentSizedMatrixType(
14555 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14556 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14557 }
14558 case Type::Vector: {
14559 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14560 assert(VX->getNumElements() == VY->getNumElements());
14561 assert(VX->getVectorKind() == VY->getVectorKind());
14562 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14563 VX->getNumElements(), VX->getVectorKind());
14564 }
14565 case Type::ExtVector: {
14566 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14567 assert(VX->getNumElements() == VY->getNumElements());
14568 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14569 VX->getNumElements());
14570 }
14571 case Type::DependentSizedExtVector: {
14572 const auto *VX = cast<DependentSizedExtVectorType>(X),
14575 getCommonSizeExpr(Ctx, VX, VY),
14576 getCommonAttrLoc(VX, VY));
14577 }
14578 case Type::DependentVector: {
14579 const auto *VX = cast<DependentVectorType>(X),
14581 assert(VX->getVectorKind() == VY->getVectorKind());
14582 return Ctx.getDependentVectorType(
14583 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14584 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14585 }
14586 case Type::Enum:
14587 case Type::Record:
14588 case Type::InjectedClassName: {
14589 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14590 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14591 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14592 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14593 /*OwnedTag=*/false);
14594 }
14595 case Type::TemplateSpecialization: {
14596 const auto *TX = cast<TemplateSpecializationType>(X),
14598 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14599 TY->template_arguments());
14601 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14602 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14603 TY->getTemplateName(),
14604 /*IgnoreDeduced=*/true),
14605 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14606 }
14607 case Type::Decltype: {
14608 const auto *DX = cast<DecltypeType>(X);
14609 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14610 assert(DX->isDependentType());
14611 assert(DY->isDependentType());
14612 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14613 // As Decltype is not uniqued, building a common type would be wasteful.
14614 return QualType(DX, 0);
14615 }
14616 case Type::PackIndexing: {
14617 const auto *DX = cast<PackIndexingType>(X);
14618 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14619 assert(DX->isDependentType());
14620 assert(DY->isDependentType());
14621 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14622 return QualType(DX, 0);
14623 }
14624 case Type::DependentName: {
14625 const auto *NX = cast<DependentNameType>(X),
14626 *NY = cast<DependentNameType>(Y);
14627 assert(NX->getIdentifier() == NY->getIdentifier());
14628 return Ctx.getDependentNameType(
14629 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14630 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14631 }
14632 case Type::OverflowBehavior: {
14633 const auto *NX = cast<OverflowBehaviorType>(X),
14635 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14636 return Ctx.getOverflowBehaviorType(
14637 NX->getBehaviorKind(),
14638 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14639 NY->getUnderlyingType(), QX, QY));
14640 }
14641 case Type::UnaryTransform: {
14642 const auto *TX = cast<UnaryTransformType>(X),
14643 *TY = cast<UnaryTransformType>(Y);
14644 assert(TX->getUTTKind() == TY->getUTTKind());
14645 return Ctx.getUnaryTransformType(
14646 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14647 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14648 TY->getUnderlyingType()),
14649 TX->getUTTKind());
14650 }
14651 case Type::PackExpansion: {
14652 const auto *PX = cast<PackExpansionType>(X),
14653 *PY = cast<PackExpansionType>(Y);
14654 assert(PX->getNumExpansions() == PY->getNumExpansions());
14655 return Ctx.getPackExpansionType(
14656 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14657 PX->getNumExpansions(), false);
14658 }
14659 case Type::Pipe: {
14660 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14661 assert(PX->isReadOnly() == PY->isReadOnly());
14662 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14664 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14665 }
14666 case Type::TemplateTypeParm: {
14667 const auto *TX = cast<TemplateTypeParmType>(X),
14669 assert(TX->getDepth() == TY->getDepth());
14670 assert(TX->getIndex() == TY->getIndex());
14671 assert(TX->isParameterPack() == TY->isParameterPack());
14672 return Ctx.getTemplateTypeParmType(
14673 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14674 getCommonDecl(TX->getDecl(), TY->getDecl()));
14675 }
14676 }
14677 llvm_unreachable("Unknown Type Class");
14678}
14679
14681 const Type *Y,
14682 SplitQualType Underlying) {
14683 Type::TypeClass TC = X->getTypeClass();
14684 if (TC != Y->getTypeClass())
14685 return QualType();
14686 switch (TC) {
14687#define UNEXPECTED_TYPE(Class, Kind) \
14688 case Type::Class: \
14689 llvm_unreachable("Unexpected " Kind ": " #Class);
14690#define TYPE(Class, Base)
14691#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14692#include "clang/AST/TypeNodes.inc"
14693
14694#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14697 CANONICAL_TYPE(BlockPointer)
14700 CANONICAL_TYPE(ConstantArray)
14701 CANONICAL_TYPE(ArrayParameter)
14702 CANONICAL_TYPE(ConstantMatrix)
14704 CANONICAL_TYPE(ExtVector)
14705 CANONICAL_TYPE(FunctionNoProto)
14706 CANONICAL_TYPE(FunctionProto)
14707 CANONICAL_TYPE(IncompleteArray)
14708 CANONICAL_TYPE(HLSLAttributedResource)
14709 CANONICAL_TYPE(HLSLInlineSpirv)
14710 CANONICAL_TYPE(LValueReference)
14711 CANONICAL_TYPE(ObjCInterface)
14712 CANONICAL_TYPE(ObjCObject)
14713 CANONICAL_TYPE(ObjCObjectPointer)
14714 CANONICAL_TYPE(OverflowBehavior)
14718 CANONICAL_TYPE(RValueReference)
14719 CANONICAL_TYPE(VariableArray)
14721#undef CANONICAL_TYPE
14722
14723#undef UNEXPECTED_TYPE
14724
14725 case Type::Adjusted: {
14726 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14727 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14728 if (!Ctx.hasSameType(OX, OY))
14729 return QualType();
14730 // FIXME: It's inefficient to have to unify the original types.
14731 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14732 Ctx.getQualifiedType(Underlying));
14733 }
14734 case Type::Decayed: {
14735 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14736 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14737 if (!Ctx.hasSameType(OX, OY))
14738 return QualType();
14739 // FIXME: It's inefficient to have to unify the original types.
14740 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14741 Ctx.getQualifiedType(Underlying));
14742 }
14743 case Type::Attributed: {
14744 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14745 AttributedType::Kind Kind = AX->getAttrKind();
14746 if (Kind != AY->getAttrKind())
14747 return QualType();
14748 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14749 if (!Ctx.hasSameType(MX, MY))
14750 return QualType();
14751 // FIXME: It's inefficient to have to unify the modified types.
14752 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14753 Ctx.getQualifiedType(Underlying),
14754 AX->getAttr());
14755 }
14756 case Type::BTFTagAttributed: {
14757 const auto *BX = cast<BTFTagAttributedType>(X);
14758 const BTFTypeTagAttr *AX = BX->getAttr();
14759 // The attribute is not uniqued, so just compare the tag.
14760 if (AX->getBTFTypeTag() !=
14761 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14762 return QualType();
14763 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14764 }
14765 case Type::Auto: {
14766 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14767 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14768 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14769
14770 AutoTypeKeyword KW = AX->getKeyword();
14771 if (KW != AY->getKeyword())
14772 return QualType();
14773
14774 TemplateDecl *CD =
14775 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14776 AY->getTypeConstraintConcept().getAsTemplateDecl());
14778 if (CD &&
14779 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14780 AY->getTypeConstraintArguments())) {
14781 CD = nullptr; // The arguments differ, so make it unconstrained.
14782 As.clear();
14783 }
14784
14785 // Both auto types can't be dependent, otherwise they wouldn't have been
14786 // sugar. This implies they can't contain unexpanded packs either.
14788 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14789 TemplateName(CD), As);
14790 }
14791 case Type::PackIndexing:
14792 case Type::Decltype:
14793 return QualType();
14794 case Type::DeducedTemplateSpecialization:
14795 // FIXME: Try to merge these.
14796 return QualType();
14797 case Type::MacroQualified: {
14798 const auto *MX = cast<MacroQualifiedType>(X),
14799 *MY = cast<MacroQualifiedType>(Y);
14800 const IdentifierInfo *IX = MX->getMacroIdentifier();
14801 if (IX != MY->getMacroIdentifier())
14802 return QualType();
14803 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14804 }
14805 case Type::SubstTemplateTypeParm: {
14806 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14808 Decl *CD =
14809 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14810 if (!CD)
14811 return QualType();
14812 unsigned Index = SX->getIndex();
14813 if (Index != SY->getIndex())
14814 return QualType();
14815 auto PackIndex = SX->getPackIndex();
14816 if (PackIndex != SY->getPackIndex())
14817 return QualType();
14818 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14819 CD, Index, PackIndex,
14820 SX->getFinal() && SY->getFinal());
14821 }
14822 case Type::ObjCTypeParam:
14823 // FIXME: Try to merge these.
14824 return QualType();
14825 case Type::Paren:
14826 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14827
14828 case Type::TemplateSpecialization: {
14829 const auto *TX = cast<TemplateSpecializationType>(X),
14831 TemplateName CTN =
14832 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14833 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14834 if (!CTN.getAsVoidPointer())
14835 return QualType();
14837 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14838 TY->template_arguments()))
14839 return QualType();
14841 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14842 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14843 }
14844 case Type::Typedef: {
14845 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14846 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14847 if (!CD)
14848 return QualType();
14849 return Ctx.getTypedefType(
14850 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14851 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14852 Ctx.getQualifiedType(Underlying));
14853 }
14854 case Type::TypeOf: {
14855 // The common sugar between two typeof expressions, where one is
14856 // potentially a typeof_unqual and the other is not, we unify to the
14857 // qualified type as that retains the most information along with the type.
14858 // We only return a typeof_unqual type when both types are unqual types.
14863 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14864 }
14865 case Type::TypeOfExpr:
14866 return QualType();
14867
14868 case Type::UnaryTransform: {
14869 const auto *UX = cast<UnaryTransformType>(X),
14870 *UY = cast<UnaryTransformType>(Y);
14871 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14872 if (KX != UY->getUTTKind())
14873 return QualType();
14874 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14875 if (!Ctx.hasSameType(BX, BY))
14876 return QualType();
14877 // FIXME: It's inefficient to have to unify the base types.
14878 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14879 Ctx.getQualifiedType(Underlying), KX);
14880 }
14881 case Type::Using: {
14882 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14883 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14884 if (!CD)
14885 return QualType();
14886 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14887 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14888 CD, Ctx.getQualifiedType(Underlying));
14889 }
14890 case Type::MemberPointer: {
14891 const auto *PX = cast<MemberPointerType>(X),
14892 *PY = cast<MemberPointerType>(Y);
14893 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14894 assert(Cls == PY->getMostRecentCXXRecordDecl());
14895 return Ctx.getMemberPointerType(
14896 ::getCommonPointeeType(Ctx, PX, PY),
14897 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14898 }
14899 case Type::CountAttributed: {
14900 const auto *DX = cast<CountAttributedType>(X),
14902 if (DX->isCountInBytes() != DY->isCountInBytes())
14903 return QualType();
14904 if (DX->isOrNull() != DY->isOrNull())
14905 return QualType();
14906 Expr *CEX = DX->getCountExpr();
14907 Expr *CEY = DY->getCountExpr();
14908 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14909 if (Ctx.hasSameExpr(CEX, CEY))
14910 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14911 DX->isCountInBytes(), DX->isOrNull(),
14912 CDX);
14913 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14914 return QualType();
14915 // Two declarations with the same integer constant may still differ in their
14916 // expression pointers, so we need to evaluate them.
14917 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14918 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14919 if (VX != VY)
14920 return QualType();
14921 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14922 DX->isCountInBytes(), DX->isOrNull(),
14923 CDX);
14924 }
14925
14926 case Type::LateParsedAttr:
14927 return QualType();
14928
14929 case Type::PredefinedSugar:
14930 assert(cast<PredefinedSugarType>(X)->getKind() !=
14932 return QualType();
14933 }
14934 llvm_unreachable("Unhandled Type Class");
14935}
14936
14937static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
14939 while (true) {
14940 QTotal.addConsistentQualifiers(T.Quals);
14941 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
14942 if (NT == QualType(T.Ty, 0))
14943 break;
14944 R.push_back(T);
14945 T = NT.split();
14946 }
14947 return R;
14948}
14949
14951 bool Unqualified) const {
14952 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
14953 if (X == Y)
14954 return X;
14955 if (!Unqualified) {
14956 if (X.isCanonical())
14957 return X;
14958 if (Y.isCanonical())
14959 return Y;
14960 }
14961
14962 SplitQualType SX = X.split(), SY = Y.split();
14963 Qualifiers QX, QY;
14964 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
14965 // until we reach their underlying "canonical nodes". Note these are not
14966 // necessarily canonical types, as they may still have sugared properties.
14967 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
14968 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
14969
14970 // If this is an ArrayType, the element qualifiers are interchangeable with
14971 // the top level qualifiers.
14972 // * In case the canonical nodes are the same, the elements types are already
14973 // the same.
14974 // * Otherwise, the element types will be made the same, and any different
14975 // element qualifiers will be moved up to the top level qualifiers, per
14976 // 'getCommonArrayElementType'.
14977 // In both cases, this means there may be top level qualifiers which differ
14978 // between X and Y. If so, these differing qualifiers are redundant with the
14979 // element qualifiers, and can be removed without changing the canonical type.
14980 // The desired behaviour is the same as for the 'Unqualified' case here:
14981 // treat the redundant qualifiers as sugar, remove the ones which are not
14982 // common to both sides.
14983 bool KeepCommonQualifiers =
14985
14986 if (SX.Ty != SY.Ty) {
14987 // The canonical nodes differ. Build a common canonical node out of the two,
14988 // unifying their sugar. This may recurse back here.
14989 SX.Ty =
14990 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
14991 } else {
14992 // The canonical nodes were identical: We may have desugared too much.
14993 // Add any common sugar back in.
14994 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
14995 QX -= SX.Quals;
14996 QY -= SY.Quals;
14997 SX = Xs.pop_back_val();
14998 SY = Ys.pop_back_val();
14999 }
15000 }
15001 if (KeepCommonQualifiers)
15003 else
15004 assert(QX == QY);
15005
15006 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15007 // related. Walk up these nodes, unifying them and adding the result.
15008 while (!Xs.empty() && !Ys.empty()) {
15009 auto Underlying = SplitQualType(
15010 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15011 SX = Xs.pop_back_val();
15012 SY = Ys.pop_back_val();
15013 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15015 // Stop at the first pair which is unrelated.
15016 if (!SX.Ty) {
15017 SX.Ty = Underlying.Ty;
15018 break;
15019 }
15020 QX -= Underlying.Quals;
15021 };
15022
15023 // Add back the missing accumulated qualifiers, which were stripped off
15024 // with the sugar nodes we could not unify.
15025 QualType R = getQualifiedType(SX.Ty, QX);
15026 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15027 return R;
15028}
15029
15031 assert(Ty->isFixedPointType());
15032
15034 return Ty;
15035
15036 switch (Ty->castAs<BuiltinType>()->getKind()) {
15037 default:
15038 llvm_unreachable("Not a saturated fixed point type!");
15039 case BuiltinType::SatShortAccum:
15040 return ShortAccumTy;
15041 case BuiltinType::SatAccum:
15042 return AccumTy;
15043 case BuiltinType::SatLongAccum:
15044 return LongAccumTy;
15045 case BuiltinType::SatUShortAccum:
15046 return UnsignedShortAccumTy;
15047 case BuiltinType::SatUAccum:
15048 return UnsignedAccumTy;
15049 case BuiltinType::SatULongAccum:
15050 return UnsignedLongAccumTy;
15051 case BuiltinType::SatShortFract:
15052 return ShortFractTy;
15053 case BuiltinType::SatFract:
15054 return FractTy;
15055 case BuiltinType::SatLongFract:
15056 return LongFractTy;
15057 case BuiltinType::SatUShortFract:
15058 return UnsignedShortFractTy;
15059 case BuiltinType::SatUFract:
15060 return UnsignedFractTy;
15061 case BuiltinType::SatULongFract:
15062 return UnsignedLongFractTy;
15063 }
15064}
15065
15067 assert(Ty->isFixedPointType());
15068
15069 if (Ty->isSaturatedFixedPointType()) return Ty;
15070
15071 switch (Ty->castAs<BuiltinType>()->getKind()) {
15072 default:
15073 llvm_unreachable("Not a fixed point type!");
15074 case BuiltinType::ShortAccum:
15075 return SatShortAccumTy;
15076 case BuiltinType::Accum:
15077 return SatAccumTy;
15078 case BuiltinType::LongAccum:
15079 return SatLongAccumTy;
15080 case BuiltinType::UShortAccum:
15082 case BuiltinType::UAccum:
15083 return SatUnsignedAccumTy;
15084 case BuiltinType::ULongAccum:
15086 case BuiltinType::ShortFract:
15087 return SatShortFractTy;
15088 case BuiltinType::Fract:
15089 return SatFractTy;
15090 case BuiltinType::LongFract:
15091 return SatLongFractTy;
15092 case BuiltinType::UShortFract:
15094 case BuiltinType::UFract:
15095 return SatUnsignedFractTy;
15096 case BuiltinType::ULongFract:
15098 }
15099}
15100
15102 if (LangOpts.OpenCL)
15104
15105 if (LangOpts.CUDA)
15107
15108 return getLangASFromTargetAS(AS);
15109}
15110
15112 assert(Ty->isFixedPointType());
15113
15114 const TargetInfo &Target = getTargetInfo();
15115 switch (Ty->castAs<BuiltinType>()->getKind()) {
15116 default:
15117 llvm_unreachable("Not a fixed point type!");
15118 case BuiltinType::ShortAccum:
15119 case BuiltinType::SatShortAccum:
15120 return Target.getShortAccumScale();
15121 case BuiltinType::Accum:
15122 case BuiltinType::SatAccum:
15123 return Target.getAccumScale();
15124 case BuiltinType::LongAccum:
15125 case BuiltinType::SatLongAccum:
15126 return Target.getLongAccumScale();
15127 case BuiltinType::UShortAccum:
15128 case BuiltinType::SatUShortAccum:
15129 return Target.getUnsignedShortAccumScale();
15130 case BuiltinType::UAccum:
15131 case BuiltinType::SatUAccum:
15132 return Target.getUnsignedAccumScale();
15133 case BuiltinType::ULongAccum:
15134 case BuiltinType::SatULongAccum:
15135 return Target.getUnsignedLongAccumScale();
15136 case BuiltinType::ShortFract:
15137 case BuiltinType::SatShortFract:
15138 return Target.getShortFractScale();
15139 case BuiltinType::Fract:
15140 case BuiltinType::SatFract:
15141 return Target.getFractScale();
15142 case BuiltinType::LongFract:
15143 case BuiltinType::SatLongFract:
15144 return Target.getLongFractScale();
15145 case BuiltinType::UShortFract:
15146 case BuiltinType::SatUShortFract:
15147 return Target.getUnsignedShortFractScale();
15148 case BuiltinType::UFract:
15149 case BuiltinType::SatUFract:
15150 return Target.getUnsignedFractScale();
15151 case BuiltinType::ULongFract:
15152 case BuiltinType::SatULongFract:
15153 return Target.getUnsignedLongFractScale();
15154 }
15155}
15156
15158 assert(Ty->isFixedPointType());
15159
15160 const TargetInfo &Target = getTargetInfo();
15161 switch (Ty->castAs<BuiltinType>()->getKind()) {
15162 default:
15163 llvm_unreachable("Not a fixed point type!");
15164 case BuiltinType::ShortAccum:
15165 case BuiltinType::SatShortAccum:
15166 return Target.getShortAccumIBits();
15167 case BuiltinType::Accum:
15168 case BuiltinType::SatAccum:
15169 return Target.getAccumIBits();
15170 case BuiltinType::LongAccum:
15171 case BuiltinType::SatLongAccum:
15172 return Target.getLongAccumIBits();
15173 case BuiltinType::UShortAccum:
15174 case BuiltinType::SatUShortAccum:
15175 return Target.getUnsignedShortAccumIBits();
15176 case BuiltinType::UAccum:
15177 case BuiltinType::SatUAccum:
15178 return Target.getUnsignedAccumIBits();
15179 case BuiltinType::ULongAccum:
15180 case BuiltinType::SatULongAccum:
15181 return Target.getUnsignedLongAccumIBits();
15182 case BuiltinType::ShortFract:
15183 case BuiltinType::SatShortFract:
15184 case BuiltinType::Fract:
15185 case BuiltinType::SatFract:
15186 case BuiltinType::LongFract:
15187 case BuiltinType::SatLongFract:
15188 case BuiltinType::UShortFract:
15189 case BuiltinType::SatUShortFract:
15190 case BuiltinType::UFract:
15191 case BuiltinType::SatUFract:
15192 case BuiltinType::ULongFract:
15193 case BuiltinType::SatULongFract:
15194 return 0;
15195 }
15196}
15197
15198llvm::FixedPointSemantics
15200 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15201 "Can only get the fixed point semantics for a "
15202 "fixed point or integer type.");
15203 if (Ty->isIntegerType())
15204 return llvm::FixedPointSemantics::GetIntegerSemantics(
15205 getIntWidth(Ty), Ty->isSignedIntegerType());
15206
15207 bool isSigned = Ty->isSignedFixedPointType();
15208 return llvm::FixedPointSemantics(
15209 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15211 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15212}
15213
15214llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15215 assert(Ty->isFixedPointType());
15216 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15217}
15218
15219llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15220 assert(Ty->isFixedPointType());
15221 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15222}
15223
15225 assert(Ty->isUnsignedFixedPointType() &&
15226 "Expected unsigned fixed point type");
15227
15228 switch (Ty->castAs<BuiltinType>()->getKind()) {
15229 case BuiltinType::UShortAccum:
15230 return ShortAccumTy;
15231 case BuiltinType::UAccum:
15232 return AccumTy;
15233 case BuiltinType::ULongAccum:
15234 return LongAccumTy;
15235 case BuiltinType::SatUShortAccum:
15236 return SatShortAccumTy;
15237 case BuiltinType::SatUAccum:
15238 return SatAccumTy;
15239 case BuiltinType::SatULongAccum:
15240 return SatLongAccumTy;
15241 case BuiltinType::UShortFract:
15242 return ShortFractTy;
15243 case BuiltinType::UFract:
15244 return FractTy;
15245 case BuiltinType::ULongFract:
15246 return LongFractTy;
15247 case BuiltinType::SatUShortFract:
15248 return SatShortFractTy;
15249 case BuiltinType::SatUFract:
15250 return SatFractTy;
15251 case BuiltinType::SatULongFract:
15252 return SatLongFractTy;
15253 default:
15254 llvm_unreachable("Unexpected unsigned fixed point type");
15255 }
15256}
15257
15258// Given a list of FMV features, return a concatenated list of the
15259// corresponding backend features (which may contain duplicates).
15260static std::vector<std::string> getFMVBackendFeaturesFor(
15261 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15262 std::vector<std::string> BackendFeats;
15263 llvm::AArch64::ExtensionSet FeatureBits;
15264 for (StringRef F : FMVFeatStrings)
15265 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15266 if (FMVExt->ID)
15267 FeatureBits.enable(*FMVExt->ID);
15268 FeatureBits.toLLVMFeatureList(BackendFeats);
15269 return BackendFeats;
15270}
15271
15272ParsedTargetAttr
15273ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15274 assert(TD != nullptr);
15275 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15276
15277 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15278 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15279 });
15280 return ParsedAttr;
15281}
15282
15283void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15284 const FunctionDecl *FD) const {
15285 if (FD)
15286 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15287 else
15288 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15289 Target->getTargetOpts().CPU,
15290 Target->getTargetOpts().Features);
15291}
15292
15293// Fills in the supplied string map with the set of target features for the
15294// passed in function.
15295void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15296 GlobalDecl GD) const {
15297 StringRef TargetCPU = Target->getTargetOpts().CPU;
15298 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15299 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15301
15302 // Make a copy of the features as passed on the command line into the
15303 // beginning of the additional features from the function to override.
15304 // AArch64 handles command line option features in parseTargetAttr().
15305 if (!Target->getTriple().isAArch64())
15306 ParsedAttr.Features.insert(
15307 ParsedAttr.Features.begin(),
15308 Target->getTargetOpts().FeaturesAsWritten.begin(),
15309 Target->getTargetOpts().FeaturesAsWritten.end());
15310
15311 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15312 TargetCPU = ParsedAttr.CPU;
15313
15314 // Now populate the feature map, first with the TargetCPU which is either
15315 // the default or a new one from the target attribute string. Then we'll use
15316 // the passed in features (FeaturesAsWritten) along with the new ones from
15317 // the attribute.
15318 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15319 ParsedAttr.Features);
15320 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15322 Target->getCPUSpecificCPUDispatchFeatures(
15323 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15324 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15325 Features.insert(Features.begin(),
15326 Target->getTargetOpts().FeaturesAsWritten.begin(),
15327 Target->getTargetOpts().FeaturesAsWritten.end());
15328 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15329 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15330 if (Target->getTriple().isAArch64()) {
15332 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15333 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15334 Features.insert(Features.begin(),
15335 Target->getTargetOpts().FeaturesAsWritten.begin(),
15336 Target->getTargetOpts().FeaturesAsWritten.end());
15337 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15338 } else if (Target->getTriple().isRISCV()) {
15339 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15340 std::vector<std::string> Features;
15341 if (VersionStr != "default") {
15342 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15343 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15344 ParsedAttr.Features.end());
15345 }
15346 Features.insert(Features.begin(),
15347 Target->getTargetOpts().FeaturesAsWritten.begin(),
15348 Target->getTargetOpts().FeaturesAsWritten.end());
15349 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15350 } else if (Target->getTriple().isOSAIX()) {
15351 std::vector<std::string> Features;
15352 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15353 if (VersionStr.starts_with("cpu="))
15354 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15355 else
15356 assert(VersionStr == "default");
15357 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15358 } else {
15359 std::vector<std::string> Features;
15360 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15361 if (VersionStr.starts_with("arch="))
15362 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15363 else if (VersionStr != "default")
15364 Features.push_back((StringRef{"+"} + VersionStr).str());
15365 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15366 }
15367 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15368 std::vector<std::string> Features;
15369 if (Target->getTriple().isRISCV()) {
15370 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15371 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15372 ParsedAttr.Features.end());
15373 } else {
15374 assert(Target->getTriple().isAArch64());
15376 TV->getFeatures(Feats);
15377 Features = getFMVBackendFeaturesFor(Feats);
15378 }
15379 Features.insert(Features.begin(),
15380 Target->getTargetOpts().FeaturesAsWritten.begin(),
15381 Target->getTargetOpts().FeaturesAsWritten.end());
15382 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15383 } else {
15384 FeatureMap = Target->getTargetOpts().FeatureMap;
15385 }
15386}
15387
15389 CanQualType KernelNameType,
15390 const FunctionDecl *FD) {
15391 // Host and device compilation may use different ABIs and different ABIs
15392 // may allocate name mangling discriminators differently. A discriminator
15393 // override is used to ensure consistent discriminator allocation across
15394 // host and device compilation.
15395 auto DeviceDiscriminatorOverrider =
15396 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15397 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15398 if (RD->isLambda())
15399 return RD->getDeviceLambdaManglingNumber();
15400 return std::nullopt;
15401 };
15402 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15403 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15404
15405 // Construct a mangled name for the SYCL kernel caller offload entry point.
15406 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15407 // name the SYCL kernel caller offload entry point function. This mangling
15408 // does not suffice to clearly identify symbols that correspond to SYCL
15409 // kernel caller functions, nor is this mangling natural for targets that
15410 // use a non-Itanium ABI.
15411 std::string Buffer;
15412 Buffer.reserve(128);
15413 llvm::raw_string_ostream Out(Buffer);
15414 MC->mangleCanonicalTypeName(KernelNameType, Out);
15415 std::string KernelName = Out.str();
15416
15417 return {KernelNameType, FD, KernelName};
15418}
15419
15421 // If the function declaration to register is invalid or dependent, the
15422 // registration attempt is ignored.
15423 if (FD->isInvalidDecl() || FD->isTemplated())
15424 return;
15425
15426 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15427 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15428
15429 // Be tolerant of multiple registration attempts so long as each attempt
15430 // is for the same entity. Callers are obligated to detect and diagnose
15431 // conflicting kernel names prior to calling this function.
15432 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15433 auto IT = SYCLKernels.find(KernelNameType);
15434 assert((IT == SYCLKernels.end() ||
15435 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15436 "SYCL kernel name conflict");
15437 (void)IT;
15438 SYCLKernels.insert(std::make_pair(
15439 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15440}
15441
15443 CanQualType KernelNameType = getCanonicalType(T);
15444 return SYCLKernels.at(KernelNameType);
15445}
15446
15448 CanQualType KernelNameType = getCanonicalType(T);
15449 auto IT = SYCLKernels.find(KernelNameType);
15450 if (IT != SYCLKernels.end())
15451 return &IT->second;
15452 return nullptr;
15453}
15454
15456 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15457 return *OMPTraitInfoVector.back();
15458}
15459
15462 const ASTContext::SectionInfo &Section) {
15463 if (Section.Decl)
15464 return DB << Section.Decl;
15465 return DB << "a prior #pragma section";
15466}
15467
15468bool ASTContext::mayExternalize(const Decl *D) const {
15469 bool IsInternalVar =
15470 isa<VarDecl>(D) &&
15472 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15473 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15474 (D->hasAttr<CUDAConstantAttr>() &&
15475 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15476 // CUDA/HIP: managed variables need to be externalized since it is
15477 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15478 // anonymous name space needs to be externalized to avoid duplicate symbols.
15479 return (IsInternalVar &&
15480 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15481 (D->hasAttr<CUDAGlobalAttr>() &&
15483 GVA_Internal);
15484}
15485
15487 return mayExternalize(D) &&
15488 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15490}
15491
15492StringRef ASTContext::getCUIDHash() const {
15493 if (!CUIDHash.empty())
15494 return CUIDHash;
15495 if (LangOpts.CUID.empty())
15496 return StringRef();
15497 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15498 return CUIDHash;
15499}
15500
15501const CXXRecordDecl *
15503 assert(ThisClass);
15504 assert(ThisClass->isPolymorphic());
15505 const CXXRecordDecl *PrimaryBase = ThisClass;
15506 while (1) {
15507 assert(PrimaryBase);
15508 assert(PrimaryBase->isPolymorphic());
15509 auto &Layout = getASTRecordLayout(PrimaryBase);
15510 auto Base = Layout.getPrimaryBase();
15511 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15512 break;
15513 PrimaryBase = Base;
15514 }
15515 return PrimaryBase;
15516}
15517
15519 StringRef MangledName) {
15520 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15521 assert(Method->isVirtual());
15522 bool DefaultIncludesPointerAuth =
15523 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15524
15525 if (!DefaultIncludesPointerAuth)
15526 return true;
15527
15528 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15529 if (Existing != ThunksToBeAbbreviated.end())
15530 return Existing->second.contains(MangledName.str());
15531
15532 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15533 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15534 auto VtableContext = getVTableContext();
15535 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15536 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15537 for (const auto &Thunk : *ThunkInfos) {
15538 SmallString<256> ElidedName;
15539 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15540 if (Destructor)
15541 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15542 Thunk, /* elideOverrideInfo */ true,
15543 ElidedNameStream);
15544 else
15545 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15546 ElidedNameStream);
15547 SmallString<256> MangledName;
15548 llvm::raw_svector_ostream mangledNameStream(MangledName);
15549 if (Destructor)
15550 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15551 Thunk, /* elideOverrideInfo */ false,
15552 mangledNameStream);
15553 else
15554 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15555 mangledNameStream);
15556
15557 Thunks[ElidedName].push_back(std::string(MangledName));
15558 }
15559 }
15560 llvm::StringSet<> SimplifiedThunkNames;
15561 for (auto &ThunkList : Thunks) {
15562 llvm::sort(ThunkList.second);
15563 SimplifiedThunkNames.insert(ThunkList.second[0]);
15564 }
15565 bool Result = SimplifiedThunkNames.contains(MangledName);
15566 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15567 return Result;
15568}
15569
15571 // Check for trivially-destructible here because non-trivially-destructible
15572 // types will always cause the type and any types derived from it to be
15573 // considered non-trivially-copyable. The same cannot be said for
15574 // trivially-copyable because deleting special members of a type derived from
15575 // a non-trivially-copyable type can cause the derived type to be considered
15576 // trivially copyable.
15577 if (getLangOpts().PointerFieldProtectionTagged)
15578 return !isa<CXXRecordDecl>(RD) ||
15579 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15580 return true;
15581}
15582
15583static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15584 std::vector<PFPField> &Fields, bool IncludeVBases) {
15585 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15586 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15587 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15588 for (unsigned i = 0; i != AT->getSize(); ++i)
15589 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15590 Fields, true);
15591 }
15592 }
15593 auto *Decl = Ty->getAsCXXRecordDecl();
15594 // isPFPType() is inherited from bases and members (including via arrays), so
15595 // we can early exit if it is false. Unions are excluded per the API
15596 // documentation.
15597 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15598 return;
15599 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15600 for (FieldDecl *Field : Decl->fields()) {
15601 CharUnits FieldOffset =
15602 Offset +
15603 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15604 if (Ctx.isPFPField(Field))
15605 Fields.push_back({FieldOffset, Field});
15606 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15607 /*IncludeVBases=*/true);
15608 }
15609 // Pass false for IncludeVBases below because vbases are only included in
15610 // layout for top-level types, i.e. not bases or vbases.
15611 for (CXXBaseSpecifier &Base : Decl->bases()) {
15612 if (Base.isVirtual())
15613 continue;
15614 CharUnits BaseOffset =
15615 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15616 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15617 /*IncludeVBases=*/false);
15618 }
15619 if (IncludeVBases) {
15620 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15621 CharUnits BaseOffset =
15622 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15623 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15624 /*IncludeVBases=*/false);
15625 }
15626 }
15627}
15628
15629std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15630 std::vector<PFPField> PFPFields;
15631 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15632 return PFPFields;
15633}
15634
15636 return !findPFPFields(Ty).empty();
15637}
15638
15639bool ASTContext::isPFPField(const FieldDecl *FD) const {
15640 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15641 return RD->isPFPType() && FD->getType()->isPointerType() &&
15642 !FD->hasAttr<NoFieldProtectionAttr>();
15643 return false;
15644}
15645
15647 auto *FD = dyn_cast<FieldDecl>(VD);
15648 if (!FD)
15649 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15650 if (isPFPField(FD))
15652}
15653
15655 if (E->getNumComponents() == 0)
15656 return;
15657 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15658 if (Comp.getKind() != OffsetOfNode::Field)
15659 return;
15660 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15662}
15663
15664namespace {
15665// PaddingCalculator is a utility class that calculates the padding bits in a
15666// c/c++ type. It traverses the type recursively, collecting occupied
15667// bit intervals, and then computes the padding intervals.
15668// If a byte only contains some padding bits, it gets intervals for only those
15669// bits. This is the case for bit-fields.
15670struct PaddingCalculator {
15671 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15672
15673 void run(QualType Ty) {
15674 OccuppiedIntervals.clear();
15675 Stack.clear();
15676
15677 TySizeInBits = Ctx.getTypeSize(Ty);
15678
15679 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15680 while (!Stack.empty()) {
15681 Data Current = Stack.back();
15682 Stack.pop_back();
15683 Visit(Current);
15684 }
15685 MergeOccuppiedIntervals();
15686 }
15687
15688 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15689 llvm::SmallVector<ASTContext::BitInterval> Results;
15690 if (OccuppiedIntervals.size() == 1 &&
15691 OccuppiedIntervals.front().First == 0 &&
15692 OccuppiedIntervals.front().Last == TySizeInBits) {
15693 return Results;
15694 }
15695 Results.reserve(OccuppiedIntervals.size() + 1);
15696 uint64_t CurrentPos = 0;
15697 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15698 if (OccupiedInterval.First > CurrentPos) {
15699 Results.push_back(
15700 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15701 }
15702 CurrentPos = OccupiedInterval.Last;
15703 }
15704 if (TySizeInBits > CurrentPos) {
15705 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15706 }
15707 return Results;
15708 }
15709
15710private:
15711 struct Data {
15712 uint64_t StartBitOffset;
15713 QualType Ty;
15714 bool VisitVirtualBase;
15715 };
15716
15717 // Return the number of non padding bits of a scalar type.
15718 //
15719 // The property that we specifically care about here is whether the scalar
15720 // type has padding bits, i.e. are there bits in the type which are not
15721 // specified by the ABI.
15722 //
15723 // We currently don't care about this anywhere else in clang: layout cares
15724 // about the ABI size, calling convention code cares about specific types,
15725 // but nothing cares about padding specifically. And it's not something we can
15726 // easily query from LLVM due to the type system mismatches.
15727 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15728 // DataLayout methods aren't really designed for this usage.
15729 //
15730 // Therefore, it is better to explicitly list all the scalar types
15731 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15732 // double.
15733 //
15734 // FIXME: There are likely other scalar types we need to think about here, as
15735 // brought up in review for #215823:
15736 // - bool
15737 // - enums(both with/without fixed underlying type)
15738 // - nullptr_t
15739 // - more?
15740 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15741 if (const auto *BIT = Ty->getAs<BitIntType>())
15742 return BIT->getNumBits();
15743
15744 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15745 if (BT->getKind() == BuiltinType::LongDouble &&
15747 &llvm::APFloat::x87DoubleExtended())
15748 return llvm::APFloat::getSizeInBits(
15750 }
15751
15752 return Ctx.getTypeSize(Ty);
15753 }
15754
15755 void Visit(const Data &D) {
15756 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15757 VisitArray(AT, D.StartBitOffset);
15758 return;
15759 }
15760
15761 if (auto *Record = D.Ty->getAsRecordDecl()) {
15762 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15763 return;
15764 }
15765
15766 if (D.Ty->isAtomicType()) {
15767 auto Unwrapped = D;
15768 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15769 Stack.push_back(Unwrapped);
15770 return;
15771 }
15772
15773 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15774 VisitComplex(Complex, D.StartBitOffset);
15775 return;
15776 }
15777
15778 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15779 VisitVector(VT, D.StartBitOffset);
15780 return;
15781 }
15782
15783 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15784 VisitBitInt(BITy, D.StartBitOffset);
15785 return;
15786 }
15787
15788 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15789 OccuppiedIntervals.push_back(
15790 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15791 }
15792
15793 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15794 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15795 ++ArrIndex) {
15796
15797 QualType ElementQualType = AT->getElementType();
15798 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15799 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15800 auto Offset = ElementSize.alignTo(ElementAlign);
15801
15802 Stack.push_back(Data{
15803 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15804 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15805 }
15806 }
15807
15808 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15809 bool VisitVirtualBase) {
15810 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15811 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15812
15813 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15814
15815 if (CXXRecord) {
15816 if (ASTLayout.hasOwnVFPtr()) {
15817 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15818 StartBitOffset, StartBitOffset + PointerSizeInBits});
15819 }
15820
15821 if (ASTLayout.hasOwnVBPtr()) {
15822 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15823 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15824 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15825 StartVBPtr, StartVBPtr + PointerSizeInBits});
15826 }
15827
15828 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15829 const CXXBaseSpecifier &Base, auto GetOffset) {
15830 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15831 if (!BaseRecord) {
15832 return;
15833 }
15834 auto BaseOffset =
15835 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15836
15837 Stack.push_back(
15838 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15839 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15840 false});
15841 };
15842
15843 for (auto Base : CXXRecord->bases()) {
15844 if (!Base.isVirtual()) {
15845 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15846 }
15847 }
15848
15849 if (VisitVirtualBase) {
15850 for (auto VBase : CXXRecord->vbases()) {
15851 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15852 }
15853 }
15854 }
15855
15856 for (auto *Field : R->fields()) {
15857 // Treat unnamed bitfields as padding.
15858 if (Field->isUnnamedBitField())
15859 continue;
15860
15861 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
15862 if (Field->isBitField()) {
15863 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15864 StartBitOffset + FieldOffset,
15865 StartBitOffset + FieldOffset + Field->getBitWidthValue()});
15866 } else {
15867 Stack.push_back(Data{StartBitOffset + FieldOffset,
15868 Field->getType().getCanonicalType(),
15869 /*VisitVirtualBase*/ true});
15870 }
15871 }
15872 }
15873
15874 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
15875 QualType ElementQualType = CT->getElementType().getCanonicalType();
15876 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15877 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15878 auto ImgOffset = ElementSize.alignTo(ElementAlign);
15879
15880 Stack.push_back(
15881 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
15882 Stack.push_back(
15883 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
15884 ElementQualType, /*VisitVirtualBase*/ true});
15885 }
15886
15887 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
15888 uint64_t SizeBit = [&]() -> uint64_t {
15889 if (VT->isPackedVectorBoolType(Ctx))
15890 return VT->getNumElements();
15891 return getScalarOccupiedSizeInBits(VT->getElementType()) *
15892 VT->getNumElements();
15893 }();
15894 OccuppiedIntervals.push_back(
15895 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
15896 }
15897
15898 /// Compute the occupied bit intervals for a BitInt.
15899 ///
15900 /// In the case of little endian, the occupied bits are always contiguous so a
15901 /// single interval is sufficient. However in big endian, the intervals can be
15902 /// disjoint.
15903 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
15904 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
15905
15906 if (Ctx.getTargetInfo().isLittleEndian()) {
15907 OccuppiedIntervals.push_back(
15908 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
15909 return;
15910 }
15911
15912 // In big endian mode, the layout of a BitInt in memory has its bytes in
15913 // reverse order, and is pictured in this order:
15914 // 1. Fully padding bytes.
15915 // 2. One partially occupied byte, with padding at the most significant
15916 // bits. ("remaining occupied bits")
15917 // 3. A sequence of fully occupied bytes up until the end of the storage.
15918 const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
15919 const uint64_t CharWidth = Ctx.getCharWidth();
15920 const uint64_t NumFullyPaddingBytes =
15921 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
15922 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
15923 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
15924
15925 // Partially occupied byte
15926 if (NumRemainingOccupiedBits > 0)
15927 OccuppiedIntervals.push_back(
15928 {StartBitOffset + NumFullyPaddingBytes * CharWidth,
15929 StartBitOffset + NumFullyPaddingBytes * CharWidth +
15930 NumRemainingOccupiedBits});
15931
15932 // Fully occupied bytes
15933 if (NumFullyOccupiedBytes > 0)
15934 OccuppiedIntervals.push_back({StartBitOffset + StorageSizeInBits -
15935 NumFullyOccupiedBytes * CharWidth,
15936 StartBitOffset + StorageSizeInBits});
15937 }
15938
15939 void MergeOccuppiedIntervals() {
15940 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
15941 [](const ASTContext::BitInterval &lhs,
15942 const ASTContext::BitInterval &rhs) {
15943 return std::tie(lhs.First, lhs.Last) <
15944 std::tie(rhs.First, rhs.Last);
15945 });
15946
15947 llvm::SmallVector<ASTContext::BitInterval> Merged;
15948 Merged.reserve(OccuppiedIntervals.size());
15949
15950 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
15951 if (Merged.empty()) {
15952 Merged.push_back(NextInterval);
15953 continue;
15954 }
15955 auto &LastInterval = Merged.back();
15956
15957 if (NextInterval.First > LastInterval.Last) {
15958 Merged.push_back(NextInterval);
15959 } else {
15960 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
15961 }
15962 }
15963
15964 OccuppiedIntervals = Merged;
15965 }
15966
15967 const ASTContext &Ctx;
15968 // unsigned PointerSizeInBits;
15969 uint64_t TySizeInBits = 0;
15970 llvm::SmallVector<Data> Stack;
15971 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
15972};
15973} // namespace
15974
15975llvm::ArrayRef<ASTContext::BitInterval>
15977 Ty = Ty.getCanonicalType();
15978 auto cached = PaddingIntervalCache.find(Ty);
15979 if (cached != PaddingIntervalCache.end())
15980 return cached->second;
15981
15982 PaddingCalculator pc{*this};
15983 pc.run(Ty);
15984
15985 auto [itr, res] =
15986 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
15987 assert(res && "Failed to insert?");
15988
15989 return itr->second;
15990}
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)
#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 std::string charUnitsToString(const CharUnits &CU)
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 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:498
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:2852
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:95
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:122
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1108
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1101
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1115
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
MemberSpecializationInfo * getInstantiatedFromStaticDataMember(const VarDecl *Var)
If this variable is an instantiated static data member of a class template specialization,...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
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...
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.
bool isPFPField(const FieldDecl *Field) const
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:850
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:851
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...
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:846
Builtin::Context & BuiltinInfo
Definition ASTContext.h:848
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:847
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.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
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:966
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:609
CanQualType UnsignedLongTy
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:849
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
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:240
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:852
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:899
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:601
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:920
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...
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
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:965
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
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
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.
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)
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
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.
AttrVec & getDeclAttrs(const Decl *D)
Retrieve the attributes for the given declaration.
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:3585
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
llvm::APInt getArraySize() const
Definition Expr.h:6040
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3970
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3800
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3814
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3818
QualType getElementType() const
Definition TypeBase.h:3812
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3822
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:6978
Expr * getPtr() const
Definition Expr.h:7009
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8276
unsigned getNumBits() const
Definition TypeBase.h:8288
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4807
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Pointer to a block type.
Definition TypeBase.h:3633
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:3241
Kind getKind() const
Definition TypeBase.h:3292
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:236
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:2641
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2262
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:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1223
bool isDynamicClass() const
Definition DeclCXX.h:574
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1195
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
QualType getElementType() const
Definition TypeBase.h:3365
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3838
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3934
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3894
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3953
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3914
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4465
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4484
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4530
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4481
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3498
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3534
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3616
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isFileContext() const
Definition DeclBase.h:2197
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
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:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
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:871
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:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
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:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
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:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
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:781
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4139
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4161
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8315
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4089
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4118
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4179
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4204
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4551
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4571
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:6329
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6334
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4305
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4330
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4146
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4364
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4262
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:113
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:3128
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:224
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:3103
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:4104
QualType getType() const
Definition Expr.h:145
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
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:4345
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:248
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5612
Abstract interface for external sources of AST nodes.
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4816
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3380
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
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:4764
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:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3806
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3935
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3791
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4458
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2537
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:4119
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5353
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5886
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5924
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5185
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5219
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4963
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4979
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5889
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5692
unsigned getNumParams() const
Definition TypeBase.h:5663
QualType getParamType(unsigned i) const
Definition TypeBase.h:5665
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4118
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5698
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5789
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5674
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5670
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5858
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5854
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4692
CallingConv getCC() const
Definition TypeBase.h:4751
unsigned getRegParm() const
Definition TypeBase.h:4744
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4740
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4763
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4607
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4647
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4581
ExtInfo getExtInfo() const
Definition TypeBase.h:4937
QualType getReturnType() const
Definition TypeBase.h:4921
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:5188
Represents a C array with an unspecified size.
Definition TypeBase.h:3987
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4004
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3695
@ 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:3557
A global _GUID constant.
Definition DeclCXX.h:4432
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4469
MSGuidDeclParts Parts
Definition DeclCXX.h:4434
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6263
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:4436
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4429
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3731
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3774
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:423
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:318
bool isExternallyVisible() const
Definition Decl.h:434
Represent a C++ namespace.
Definition Decl.h:593
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:8003
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:988
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:8059
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8140
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:995
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8134
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8096
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8117
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8071
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8111
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1915
qual_range quals() const
Definition TypeBase.h:8178
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8123
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:2571
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2618
unsigned getNumComponents() const
Definition Expr.h:2626
Helper class for OffsetOfExpr.
Definition Expr.h:2465
@ Field
A field.
Definition Expr.h:2472
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:4416
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:3376
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:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
QualType getOriginalType() const
Definition Decl.cpp:2954
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:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
PredefinedSugarKind Kind
Definition TypeBase.h:8329
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:8502
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2998
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8549
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8507
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:8418
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8544
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8458
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8470
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8512
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8439
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8491
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:8475
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8422
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:3141
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8450
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:8358
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8365
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:3713
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:4460
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5310
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
field_range fields() const
Definition Decl.h:4663
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5296
RecordDecl * getMostRecentDecl()
Definition Decl.h:4486
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5355
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
bool field_empty() const
Definition Decl.h:4671
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:3658
QualType getPointeeType() const
Definition TypeBase.h:3680
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:1819
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:1194
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:3852
TagTypeKind TagKind
Definition Decl.h:3857
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4089
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4970
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4963
bool isUnion() const
Definition Decl.h:4063
TagKind getTagKind() const
Definition Decl.h:4052
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:226
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:852
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:745
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:339
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:348
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:353
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:362
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:341
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:344
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:357
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:511
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:413
bool isLittleEndian() const
IntType getSizeType() const
Definition TargetInfo.h:394
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:972
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:753
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:395
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:803
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:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateName getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3648
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:6295
A container of type source information.
Definition TypeBase.h:8389
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:8675
bool isVoidType() const
Definition TypeBase.h:9027
bool isObjCBuiltinType() const
Definition TypeBase.h:8885
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:455
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2803
bool isIncompleteArrayType() const
Definition TypeBase.h:8762
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isFloat16Type() const
Definition TypeBase.h:9036
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:8758
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:2549
bool isArrayType() const
Definition TypeBase.h:8754
bool isCharType() const
Definition Type.cpp:2223
bool isPointerType() const
Definition TypeBase.h:8655
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8770
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9071
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
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:9115
bool isEnumeralType() const
Definition TypeBase.h:8786
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8855
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9149
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2976
bool isBitIntType() const
Definition TypeBase.h:8930
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8778
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9087
bool isHalfType() const
Definition TypeBase.h:9031
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9103
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:3196
@ 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:8867
bool isOverflowBehaviorType() const
Definition TypeBase.h:8826
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9111
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9307
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:2559
bool isFunctionType() const
Definition TypeBase.h:8651
bool isObjCObjectPointerType() const
Definition TypeBase.h:8834
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:9129
bool isVectorType() const
Definition TypeBase.h:8794
bool isObjCClassType() const
Definition TypeBase.h:8873
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2785
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2720
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
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:2364
bool isAnyPointerType() const
Definition TypeBase.h:8663
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:9254
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9064
bool isRecordType() const
Definition TypeBase.h:8782
bool isObjCRetainableType() const
Definition Type.cpp:5440
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5159
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3802
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5830
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
QualType getUnderlyingType() const
Definition Decl.h:3752
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6239
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2324
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4489
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4517
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6100
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6137
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4066
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4131
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3821
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3428
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3492
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:6177
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5645
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2782
bool hasInit() const
Definition Decl.cpp:2380
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:2443
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
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:1215
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2357
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:2751
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4044
Expr * getSizeExpr() const
Definition TypeBase.h:4058
Represents a GCC generic vector type.
Definition TypeBase.h:4253
unsigned getNumElements() const
Definition TypeBase.h:4268
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4277
VectorKind getVectorKind() const
Definition TypeBase.h:4273
QualType getElementType() const
Definition TypeBase.h:4267
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:47
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:212
@ OCLTK_ReserveID
Definition TargetInfo.h:219
@ OCLTK_Sampler
Definition TargetInfo.h:220
@ OCLTK_Pipe
Definition TargetInfo.h:217
@ OCLTK_ClkEvent
Definition TargetInfo.h:214
@ OCLTK_Event
Definition TargetInfo.h:215
@ OCLTK_Default
Definition TargetInfo.h:213
@ OCLTK_Queue
Definition TargetInfo.h:218
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8553
Stmt Stmt * Callback
Definition StmtOpenMP.h:919
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
@ Nullable
Values of this type can be null.
Definition Specifiers.h:351
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:356
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:273
@ 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:125
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:258
@ SC_Static
Definition Specifiers.h:253
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3797
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:6013
@ Struct
The "struct" keyword.
Definition TypeBase.h:6010
@ Class
The "class" keyword.
Definition TypeBase.h:6019
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:491
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
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:74
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
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:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_M68kRTD
Definition Specifiers.h:299
@ CC_X86RegCall
Definition Specifiers.h:288
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ 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:4223
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4232
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4220
@ Generic
not a target-specific vector type
Definition TypeBase.h:4214
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4238
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4241
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4235
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ 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:845
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5983
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5988
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6004
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5985
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5994
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5991
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5997
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6001
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6768
Expr * getCopyExpr() const
Definition Expr.h:6775
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:5442
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5444
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5447
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5450
Extra information about a function prototype.
Definition TypeBase.h:5470
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5516
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5475
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5520
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5509
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:3417
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:233
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:146
AlignRequirementKind AlignRequirement
Definition ASTContext.h:205
bool isAlignRequired()
Definition ASTContext.h:197
AlignRequirementKind AlignRequirement
Definition ASTContext.h:191
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