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 void *InsertPos = nullptr;
730 CanonicalTemplateTemplateParm *Canonical
731 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
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.FindNodeOrInsertPos(ID, InsertPos);
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.InsertNode(Canonical, InsertPos);
806 return CanonTTP;
807}
808
811 TemplateTemplateParmDecl *TTP) const {
812 llvm::FoldingSetNodeID ID;
813 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
814 void *InsertPos = nullptr;
815 CanonicalTemplateTemplateParm *Canonical =
816 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
817 return Canonical ? Canonical->getParam() : nullptr;
818}
819
822 TemplateTemplateParmDecl *CanonTTP) const {
823 llvm::FoldingSetNodeID ID;
824 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
825 void *InsertPos = nullptr;
826 if (auto *Existing =
827 CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.InsertNode(
830 new (*this) CanonicalTemplateTemplateParm(CanonTTP), InsertPos);
831 return CanonTTP;
832}
833
834/// For the purposes of overflow pattern exclusion, does this match the
835/// while(i--) pattern?
836static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx) {
837 if (UO->getOpcode() != UO_PostDec)
838 return false;
839
840 if (!UO->getType()->isUnsignedIntegerType())
841 return false;
842
843 // -fsanitize-undefined-ignore-overflow-pattern=unsigned-post-decr-while
846 return false;
847
848 // all Parents (usually just one) must be a WhileStmt
849 return llvm::all_of(
851 [](const DynTypedNode &P) { return P.get<WhileStmt>() != nullptr; });
852}
853
855 // -fsanitize-undefined-ignore-overflow-pattern=negated-unsigned-const
856 // ... like -1UL;
857 if (UO->getOpcode() == UO_Minus &&
858 getLangOpts().isOverflowPatternExcluded(
860 UO->isIntegerConstantExpr(*this)) {
861 return true;
862 }
863
864 if (matchesPostDecrInWhile(UO, *this))
865 return true;
866
867 return false;
868}
869
870/// Check if a type can have its sanitizer instrumentation elided based on its
871/// presence within an ignorelist.
873 const QualType &Ty) const {
874 std::string TyName = Ty.getUnqualifiedType().getAsString(getPrintingPolicy());
875 return NoSanitizeL->containsType(Mask, TyName);
876}
877
879 auto Kind = getTargetInfo().getCXXABI().getKind();
880 return getLangOpts().CXXABI.value_or(Kind);
881}
882
883CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
884 if (!LangOpts.CPlusPlus) return nullptr;
885
886 switch (getCXXABIKind()) {
887 case TargetCXXABI::AppleARM64:
888 case TargetCXXABI::Fuchsia:
889 case TargetCXXABI::GenericARM: // Same as Itanium at this level
890 case TargetCXXABI::iOS:
891 case TargetCXXABI::WatchOS:
892 case TargetCXXABI::GenericAArch64:
893 case TargetCXXABI::GenericMIPS:
894 case TargetCXXABI::GenericItanium:
895 case TargetCXXABI::WebAssembly:
896 case TargetCXXABI::XL:
897 return CreateItaniumCXXABI(*this);
898 case TargetCXXABI::Microsoft:
899 return CreateMicrosoftCXXABI(*this);
900 }
901 llvm_unreachable("Invalid CXXABI type!");
902}
903
905 if (!InterpContext) {
906 InterpContext.reset(new interp::Context(const_cast<ASTContext &>(*this)));
907 }
908 return *InterpContext;
909}
910
912 if (!ParentMapCtx)
913 ParentMapCtx.reset(new ParentMapContext(*this));
914 return *ParentMapCtx;
915}
916
918 const LangOptions &LangOpts) {
919 switch (LangOpts.getAddressSpaceMapMangling()) {
921 return TI.useAddressSpaceMapMangling();
923 return true;
925 return false;
926 }
927 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
928}
929
931 IdentifierTable &idents, SelectorTable &sels,
933 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
934 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
935 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
936 DependentSizedMatrixTypes(this_()),
937 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
938 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
939 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
940 AttributedTypes(this_()), DependentBitIntTypes(this_()),
941 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
942 ArrayParameterTypes(this_()), CanonTemplateTemplateParms(this_()),
943 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 void *insertPos = nullptr;
3294 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
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.FindNodeOrInsertPos(ID, insertPos);
3308 }
3309
3310 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3311 ExtQualNodes.InsertNode(eq, insertPos);
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 void *InsertPos = nullptr;
3766 CountAttributedType *CATy =
3767 CountAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
3768 if (CATy)
3769 return QualType(CATy, 0);
3770
3771 QualType CanonTy = getCanonicalType(WrappedTy);
3772 size_t Size = CountAttributedType::totalSizeToAlloc<TypeCoupledDeclRefInfo>(
3773 DependentDecls.size());
3775 new (CATy) CountAttributedType(WrappedTy, CanonTy, CountExpr, CountInBytes,
3776 OrNull, DependentDecls);
3777 Types.push_back(CATy);
3778 CountAttributedTypes.InsertNode(CATy, InsertPos);
3779
3780 return QualType(CATy, 0);
3781}
3782
3784 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3785 QualType CanonTy = getCanonicalType(WrappedTy);
3786
3787 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3788 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3789
3790 Types.push_back(LPATy);
3791 return QualType(LPATy, 0);
3792}
3793
3796 llvm::function_ref<QualType(QualType)> Adjust) const {
3797 switch (Orig->getTypeClass()) {
3798 case Type::Attributed: {
3799 const auto *AT = cast<AttributedType>(Orig);
3800 return getAttributedType(AT->getAttrKind(),
3801 adjustType(AT->getModifiedType(), Adjust),
3802 adjustType(AT->getEquivalentType(), Adjust),
3803 AT->getAttr());
3804 }
3805
3806 case Type::BTFTagAttributed: {
3807 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3808 return getBTFTagAttributedType(BTFT->getAttr(),
3809 adjustType(BTFT->getWrappedType(), Adjust));
3810 }
3811
3812 case Type::OverflowBehavior: {
3813 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3814 return getOverflowBehaviorType(OB->getBehaviorKind(),
3815 adjustType(OB->getUnderlyingType(), Adjust));
3816 }
3817
3818 case Type::Paren:
3819 return getParenType(
3820 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3821
3822 case Type::Adjusted: {
3823 const auto *AT = cast<AdjustedType>(Orig);
3824 return getAdjustedType(AT->getOriginalType(),
3825 adjustType(AT->getAdjustedType(), Adjust));
3826 }
3827
3828 case Type::MacroQualified: {
3829 const auto *MQT = cast<MacroQualifiedType>(Orig);
3830 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3831 MQT->getMacroIdentifier());
3832 }
3833
3834 default:
3835 return Adjust(Orig);
3836 }
3837}
3838
3840 FunctionType::ExtInfo Info) {
3841 if (T->getExtInfo() == Info)
3842 return T;
3843
3845 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3846 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3847 } else {
3848 const auto *FPT = cast<FunctionProtoType>(T);
3849 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3850 EPI.ExtInfo = Info;
3851 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3852 }
3853
3854 return cast<FunctionType>(Result.getTypePtr());
3855}
3856
3858 QualType ResultType) {
3859 return adjustType(FunctionType, [&](QualType Orig) {
3860 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3861 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3862
3863 const auto *FPT = Orig->castAs<FunctionProtoType>();
3864 return getFunctionType(ResultType, FPT->getParamTypes(),
3865 FPT->getExtProtoInfo());
3866 });
3867}
3868
3870 QualType ResultType) {
3871 FD = FD->getMostRecentDecl();
3872 while (true) {
3873 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3874 if (FunctionDecl *Next = FD->getPreviousDecl())
3875 FD = Next;
3876 else
3877 break;
3878 }
3880 L->DeducedReturnType(FD, ResultType);
3881}
3882
3883/// Get a function type and produce the equivalent function type with the
3884/// specified exception specification. Type sugar that can be present on a
3885/// declaration of a function with an exception specification is permitted
3886/// and preserved. Other type sugar (for instance, typedefs) is not.
3888 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3889 return adjustType(Orig, [&](QualType Ty) {
3890 const auto *Proto = Ty->castAs<FunctionProtoType>();
3891 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3892 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3893 });
3894}
3895
3903
3905 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3906 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3907 SmallVector<QualType, 16> Args(Proto->param_types().size());
3908 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3909 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3910 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3911 }
3912
3913 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3914 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3915 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3916 }
3917
3918 return T;
3919}
3920
3926
3928 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3929 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3930 EPI.ExtParameterInfos = nullptr;
3931 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
3932 }
3933 return T;
3934}
3935
3941
3944 bool AsWritten) {
3945 // Update the type.
3946 QualType Updated =
3948 FD->setType(Updated);
3949
3950 if (!AsWritten)
3951 return;
3952
3953 // Update the type in the type source information too.
3954 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3955 // If the type and the type-as-written differ, we may need to update
3956 // the type-as-written too.
3957 if (TSInfo->getType() != FD->getType())
3958 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3959
3960 // FIXME: When we get proper type location information for exceptions,
3961 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3962 // up the TypeSourceInfo;
3963 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3964 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3965 "TypeLoc size mismatch from updating exception specification");
3966 TSInfo->overrideType(Updated);
3967 }
3968}
3969
3970/// getComplexType - Return the uniqued reference to the type for a complex
3971/// number with the specified element type.
3973 // Unique pointers, to guarantee there is only one pointer of a particular
3974 // structure.
3975 llvm::FoldingSetNodeID ID;
3977
3978 void *InsertPos = nullptr;
3979 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3980 return QualType(CT, 0);
3981
3982 // If the pointee type isn't canonical, this won't be a canonical type either,
3983 // so fill in the canonical type field.
3984 QualType Canonical;
3985 if (!T.isCanonical()) {
3986 Canonical = getComplexType(getCanonicalType(T));
3987
3988 // Get the new insert position for the node we care about.
3989 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3990 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3991 }
3992 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
3993 Types.push_back(New);
3994 ComplexTypes.InsertNode(New, InsertPos);
3995 return QualType(New, 0);
3996}
3997
3998/// getPointerType - Return the uniqued reference to the type for a pointer to
3999/// the specified type.
4001 // Unique pointers, to guarantee there is only one pointer of a particular
4002 // structure.
4003 llvm::FoldingSetNodeID ID;
4005
4006 void *InsertPos = nullptr;
4007 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4008 return QualType(PT, 0);
4009
4010 // If the pointee type isn't canonical, this won't be a canonical type either,
4011 // so fill in the canonical type field.
4012 QualType Canonical;
4013 if (!T.isCanonical()) {
4014 Canonical = getPointerType(getCanonicalType(T));
4015
4016 // Get the new insert position for the node we care about.
4017 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4019 }
4020 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4021 Types.push_back(New);
4022 PointerTypes.InsertNode(New, InsertPos);
4023 return QualType(New, 0);
4024}
4025
4027 llvm::FoldingSetNodeID ID;
4028 AdjustedType::Profile(ID, Orig, New);
4029 void *InsertPos = nullptr;
4030 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4031 if (AT)
4032 return QualType(AT, 0);
4033
4034 QualType Canonical = getCanonicalType(New);
4035
4036 // Get the new insert position for the node we care about.
4037 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4038 assert(!AT && "Shouldn't be in the map!");
4039
4040 AT = new (*this, alignof(AdjustedType))
4041 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4042 Types.push_back(AT);
4043 AdjustedTypes.InsertNode(AT, InsertPos);
4044 return QualType(AT, 0);
4045}
4046
4048 llvm::FoldingSetNodeID ID;
4049 AdjustedType::Profile(ID, Orig, Decayed);
4050 void *InsertPos = nullptr;
4051 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4052 if (AT)
4053 return QualType(AT, 0);
4054
4055 QualType Canonical = getCanonicalType(Decayed);
4056
4057 // Get the new insert position for the node we care about.
4058 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
4059 assert(!AT && "Shouldn't be in the map!");
4060
4061 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4062 Types.push_back(AT);
4063 AdjustedTypes.InsertNode(AT, InsertPos);
4064 return QualType(AT, 0);
4065}
4066
4068 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4069
4070 QualType Decayed;
4071
4072 // C99 6.7.5.3p7:
4073 // A declaration of a parameter as "array of type" shall be
4074 // adjusted to "qualified pointer to type", where the type
4075 // qualifiers (if any) are those specified within the [ and ] of
4076 // the array type derivation.
4077 if (T->isArrayType())
4078 Decayed = getArrayDecayedType(T);
4079
4080 // C99 6.7.5.3p8:
4081 // A declaration of a parameter as "function returning type"
4082 // shall be adjusted to "pointer to function returning type", as
4083 // in 6.3.2.1.
4084 if (T->isFunctionType())
4085 Decayed = getPointerType(T);
4086
4087 return getDecayedType(T, Decayed);
4088}
4089
4091 if (Ty->isArrayParameterType())
4092 return Ty;
4093 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4094 QualType DTy = Ty.getDesugaredType(*this);
4095 const auto *ATy = cast<ConstantArrayType>(DTy);
4096 llvm::FoldingSetNodeID ID;
4097 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4098 ATy->getSizeExpr(), ATy->getSizeModifier(),
4099 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4100 void *InsertPos = nullptr;
4101 ArrayParameterType *AT =
4102 ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4103 if (AT)
4104 return QualType(AT, 0);
4105
4106 QualType Canonical;
4107 if (!DTy.isCanonical()) {
4108 Canonical = getArrayParameterType(getCanonicalType(Ty));
4109
4110 // Get the new insert position for the node we care about.
4111 AT = ArrayParameterTypes.FindNodeOrInsertPos(ID, InsertPos);
4112 assert(!AT && "Shouldn't be in the map!");
4113 }
4114
4115 AT = new (*this, alignof(ArrayParameterType))
4116 ArrayParameterType(ATy, Canonical);
4117 Types.push_back(AT);
4118 ArrayParameterTypes.InsertNode(AT, InsertPos);
4119 return QualType(AT, 0);
4120}
4121
4122/// getBlockPointerType - Return the uniqued reference to the type for
4123/// a pointer to the specified block.
4125 assert(T->isFunctionType() && "block of function types only");
4126 // Unique pointers, to guarantee there is only one block of a particular
4127 // structure.
4128 llvm::FoldingSetNodeID ID;
4130
4131 void *InsertPos = nullptr;
4132 if (BlockPointerType *PT =
4133 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4134 return QualType(PT, 0);
4135
4136 // If the block pointee type isn't canonical, this won't be a canonical
4137 // type either so fill in the canonical type field.
4138 QualType Canonical;
4139 if (!T.isCanonical()) {
4141
4142 // Get the new insert position for the node we care about.
4143 BlockPointerType *NewIP =
4144 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4145 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4146 }
4147 auto *New =
4148 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4149 Types.push_back(New);
4150 BlockPointerTypes.InsertNode(New, InsertPos);
4151 return QualType(New, 0);
4152}
4153
4154/// getLValueReferenceType - Return the uniqued reference to the type for an
4155/// lvalue reference to the specified type.
4157ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4158 assert((!T->isPlaceholderType() ||
4159 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4160 "Unresolved placeholder type");
4161
4162 // Unique pointers, to guarantee there is only one pointer of a particular
4163 // structure.
4164 llvm::FoldingSetNodeID ID;
4165 ReferenceType::Profile(ID, T, SpelledAsLValue);
4166
4167 void *InsertPos = nullptr;
4168 if (LValueReferenceType *RT =
4169 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
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 (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4178 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4179 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4180
4181 // Get the new insert position for the node we care about.
4182 LValueReferenceType *NewIP =
4183 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4184 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4185 }
4186
4187 auto *New = new (*this, alignof(LValueReferenceType))
4188 LValueReferenceType(T, Canonical, SpelledAsLValue);
4189 Types.push_back(New);
4190 LValueReferenceTypes.InsertNode(New, InsertPos);
4191
4192 return QualType(New, 0);
4193}
4194
4195/// getRValueReferenceType - Return the uniqued reference to the type for an
4196/// rvalue reference to the specified type.
4198 assert((!T->isPlaceholderType() ||
4199 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4200 "Unresolved placeholder type");
4201
4202 // Unique pointers, to guarantee there is only one pointer of a particular
4203 // structure.
4204 llvm::FoldingSetNodeID ID;
4205 ReferenceType::Profile(ID, T, false);
4206
4207 void *InsertPos = nullptr;
4208 if (RValueReferenceType *RT =
4209 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
4210 return QualType(RT, 0);
4211
4212 const auto *InnerRef = T->getAs<ReferenceType>();
4213
4214 // If the referencee type isn't canonical, this won't be a canonical type
4215 // either, so fill in the canonical type field.
4216 QualType Canonical;
4217 if (InnerRef || !T.isCanonical()) {
4218 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4219 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4220
4221 // Get the new insert position for the node we care about.
4222 RValueReferenceType *NewIP =
4223 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
4224 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4225 }
4226
4227 auto *New = new (*this, alignof(RValueReferenceType))
4228 RValueReferenceType(T, Canonical);
4229 Types.push_back(New);
4230 RValueReferenceTypes.InsertNode(New, InsertPos);
4231 return QualType(New, 0);
4232}
4233
4235 NestedNameSpecifier Qualifier,
4236 const CXXRecordDecl *Cls) const {
4237 if (!Qualifier) {
4238 assert(Cls && "At least one of Qualifier or Cls must be provided");
4239 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4240 } else if (!Cls) {
4241 Cls = Qualifier.getAsRecordDecl();
4242 }
4243 // Unique pointers, to guarantee there is only one pointer of a particular
4244 // structure.
4245 llvm::FoldingSetNodeID ID;
4246 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4247
4248 void *InsertPos = nullptr;
4249 if (MemberPointerType *PT =
4250 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4251 return QualType(PT, 0);
4252
4253 NestedNameSpecifier CanonicalQualifier = [&] {
4254 if (!Cls)
4255 return Qualifier.getCanonical();
4256 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4257 assert(R.isCanonical());
4258 return R;
4259 }();
4260 // If the pointee or class type isn't canonical, this won't be a canonical
4261 // type either, so fill in the canonical type field.
4262 QualType Canonical;
4263 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4264 Canonical =
4265 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4266 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4267 // Get the new insert position for the node we care about.
4268 [[maybe_unused]] MemberPointerType *NewIP =
4269 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4270 assert(!NewIP && "Shouldn't be in the map!");
4271 }
4272 auto *New = new (*this, alignof(MemberPointerType))
4273 MemberPointerType(T, Qualifier, Canonical);
4274 Types.push_back(New);
4275 MemberPointerTypes.InsertNode(New, InsertPos);
4276 return QualType(New, 0);
4277}
4278
4279/// getConstantArrayType - Return the unique reference to the type for an
4280/// array of the specified element type.
4282 const llvm::APInt &ArySizeIn,
4283 const Expr *SizeExpr,
4285 unsigned IndexTypeQuals) const {
4286 assert((EltTy->isDependentType() ||
4287 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4288 "Constant array of VLAs is illegal!");
4289
4290 // We only need the size as part of the type if it's instantiation-dependent.
4291 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4292 SizeExpr = nullptr;
4293
4294 // Convert the array size into a canonical width matching the pointer size for
4295 // the target.
4296 llvm::APInt ArySize(ArySizeIn);
4297 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4298
4299 llvm::FoldingSetNodeID ID;
4300 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4301 ASM, IndexTypeQuals);
4302
4303 void *InsertPos = nullptr;
4304 if (ConstantArrayType *ATP =
4305 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
4306 return QualType(ATP, 0);
4307
4308 // If the element type isn't canonical or has qualifiers, or the array bound
4309 // is instantiation-dependent, this won't be a canonical type either, so fill
4310 // in the canonical type field.
4311 QualType Canon;
4312 // FIXME: Check below should look for qualifiers behind sugar.
4313 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4314 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4315 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4316 ASM, IndexTypeQuals);
4317 Canon = getQualifiedType(Canon, canonSplit.Quals);
4318
4319 // Get the new insert position for the node we care about.
4320 ConstantArrayType *NewIP =
4321 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
4322 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4323 }
4324
4325 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4326 ASM, IndexTypeQuals);
4327 ConstantArrayTypes.InsertNode(New, InsertPos);
4328 Types.push_back(New);
4329 return QualType(New, 0);
4330}
4331
4332/// getVariableArrayDecayedType - Turns the given type, which may be
4333/// variably-modified, into the corresponding type with all the known
4334/// sizes replaced with [*].
4336 // Vastly most common case.
4337 if (!type->isVariablyModifiedType()) return type;
4338
4339 QualType result;
4340
4341 SplitQualType split = type.getSplitDesugaredType();
4342 const Type *ty = split.Ty;
4343 switch (ty->getTypeClass()) {
4344#define TYPE(Class, Base)
4345#define ABSTRACT_TYPE(Class, Base)
4346#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4347#include "clang/AST/TypeNodes.inc"
4348 llvm_unreachable("didn't desugar past all non-canonical types?");
4349
4350 // These types should never be variably-modified.
4351 case Type::Builtin:
4352 case Type::Complex:
4353 case Type::Vector:
4354 case Type::DependentVector:
4355 case Type::ExtVector:
4356 case Type::DependentSizedExtVector:
4357 case Type::ConstantMatrix:
4358 case Type::DependentSizedMatrix:
4359 case Type::DependentAddressSpace:
4360 case Type::ObjCObject:
4361 case Type::ObjCInterface:
4362 case Type::ObjCObjectPointer:
4363 case Type::Record:
4364 case Type::Enum:
4365 case Type::UnresolvedUsing:
4366 case Type::TypeOfExpr:
4367 case Type::TypeOf:
4368 case Type::Decltype:
4369 case Type::UnaryTransform:
4370 case Type::DependentName:
4371 case Type::InjectedClassName:
4372 case Type::TemplateSpecialization:
4373 case Type::TemplateTypeParm:
4374 case Type::SubstTemplateTypeParmPack:
4375 case Type::SubstBuiltinTemplatePack:
4376 case Type::Auto:
4377 case Type::DeducedTemplateSpecialization:
4378 case Type::PackExpansion:
4379 case Type::PackIndexing:
4380 case Type::BitInt:
4381 case Type::DependentBitInt:
4382 case Type::ArrayParameter:
4383 case Type::HLSLAttributedResource:
4384 case Type::HLSLInlineSpirv:
4385 case Type::OverflowBehavior:
4386 llvm_unreachable("type should never be variably-modified");
4387
4388 // These types can be variably-modified but should never need to
4389 // further decay.
4390 case Type::FunctionNoProto:
4391 case Type::FunctionProto:
4392 case Type::BlockPointer:
4393 case Type::MemberPointer:
4394 case Type::Pipe:
4395 return type;
4396
4397 // These types can be variably-modified. All these modifications
4398 // preserve structure except as noted by comments.
4399 // TODO: if we ever care about optimizing VLAs, there are no-op
4400 // optimizations available here.
4401 case Type::Pointer:
4404 break;
4405
4406 case Type::LValueReference: {
4407 const auto *lv = cast<LValueReferenceType>(ty);
4408 result = getLValueReferenceType(
4409 getVariableArrayDecayedType(lv->getPointeeType()),
4410 lv->isSpelledAsLValue());
4411 break;
4412 }
4413
4414 case Type::RValueReference: {
4415 const auto *lv = cast<RValueReferenceType>(ty);
4416 result = getRValueReferenceType(
4417 getVariableArrayDecayedType(lv->getPointeeType()));
4418 break;
4419 }
4420
4421 case Type::Atomic: {
4422 const auto *at = cast<AtomicType>(ty);
4423 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4424 break;
4425 }
4426
4427 case Type::ConstantArray: {
4428 const auto *cat = cast<ConstantArrayType>(ty);
4429 result = getConstantArrayType(
4430 getVariableArrayDecayedType(cat->getElementType()),
4431 cat->getSize(),
4432 cat->getSizeExpr(),
4433 cat->getSizeModifier(),
4434 cat->getIndexTypeCVRQualifiers());
4435 break;
4436 }
4437
4438 case Type::DependentSizedArray: {
4439 const auto *dat = cast<DependentSizedArrayType>(ty);
4441 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4442 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4443 break;
4444 }
4445
4446 // Turn incomplete types into [*] types.
4447 case Type::IncompleteArray: {
4448 const auto *iat = cast<IncompleteArrayType>(ty);
4449 result =
4451 /*size*/ nullptr, ArraySizeModifier::Normal,
4452 iat->getIndexTypeCVRQualifiers());
4453 break;
4454 }
4455
4456 // Turn VLA types into [*] types.
4457 case Type::VariableArray: {
4458 const auto *vat = cast<VariableArrayType>(ty);
4459 result =
4461 /*size*/ nullptr, ArraySizeModifier::Star,
4462 vat->getIndexTypeCVRQualifiers());
4463 break;
4464 }
4465 }
4466
4467 // Apply the top-level qualifiers from the original.
4468 return getQualifiedType(result, split.Quals);
4469}
4470
4471/// getVariableArrayType - Returns a non-unique reference to the type for a
4472/// variable array of the specified element type.
4475 unsigned IndexTypeQuals) const {
4476 // Since we don't unique expressions, it isn't possible to unique VLA's
4477 // that have an expression provided for their size.
4478 QualType Canon;
4479
4480 // Be sure to pull qualifiers off the element type.
4481 // FIXME: Check below should look for qualifiers behind sugar.
4482 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4483 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4484 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4485 IndexTypeQuals);
4486 Canon = getQualifiedType(Canon, canonSplit.Quals);
4487 }
4488
4489 auto *New = new (*this, alignof(VariableArrayType))
4490 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4491
4492 VariableArrayTypes.push_back(New);
4493 Types.push_back(New);
4494 return QualType(New, 0);
4495}
4496
4497/// getDependentSizedArrayType - Returns a non-unique reference to
4498/// the type for a dependently-sized array of the specified element
4499/// type.
4503 unsigned elementTypeQuals) const {
4504 assert((!numElements || numElements->isTypeDependent() ||
4505 numElements->isValueDependent()) &&
4506 "Size must be type- or value-dependent!");
4507
4508 SplitQualType canonElementType = getCanonicalType(elementType).split();
4509
4510 void *insertPos = nullptr;
4511 llvm::FoldingSetNodeID ID;
4513 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4514 ASM, elementTypeQuals, numElements);
4515
4516 // Look for an existing type with these properties.
4517 DependentSizedArrayType *canonTy =
4518 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4519
4520 // Dependently-sized array types that do not have a specified number
4521 // of elements will have their sizes deduced from a dependent
4522 // initializer.
4523 if (!numElements) {
4524 if (canonTy)
4525 return QualType(canonTy, 0);
4526
4527 auto *newType = new (*this, alignof(DependentSizedArrayType))
4528 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4529 elementTypeQuals);
4530 DependentSizedArrayTypes.InsertNode(newType, insertPos);
4531 Types.push_back(newType);
4532 return QualType(newType, 0);
4533 }
4534
4535 // If we don't have one, build one.
4536 if (!canonTy) {
4537 canonTy = new (*this, alignof(DependentSizedArrayType))
4538 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4539 numElements, ASM, elementTypeQuals);
4540 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
4541 Types.push_back(canonTy);
4542 }
4543
4544 // Apply qualifiers from the element type to the array.
4545 QualType canon = getQualifiedType(QualType(canonTy,0),
4546 canonElementType.Quals);
4547
4548 // If we didn't need extra canonicalization for the element type or the size
4549 // expression, then just use that as our result.
4550 if (QualType(canonElementType.Ty, 0) == elementType &&
4551 canonTy->getSizeExpr() == numElements)
4552 return canon;
4553
4554 // Otherwise, we need to build a type which follows the spelling
4555 // of the element type.
4556 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4557 DependentSizedArrayType(elementType, canon, numElements, ASM,
4558 elementTypeQuals);
4559 Types.push_back(sugaredType);
4560 return QualType(sugaredType, 0);
4561}
4562
4565 unsigned elementTypeQuals) const {
4566 llvm::FoldingSetNodeID ID;
4567 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4568
4569 void *insertPos = nullptr;
4570 if (IncompleteArrayType *iat =
4571 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
4572 return QualType(iat, 0);
4573
4574 // If the element type isn't canonical, this won't be a canonical type
4575 // either, so fill in the canonical type field. We also have to pull
4576 // qualifiers off the element type.
4577 QualType canon;
4578
4579 // FIXME: Check below should look for qualifiers behind sugar.
4580 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4581 SplitQualType canonSplit = getCanonicalType(elementType).split();
4582 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4583 ASM, elementTypeQuals);
4584 canon = getQualifiedType(canon, canonSplit.Quals);
4585
4586 // Get the new insert position for the node we care about.
4587 IncompleteArrayType *existing =
4588 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
4589 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4590 }
4591
4592 auto *newType = new (*this, alignof(IncompleteArrayType))
4593 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4594
4595 IncompleteArrayTypes.InsertNode(newType, insertPos);
4596 Types.push_back(newType);
4597 return QualType(newType, 0);
4598}
4599
4602#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4603 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4604 NUMVECTORS};
4605
4606#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4607 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4608
4609 switch (Ty->getKind()) {
4610 default:
4611 llvm_unreachable("Unsupported builtin vector type");
4612
4613#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4614 ElBits, NF, IsSigned) \
4615 case BuiltinType::Id: \
4616 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4617 llvm::ElementCount::getScalable(NumEls), NF};
4618#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4619 ElBits, NF) \
4620 case BuiltinType::Id: \
4621 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4622 llvm::ElementCount::getScalable(NumEls), NF};
4623#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4624 ElBits, NF) \
4625 case BuiltinType::Id: \
4626 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4627#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4628 ElBits, NF) \
4629 case BuiltinType::Id: \
4630 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4631#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4632 case BuiltinType::Id: \
4633 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4634#include "clang/Basic/AArch64ACLETypes.def"
4635
4636#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4637 IsSigned) \
4638 case BuiltinType::Id: \
4639 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4640 llvm::ElementCount::getScalable(NumEls), NF};
4641#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4642 case BuiltinType::Id: \
4643 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4644 llvm::ElementCount::getScalable(NumEls), NF};
4645#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4646 case BuiltinType::Id: \
4647 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4648#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4649 case BuiltinType::Id: \
4650 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4651#include "clang/Basic/RISCVVTypes.def"
4652 }
4653}
4654
4655/// getExternrefType - Return a WebAssembly externref type, which represents an
4656/// opaque reference to a host value.
4658 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4659#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4660 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4661 return SingletonId;
4662#include "clang/Basic/WebAssemblyReferenceTypes.def"
4663 }
4664 llvm_unreachable(
4665 "shouldn't try to generate type externref outside WebAssembly target");
4666}
4667
4668/// getScalableVectorType - Return the unique reference to a scalable vector
4669/// type of the specified element type and size. VectorType must be a built-in
4670/// type.
4672 unsigned NumFields) const {
4673 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4674 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4675 return It->second;
4676
4677 if (Target->hasAArch64ACLETypes()) {
4678 uint64_t EltTySize = getTypeSize(EltTy);
4679
4680#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4681 ElBits, NF, IsSigned) \
4682 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4683 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4684 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4685 return ScalableVecTyMap[K] = SingletonId; \
4686 }
4687#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4688 ElBits, NF) \
4689 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4690 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4691 return ScalableVecTyMap[K] = SingletonId; \
4692 }
4693#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4694 ElBits, NF) \
4695 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4696 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4697 return ScalableVecTyMap[K] = SingletonId; \
4698 }
4699#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4700 ElBits, NF) \
4701 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4702 NumElts == (NumEls * NF) && NumFields == 1) { \
4703 return ScalableVecTyMap[K] = SingletonId; \
4704 }
4705#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4706 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4707 return ScalableVecTyMap[K] = SingletonId;
4708#include "clang/Basic/AArch64ACLETypes.def"
4709 } else if (Target->hasRISCVVTypes()) {
4710 uint64_t EltTySize = getTypeSize(EltTy);
4711#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4712 IsFP, IsBF) \
4713 if (!EltTy->isBooleanType() && \
4714 ((EltTy->hasIntegerRepresentation() && \
4715 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4716 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4717 IsFP && !IsBF) || \
4718 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4719 IsBF && !IsFP)) && \
4720 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4721 return ScalableVecTyMap[K] = SingletonId;
4722#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4723 if (EltTy->isBooleanType() && NumElts == NumEls) \
4724 return ScalableVecTyMap[K] = SingletonId;
4725#include "clang/Basic/RISCVVTypes.def"
4726 }
4727 return QualType();
4728}
4729
4730/// getVectorType - Return the unique reference to a vector type of
4731/// the specified element type and size. VectorType must be a built-in type.
4733 VectorKind VecKind) const {
4734 assert(vecType->isBuiltinType() ||
4735 (vecType->isBitIntType() &&
4736 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4737 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4738
4739 // Check if we've already instantiated a vector of this type.
4740 llvm::FoldingSetNodeID ID;
4741 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4742
4743 void *InsertPos = nullptr;
4744 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4745 return QualType(VTP, 0);
4746
4747 // If the element type isn't canonical, this won't be a canonical type either,
4748 // so fill in the canonical type field.
4749 QualType Canonical;
4750 if (!vecType.isCanonical()) {
4751 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4752
4753 // Get the new insert position for the node we care about.
4754 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4755 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4756 }
4757 auto *New = new (*this, alignof(VectorType))
4758 VectorType(vecType, NumElts, Canonical, VecKind);
4759 VectorTypes.InsertNode(New, InsertPos);
4760 Types.push_back(New);
4761 return QualType(New, 0);
4762}
4763
4765 SourceLocation AttrLoc,
4766 VectorKind VecKind) const {
4767 llvm::FoldingSetNodeID ID;
4768 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4769 VecKind);
4770 void *InsertPos = nullptr;
4771 DependentVectorType *Canon =
4772 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4774
4775 if (Canon) {
4776 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4777 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4778 } else {
4779 QualType CanonVecTy = getCanonicalType(VecType);
4780 if (CanonVecTy == VecType) {
4781 New = new (*this, alignof(DependentVectorType))
4782 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4783
4784 DependentVectorType *CanonCheck =
4785 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4786 assert(!CanonCheck &&
4787 "Dependent-sized vector_size canonical type broken");
4788 (void)CanonCheck;
4789 DependentVectorTypes.InsertNode(New, InsertPos);
4790 } else {
4791 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4792 SourceLocation(), VecKind);
4793 New = new (*this, alignof(DependentVectorType))
4794 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4795 }
4796 }
4797
4798 Types.push_back(New);
4799 return QualType(New, 0);
4800}
4801
4802/// getExtVectorType - Return the unique reference to an extended vector type of
4803/// the specified element type and size. VectorType must be a built-in type.
4805 unsigned NumElts) const {
4806 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4807 (vecType->isBitIntType() &&
4808 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4809 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4810
4811 // Check if we've already instantiated a vector of this type.
4812 llvm::FoldingSetNodeID ID;
4813 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4815 void *InsertPos = nullptr;
4816 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
4817 return QualType(VTP, 0);
4818
4819 // If the element type isn't canonical, this won't be a canonical type either,
4820 // so fill in the canonical type field.
4821 QualType Canonical;
4822 if (!vecType.isCanonical()) {
4823 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4824
4825 // Get the new insert position for the node we care about.
4826 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4827 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4828 }
4829 auto *New = new (*this, alignof(ExtVectorType))
4830 ExtVectorType(vecType, NumElts, Canonical);
4831 VectorTypes.InsertNode(New, InsertPos);
4832 Types.push_back(New);
4833 return QualType(New, 0);
4834}
4835
4838 Expr *SizeExpr,
4839 SourceLocation AttrLoc) const {
4840 llvm::FoldingSetNodeID ID;
4842 SizeExpr);
4843
4844 void *InsertPos = nullptr;
4846 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4848 if (Canon) {
4849 // We already have a canonical version of this array type; use it as
4850 // the canonical type for a newly-built type.
4851 New = new (*this, alignof(DependentSizedExtVectorType))
4852 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4853 AttrLoc);
4854 } else {
4855 QualType CanonVecTy = getCanonicalType(vecType);
4856 if (CanonVecTy == vecType) {
4857 New = new (*this, alignof(DependentSizedExtVectorType))
4858 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4859
4860 DependentSizedExtVectorType *CanonCheck
4861 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
4862 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4863 (void)CanonCheck;
4864 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
4865 } else {
4866 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4867 SourceLocation());
4868 New = new (*this, alignof(DependentSizedExtVectorType))
4869 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4870 }
4871 }
4872
4873 Types.push_back(New);
4874 return QualType(New, 0);
4875}
4876
4878 unsigned NumColumns) const {
4879 llvm::FoldingSetNodeID ID;
4880 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
4881 Type::ConstantMatrix);
4882
4883 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4884 "need a valid element type");
4885 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4886 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4887 "need valid matrix dimensions");
4888 void *InsertPos = nullptr;
4889 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
4890 return QualType(MTP, 0);
4891
4892 QualType Canonical;
4893 if (!ElementTy.isCanonical()) {
4894 Canonical =
4895 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
4896
4897 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4898 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4899 (void)NewIP;
4900 }
4901
4902 auto *New = new (*this, alignof(ConstantMatrixType))
4903 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
4904 MatrixTypes.InsertNode(New, InsertPos);
4905 Types.push_back(New);
4906 return QualType(New, 0);
4907}
4908
4910 Expr *RowExpr,
4911 Expr *ColumnExpr,
4912 SourceLocation AttrLoc) const {
4913 QualType CanonElementTy = getCanonicalType(ElementTy);
4914 llvm::FoldingSetNodeID ID;
4915 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4916 ColumnExpr);
4917
4918 void *InsertPos = nullptr;
4920 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4921
4922 if (!Canon) {
4923 Canon = new (*this, alignof(DependentSizedMatrixType))
4924 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4925 ColumnExpr, AttrLoc);
4926#ifndef NDEBUG
4927 DependentSizedMatrixType *CanonCheck =
4928 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
4929 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4930#endif
4931 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
4932 Types.push_back(Canon);
4933 }
4934
4935 // Already have a canonical version of the matrix type
4936 //
4937 // If it exactly matches the requested type, use it directly.
4938 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4939 Canon->getRowExpr() == ColumnExpr)
4940 return QualType(Canon, 0);
4941
4942 // Use Canon as the canonical type for newly-built type.
4944 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4945 ColumnExpr, AttrLoc);
4946 Types.push_back(New);
4947 return QualType(New, 0);
4948}
4949
4951 Expr *AddrSpaceExpr,
4952 SourceLocation AttrLoc) const {
4953 assert(AddrSpaceExpr->isInstantiationDependent());
4954
4955 QualType canonPointeeType = getCanonicalType(PointeeType);
4956
4957 void *insertPos = nullptr;
4958 llvm::FoldingSetNodeID ID;
4959 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
4960 AddrSpaceExpr);
4961
4962 DependentAddressSpaceType *canonTy =
4963 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
4964
4965 if (!canonTy) {
4966 canonTy = new (*this, alignof(DependentAddressSpaceType))
4967 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
4968 AttrLoc);
4969 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
4970 Types.push_back(canonTy);
4971 }
4972
4973 if (canonPointeeType == PointeeType &&
4974 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
4975 return QualType(canonTy, 0);
4976
4977 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
4978 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
4979 AddrSpaceExpr, AttrLoc);
4980 Types.push_back(sugaredType);
4981 return QualType(sugaredType, 0);
4982}
4983
4984/// Determine whether \p T is canonical as the result type of a function.
4986 return T.isCanonical() &&
4987 (T.getObjCLifetime() == Qualifiers::OCL_None ||
4988 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
4989}
4990
4991/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
4992QualType
4994 const FunctionType::ExtInfo &Info) const {
4995 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
4996 // functionality creates a function without a prototype regardless of
4997 // language mode (so it makes them even in C++). Once the rewriter has been
4998 // fixed, this assertion can be enabled again.
4999 //assert(!LangOpts.requiresStrictPrototypes() &&
5000 // "strict prototypes are disabled");
5001
5002 // Unique functions, to guarantee there is only one function of a particular
5003 // structure.
5004 llvm::FoldingSetNodeID ID;
5005 FunctionNoProtoType::Profile(ID, ResultTy, Info);
5006
5007 void *InsertPos = nullptr;
5008 if (FunctionNoProtoType *FT =
5009 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
5010 return QualType(FT, 0);
5011
5012 QualType Canonical;
5013 if (!isCanonicalResultType(ResultTy)) {
5014 Canonical =
5016
5017 // Get the new insert position for the node we care about.
5018 FunctionNoProtoType *NewIP =
5019 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5020 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5021 }
5022
5023 auto *New = new (*this, alignof(FunctionNoProtoType))
5024 FunctionNoProtoType(ResultTy, Canonical, Info);
5025 Types.push_back(New);
5026 FunctionNoProtoTypes.InsertNode(New, InsertPos);
5027 return QualType(New, 0);
5028}
5029
5032 CanQualType CanResultType = getCanonicalType(ResultType);
5033
5034 // Canonical result types do not have ARC lifetime qualifiers.
5035 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5036 Qualifiers Qs = CanResultType.getQualifiers();
5037 Qs.removeObjCLifetime();
5039 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5040 }
5041
5042 return CanResultType;
5043}
5044
5046 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5047 if (ESI.Type == EST_None)
5048 return true;
5049 if (!NoexceptInType)
5050 return false;
5051
5052 // C++17 onwards: exception specification is part of the type, as a simple
5053 // boolean "can this function type throw".
5054 if (ESI.Type == EST_BasicNoexcept)
5055 return true;
5056
5057 // A noexcept(expr) specification is (possibly) canonical if expr is
5058 // value-dependent.
5059 if (ESI.Type == EST_DependentNoexcept)
5060 return true;
5061
5062 // A dynamic exception specification is canonical if it only contains pack
5063 // expansions (so we can't tell whether it's non-throwing) and all its
5064 // contained types are canonical.
5065 if (ESI.Type == EST_Dynamic) {
5066 bool AnyPackExpansions = false;
5067 for (QualType ET : ESI.Exceptions) {
5068 if (!ET.isCanonical())
5069 return false;
5070 if (ET->getAs<PackExpansionType>())
5071 AnyPackExpansions = true;
5072 }
5073 return AnyPackExpansions;
5074 }
5075
5076 return false;
5077}
5078
5079QualType ASTContext::getFunctionTypeInternal(
5080 QualType ResultTy, ArrayRef<QualType> ArgArray,
5081 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5082 size_t NumArgs = ArgArray.size();
5083
5084 // Unique functions, to guarantee there is only one function of a particular
5085 // structure.
5086 llvm::FoldingSetNodeID ID;
5087 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5088 *this, true);
5089
5090 QualType Canonical;
5091 bool Unique = false;
5092
5093 void *InsertPos = nullptr;
5094 if (FunctionProtoType *FPT =
5095 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5096 QualType Existing = QualType(FPT, 0);
5097
5098 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5099 // it so long as our exception specification doesn't contain a dependent
5100 // noexcept expression, or we're just looking for a canonical type.
5101 // Otherwise, we're going to need to create a type
5102 // sugar node to hold the concrete expression.
5103 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5104 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5105 return Existing;
5106
5107 // We need a new type sugar node for this one, to hold the new noexcept
5108 // expression. We do no canonicalization here, but that's OK since we don't
5109 // expect to see the same noexcept expression much more than once.
5110 Canonical = getCanonicalType(Existing);
5111 Unique = true;
5112 }
5113
5114 bool NoexceptInType = getLangOpts().CPlusPlus17;
5115 bool IsCanonicalExceptionSpec =
5117
5118 // Determine whether the type being created is already canonical or not.
5119 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5120 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5121 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5122 if (!ArgArray[i].isCanonicalAsParam())
5123 isCanonical = false;
5124
5125 if (OnlyWantCanonical)
5126 assert(isCanonical &&
5127 "given non-canonical parameters constructing canonical type");
5128
5129 // If this type isn't canonical, get the canonical version of it if we don't
5130 // already have it. The exception spec is only partially part of the
5131 // canonical type, and only in C++17 onwards.
5132 if (!isCanonical && Canonical.isNull()) {
5133 SmallVector<QualType, 16> CanonicalArgs;
5134 CanonicalArgs.reserve(NumArgs);
5135 for (unsigned i = 0; i != NumArgs; ++i)
5136 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5137
5138 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5139 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5140 CanonicalEPI.HasTrailingReturn = false;
5141
5142 if (IsCanonicalExceptionSpec) {
5143 // Exception spec is already OK.
5144 } else if (NoexceptInType) {
5145 switch (EPI.ExceptionSpec.Type) {
5147 // We don't know yet. It shouldn't matter what we pick here; no-one
5148 // should ever look at this.
5149 [[fallthrough]];
5150 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5151 CanonicalEPI.ExceptionSpec.Type = EST_None;
5152 break;
5153
5154 // A dynamic exception specification is almost always "not noexcept",
5155 // with the exception that a pack expansion might expand to no types.
5156 case EST_Dynamic: {
5157 bool AnyPacks = false;
5158 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5159 if (ET->getAs<PackExpansionType>())
5160 AnyPacks = true;
5161 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5162 }
5163 if (!AnyPacks)
5164 CanonicalEPI.ExceptionSpec.Type = EST_None;
5165 else {
5166 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5167 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5168 }
5169 break;
5170 }
5171
5172 case EST_DynamicNone:
5173 case EST_BasicNoexcept:
5174 case EST_NoexceptTrue:
5175 case EST_NoThrow:
5176 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5177 break;
5178
5180 llvm_unreachable("dependent noexcept is already canonical");
5181 }
5182 } else {
5183 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5184 }
5185
5186 // Adjust the canonical function result type.
5187 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5188 Canonical =
5189 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5190
5191 // Get the new insert position for the node we care about.
5192 FunctionProtoType *NewIP =
5193 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
5194 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5195 }
5196
5197 // Compute the needed size to hold this FunctionProtoType and the
5198 // various trailing objects.
5199 auto ESH = FunctionProtoType::getExceptionSpecSize(
5200 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5201 size_t Size = FunctionProtoType::totalSizeToAlloc<
5202 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5203 FunctionType::FunctionTypeExtraAttributeInfo,
5204 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5205 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5206 FunctionEffect, EffectConditionExpr>(
5209 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5210 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5211 EPI.ExtParameterInfos ? NumArgs : 0,
5213 EPI.FunctionEffects.conditions().size());
5214
5215 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5216 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5217 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5218 Types.push_back(FTP);
5219 if (!Unique)
5220 FunctionProtoTypes.InsertNode(FTP, InsertPos);
5221 if (!EPI.FunctionEffects.empty())
5222 AnyFunctionEffects = true;
5223 return QualType(FTP, 0);
5224}
5225
5226QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5227 llvm::FoldingSetNodeID ID;
5228 PipeType::Profile(ID, T, ReadOnly);
5229
5230 void *InsertPos = nullptr;
5231 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
5232 return QualType(PT, 0);
5233
5234 // If the pipe element type isn't canonical, this won't be a canonical type
5235 // either, so fill in the canonical type field.
5236 QualType Canonical;
5237 if (!T.isCanonical()) {
5238 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5239
5240 // Get the new insert position for the node we care about.
5241 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
5242 assert(!NewIP && "Shouldn't be in the map!");
5243 (void)NewIP;
5244 }
5245 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5246 Types.push_back(New);
5247 PipeTypes.InsertNode(New, InsertPos);
5248 return QualType(New, 0);
5249}
5250
5252 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5253 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5254 : Ty;
5255}
5256
5258 return getPipeType(T, true);
5259}
5260
5262 return getPipeType(T, false);
5263}
5264
5265QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5266 llvm::FoldingSetNodeID ID;
5267 BitIntType::Profile(ID, IsUnsigned, NumBits);
5268
5269 void *InsertPos = nullptr;
5270 if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5271 return QualType(EIT, 0);
5272
5273 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5274 BitIntTypes.InsertNode(New, InsertPos);
5275 Types.push_back(New);
5276 return QualType(New, 0);
5277}
5278
5280 Expr *NumBitsExpr) const {
5281 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5282 llvm::FoldingSetNodeID ID;
5283 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5284
5285 void *InsertPos = nullptr;
5286 if (DependentBitIntType *Existing =
5287 DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
5288 return QualType(Existing, 0);
5289
5290 auto *New = new (*this, alignof(DependentBitIntType))
5291 DependentBitIntType(IsUnsigned, NumBitsExpr);
5292 DependentBitIntTypes.InsertNode(New, InsertPos);
5293
5294 Types.push_back(New);
5295 return QualType(New, 0);
5296}
5297
5300 using Kind = PredefinedSugarType::Kind;
5301
5302 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5303 Target != nullptr)
5304 return QualType(Target, 0);
5305
5306 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5307 switch (KDI) {
5308 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5309 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5310 // are part of the core language and are widely used. Using
5311 // PredefinedSugarType makes these types as named sugar types rather than
5312 // standard integer types, enabling better hints and diagnostics.
5313 case Kind::SizeT:
5314 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5315 case Kind::SignedSizeT:
5316 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5317 case Kind::PtrdiffT:
5318 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5319 }
5320 llvm_unreachable("unexpected kind");
5321 };
5322 auto *New = new (*this, alignof(PredefinedSugarType))
5323 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5324 getCanonicalType(*this, static_cast<Kind>(KD)));
5325 Types.push_back(New);
5326 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5327 return QualType(New, 0);
5328}
5329
5331 NestedNameSpecifier Qualifier,
5332 const TypeDecl *Decl) const {
5333 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5334 return getTagType(Keyword, Qualifier, Tag,
5335 /*OwnsTag=*/false);
5336 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5337 return getTypedefType(Keyword, Qualifier, Typedef);
5338 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5339 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5340
5342 assert(!Qualifier);
5343 return QualType(Decl->TypeForDecl, 0);
5344}
5345
5347 if (auto *Tag = dyn_cast<TagDecl>(TD))
5348 return getCanonicalTagType(Tag);
5349 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5350 return getCanonicalType(TN->getUnderlyingType());
5351 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5353 assert(TD->TypeForDecl);
5354 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5355}
5356
5358 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5359 return getCanonicalTagType(TD);
5360 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5361 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5363 /*Qualifier=*/std::nullopt, TD);
5364 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5365 return getCanonicalUnresolvedUsingType(Using);
5366
5367 assert(Decl->TypeForDecl);
5368 return QualType(Decl->TypeForDecl, 0);
5369}
5370
5371/// getTypedefType - Return the unique reference to the type for the
5372/// specified typedef name decl.
5375 NestedNameSpecifier Qualifier,
5376 const TypedefNameDecl *Decl, QualType UnderlyingType,
5377 std::optional<bool> TypeMatchesDeclOrNone) const {
5378 if (!TypeMatchesDeclOrNone) {
5379 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5380 assert(!DeclUnderlyingType.isNull());
5381 if (UnderlyingType.isNull())
5382 UnderlyingType = DeclUnderlyingType;
5383 else
5384 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5385 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5386 } else {
5387 // FIXME: This is a workaround for a serialization cycle: assume the decl
5388 // underlying type is not available; don't touch it.
5389 assert(!UnderlyingType.isNull());
5390 }
5391
5392 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5393 *TypeMatchesDeclOrNone) {
5394 if (Decl->TypeForDecl)
5395 return QualType(Decl->TypeForDecl, 0);
5396
5397 auto *NewType = new (*this, alignof(TypedefType))
5398 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5399 !*TypeMatchesDeclOrNone);
5400
5401 Types.push_back(NewType);
5402 Decl->TypeForDecl = NewType;
5403 return QualType(NewType, 0);
5404 }
5405
5406 llvm::FoldingSetNodeID ID;
5407 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5408 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5409
5410 void *InsertPos = nullptr;
5411 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5412 TypedefTypes.FindNodeOrInsertPos(ID, InsertPos))
5413 return QualType(Placeholder->getType(), 0);
5414
5415 void *Mem =
5416 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5418 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5419 alignof(TypedefType));
5420 auto *NewType =
5421 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5422 UnderlyingType, !*TypeMatchesDeclOrNone);
5423 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5425 TypedefTypes.InsertNode(Placeholder, InsertPos);
5426 Types.push_back(NewType);
5427 return QualType(NewType, 0);
5428}
5429
5431 NestedNameSpecifier Qualifier,
5432 const UsingShadowDecl *D,
5433 QualType UnderlyingType) const {
5434 // FIXME: This is expensive to compute every time!
5435 if (UnderlyingType.isNull()) {
5436 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5437 UnderlyingType =
5440 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5441 }
5442
5443 llvm::FoldingSetNodeID ID;
5444 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5445
5446 void *InsertPos = nullptr;
5447 if (const UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5448 return QualType(T, 0);
5449
5450 assert(!UnderlyingType.hasLocalQualifiers());
5451
5452 assert(
5454 UnderlyingType));
5455
5456 void *Mem =
5457 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5458 alignof(UsingType));
5459 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5460 Types.push_back(T);
5461 UsingTypes.InsertNode(T, InsertPos);
5462 return QualType(T, 0);
5463}
5464
5465TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5466 NestedNameSpecifier Qualifier,
5467 const TagDecl *TD, bool OwnsTag,
5468 bool IsInjected,
5469 const Type *CanonicalType,
5470 bool WithFoldingSetNode) const {
5471 auto [TC, Size] = [&] {
5472 switch (TD->getDeclKind()) {
5473 case Decl::Enum:
5474 static_assert(alignof(EnumType) == alignof(TagType));
5475 return std::make_tuple(Type::Enum, sizeof(EnumType));
5476 case Decl::ClassTemplatePartialSpecialization:
5477 case Decl::ClassTemplateSpecialization:
5478 case Decl::CXXRecord:
5479 static_assert(alignof(RecordType) == alignof(TagType));
5480 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5481 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5482 return std::make_tuple(Type::InjectedClassName,
5483 sizeof(InjectedClassNameType));
5484 [[fallthrough]];
5485 case Decl::Record:
5486 return std::make_tuple(Type::Record, sizeof(RecordType));
5487 default:
5488 llvm_unreachable("unexpected decl kind");
5489 }
5490 }();
5491
5492 if (Qualifier) {
5493 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5494 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5495 sizeof(NestedNameSpecifier);
5496 }
5497 void *Mem;
5498 if (WithFoldingSetNode) {
5499 // FIXME: It would be more profitable to tail allocate the folding set node
5500 // from the type, instead of the other way around, due to the greater
5501 // alignment requirements of the type. But this makes it harder to deal with
5502 // the different type node sizes. This would require either uniquing from
5503 // different folding sets, or having the folding setaccept a
5504 // contextual parameter which is not fixed at construction.
5505 Mem = Allocate(
5506 sizeof(TagTypeFoldingSetPlaceholder) +
5507 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5508 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5509 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5510 Mem = T->getTagType();
5511 } else {
5512 Mem = Allocate(Size, alignof(TagType));
5513 }
5514
5515 auto *T = [&, TC = TC]() -> TagType * {
5516 switch (TC) {
5517 case Type::Enum: {
5518 assert(isa<EnumDecl>(TD));
5519 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5520 IsInjected, CanonicalType);
5521 assert(reinterpret_cast<void *>(T) ==
5522 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5523 "TagType must be the first base of EnumType");
5524 return T;
5525 }
5526 case Type::Record: {
5527 assert(isa<RecordDecl>(TD));
5528 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5529 IsInjected, CanonicalType);
5530 assert(reinterpret_cast<void *>(T) ==
5531 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5532 "TagType must be the first base of RecordType");
5533 return T;
5534 }
5535 case Type::InjectedClassName: {
5536 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5537 IsInjected, CanonicalType);
5538 assert(reinterpret_cast<void *>(T) ==
5539 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5540 "TagType must be the first base of InjectedClassNameType");
5541 return T;
5542 }
5543 default:
5544 llvm_unreachable("unexpected type class");
5545 }
5546 }();
5547 assert(T->getKeyword() == Keyword);
5548 assert(T->getQualifier() == Qualifier);
5549 assert(T->getDecl() == TD);
5550 assert(T->isInjected() == IsInjected);
5551 assert(T->isTagOwned() == OwnsTag);
5552 assert((T->isCanonicalUnqualified()
5553 ? QualType()
5554 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5555 Types.push_back(T);
5556 return T;
5557}
5558
5559static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5560 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5561 RD && RD->isInjectedClassName())
5562 return cast<TagDecl>(RD->getDeclContext());
5563 return TD;
5564}
5565
5568 if (TD->TypeForDecl)
5569 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5570
5571 const Type *CanonicalType = getTagTypeInternal(
5573 /*Qualifier=*/std::nullopt, TD,
5574 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5575 /*WithFoldingSetNode=*/false);
5576 TD->TypeForDecl = CanonicalType;
5577 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5578}
5579
5581 NestedNameSpecifier Qualifier,
5582 const TagDecl *TD, bool OwnsTag) const {
5583
5584 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5585 bool IsInjected = TD != NonInjectedTD;
5586
5587 ElaboratedTypeKeyword PreferredKeyword =
5590 NonInjectedTD->getTagKind());
5591
5592 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5593 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5594 return QualType(T, 0);
5595
5596 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5597 const Type *T =
5598 getTagTypeInternal(Keyword,
5599 /*Qualifier=*/std::nullopt, NonInjectedTD,
5600 /*OwnsTag=*/false, IsInjected, CanonicalType,
5601 /*WithFoldingSetNode=*/false);
5602 TD->TypeForDecl = T;
5603 return QualType(T, 0);
5604 }
5605
5606 llvm::FoldingSetNodeID ID;
5607 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5608 OwnsTag, IsInjected);
5609
5610 void *InsertPos = nullptr;
5611 if (TagTypeFoldingSetPlaceholder *T =
5612 TagTypes.FindNodeOrInsertPos(ID, InsertPos))
5613 return QualType(T->getTagType(), 0);
5614
5615 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5616 TagType *T =
5617 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5618 CanonicalType, /*WithFoldingSetNode=*/true);
5619 TagTypes.InsertNode(TagTypeFoldingSetPlaceholder::fromTagType(T), InsertPos);
5620 return QualType(T, 0);
5621}
5622
5623bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5624 unsigned NumPositiveBits,
5625 QualType &BestType,
5626 QualType &BestPromotionType) {
5627 unsigned IntWidth = Target->getIntWidth();
5628 unsigned CharWidth = Target->getCharWidth();
5629 unsigned ShortWidth = Target->getShortWidth();
5630 bool EnumTooLarge = false;
5631 unsigned BestWidth;
5632 if (NumNegativeBits) {
5633 // If there is a negative value, figure out the smallest integer type (of
5634 // int/long/longlong) that fits.
5635 // If it's packed, check also if it fits a char or a short.
5636 if (IsPacked && NumNegativeBits <= CharWidth &&
5637 NumPositiveBits < CharWidth) {
5638 BestType = SignedCharTy;
5639 BestWidth = CharWidth;
5640 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5641 NumPositiveBits < ShortWidth) {
5642 BestType = ShortTy;
5643 BestWidth = ShortWidth;
5644 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5645 BestType = IntTy;
5646 BestWidth = IntWidth;
5647 } else {
5648 BestWidth = Target->getLongWidth();
5649
5650 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5651 BestType = LongTy;
5652 } else {
5653 BestWidth = Target->getLongLongWidth();
5654
5655 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5656 EnumTooLarge = true;
5657 BestType = LongLongTy;
5658 }
5659 }
5660 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5661 } else {
5662 // If there is no negative value, figure out the smallest type that fits
5663 // all of the enumerator values.
5664 // If it's packed, check also if it fits a char or a short.
5665 if (IsPacked && NumPositiveBits <= CharWidth) {
5666 BestType = UnsignedCharTy;
5667 BestPromotionType = IntTy;
5668 BestWidth = CharWidth;
5669 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5670 BestType = UnsignedShortTy;
5671 BestPromotionType = IntTy;
5672 BestWidth = ShortWidth;
5673 } else if (NumPositiveBits <= IntWidth) {
5674 BestType = UnsignedIntTy;
5675 BestWidth = IntWidth;
5676 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5678 : IntTy;
5679 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5680 BestType = UnsignedLongTy;
5681 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5683 : LongTy;
5684 } else {
5685 BestWidth = Target->getLongLongWidth();
5686 if (NumPositiveBits > BestWidth) {
5687 // This can happen with bit-precise integer types, but those are not
5688 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5689 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5690 // a 128-bit integer, we should consider doing the same.
5691 EnumTooLarge = true;
5692 }
5693 BestType = UnsignedLongLongTy;
5694 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5696 : LongLongTy;
5697 }
5698 }
5699 return EnumTooLarge;
5700}
5701
5703 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5704 "Integral type required!");
5705 unsigned BitWidth = getIntWidth(T);
5706
5707 if (Value.isUnsigned() || Value.isNonNegative()) {
5708 if (T->isSignedIntegerOrEnumerationType())
5709 --BitWidth;
5710 return Value.getActiveBits() <= BitWidth;
5711 }
5712 return Value.getSignificantBits() <= BitWidth;
5713}
5714
5715UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5717 const UnresolvedUsingTypenameDecl *D, void *InsertPos,
5718 const Type *CanonicalType) const {
5719 void *Mem = Allocate(
5720 UnresolvedUsingType::totalSizeToAlloc<
5722 !!InsertPos, !!Qualifier),
5723 alignof(UnresolvedUsingType));
5724 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5725 if (InsertPos) {
5726 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5728 TypedefTypes.InsertNode(Placeholder, InsertPos);
5729 }
5730 Types.push_back(T);
5731 return T;
5732}
5733
5735 const UnresolvedUsingTypenameDecl *D) const {
5736 D = D->getCanonicalDecl();
5737 if (D->TypeForDecl)
5738 return D->TypeForDecl->getCanonicalTypeUnqualified();
5739
5740 const Type *CanonicalType = getUnresolvedUsingTypeInternal(
5742 /*Qualifier=*/std::nullopt, D,
5743 /*InsertPos=*/nullptr, /*CanonicalType=*/nullptr);
5744 D->TypeForDecl = CanonicalType;
5745 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5746}
5747
5750 NestedNameSpecifier Qualifier,
5751 const UnresolvedUsingTypenameDecl *D) const {
5752 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5753 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5754 return QualType(T, 0);
5755
5756 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5757 const Type *T =
5758 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5759 /*Qualifier=*/std::nullopt, D,
5760 /*InsertPos=*/nullptr, CanonicalType);
5761 D->TypeForDecl = T;
5762 return QualType(T, 0);
5763 }
5764
5765 llvm::FoldingSetNodeID ID;
5766 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5767
5768 void *InsertPos = nullptr;
5770 UnresolvedUsingTypes.FindNodeOrInsertPos(ID, InsertPos))
5771 return QualType(Placeholder->getType(), 0);
5772 assert(InsertPos);
5773
5774 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5775 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D,
5776 InsertPos, CanonicalType);
5777 return QualType(T, 0);
5778}
5779
5781 QualType modifiedType,
5782 QualType equivalentType,
5783 const Attr *attr) const {
5784 llvm::FoldingSetNodeID id;
5785 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5786 attr);
5787
5788 void *insertPos = nullptr;
5789 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
5790 if (type) return QualType(type, 0);
5791
5792 assert(!attr || attr->getKind() == attrKind);
5793
5794 QualType canon = getCanonicalType(equivalentType);
5795 type = new (*this, alignof(AttributedType))
5796 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5797
5798 Types.push_back(type);
5799 AttributedTypes.InsertNode(type, insertPos);
5800
5801 return QualType(type, 0);
5802}
5803
5805 QualType equivalentType) const {
5806 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5807}
5808
5810 QualType modifiedType,
5811 QualType equivalentType) const {
5812 switch (nullability) {
5814 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5815
5817 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5818
5820 return getAttributedType(attr::TypeNullableResult, modifiedType,
5821 equivalentType);
5822
5824 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5825 equivalentType);
5826 }
5827
5828 llvm_unreachable("Unknown nullability kind");
5829}
5830
5831QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5832 QualType Wrapped) const {
5833 llvm::FoldingSetNodeID ID;
5834 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5835
5836 void *InsertPos = nullptr;
5837 BTFTagAttributedType *Ty =
5838 BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
5839 if (Ty)
5840 return QualType(Ty, 0);
5841
5842 QualType Canon = getCanonicalType(Wrapped);
5843 Ty = new (*this, alignof(BTFTagAttributedType))
5844 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5845
5846 Types.push_back(Ty);
5847 BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
5848
5849 return QualType(Ty, 0);
5850}
5851
5853 QualType Underlying) const {
5854 const IdentifierInfo *II = Attr->getBehaviorKind();
5855 StringRef IdentName = II->getName();
5856 OverflowBehaviorType::OverflowBehaviorKind Kind;
5857 if (IdentName == "wrap") {
5858 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5859 } else if (IdentName == "trap") {
5860 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5861 } else {
5862 return Underlying;
5863 }
5864
5865 return getOverflowBehaviorType(Kind, Underlying);
5866}
5867
5869 OverflowBehaviorType::OverflowBehaviorKind Kind,
5870 QualType Underlying) const {
5871 assert(!Underlying->isOverflowBehaviorType() &&
5872 "Cannot have underlying types that are themselves OBTs");
5873 llvm::FoldingSetNodeID ID;
5874 OverflowBehaviorType::Profile(ID, Underlying, Kind);
5875 void *InsertPos = nullptr;
5876
5877 if (OverflowBehaviorType *OBT =
5878 OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos)) {
5879 return QualType(OBT, 0);
5880 }
5881
5882 QualType Canonical;
5883 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5884 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5885 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5886 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5887 assert(!OverflowBehaviorTypes.FindNodeOrInsertPos(ID, InsertPos) &&
5888 "Shouldn't be in the map");
5889 }
5890
5891 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5892 OverflowBehaviorType(Canonical, Underlying, Kind);
5893
5894 Types.push_back(Ty);
5895 OverflowBehaviorTypes.InsertNode(Ty, InsertPos);
5896 return QualType(Ty, 0);
5897}
5898
5900 QualType Wrapped, QualType Contained,
5901 const HLSLAttributedResourceType::Attributes &Attrs) {
5902
5903 llvm::FoldingSetNodeID ID;
5904 HLSLAttributedResourceType::Profile(ID, Wrapped, Contained, Attrs);
5905
5906 void *InsertPos = nullptr;
5907 HLSLAttributedResourceType *Ty =
5908 HLSLAttributedResourceTypes.FindNodeOrInsertPos(ID, InsertPos);
5909 if (Ty)
5910 return QualType(Ty, 0);
5911
5912 Ty = new (*this, alignof(HLSLAttributedResourceType))
5913 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5914
5915 Types.push_back(Ty);
5916 HLSLAttributedResourceTypes.InsertNode(Ty, InsertPos);
5917
5918 return QualType(Ty, 0);
5919}
5920
5921QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5922 uint32_t Alignment,
5923 ArrayRef<SpirvOperand> Operands) {
5924 llvm::FoldingSetNodeID ID;
5925 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5926
5927 void *InsertPos = nullptr;
5928 HLSLInlineSpirvType *Ty =
5929 HLSLInlineSpirvTypes.FindNodeOrInsertPos(ID, InsertPos);
5930 if (Ty)
5931 return QualType(Ty, 0);
5932
5933 void *Mem = Allocate(
5934 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5935 alignof(HLSLInlineSpirvType));
5936
5937 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5938
5939 Types.push_back(Ty);
5940 HLSLInlineSpirvTypes.InsertNode(Ty, InsertPos);
5941
5942 return QualType(Ty, 0);
5943}
5944
5945/// Retrieve a substitution-result type.
5947 Decl *AssociatedDecl,
5948 unsigned Index,
5950 bool Final) const {
5951 llvm::FoldingSetNodeID ID;
5952 SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
5953 PackIndex, Final);
5954 void *InsertPos = nullptr;
5955 SubstTemplateTypeParmType *SubstParm =
5956 SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
5957
5958 if (!SubstParm) {
5959 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5960 !Replacement.isCanonical()),
5961 alignof(SubstTemplateTypeParmType));
5962 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
5963 Index, PackIndex, Final);
5964 Types.push_back(SubstParm);
5965 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
5966 }
5967
5968 return QualType(SubstParm, 0);
5969}
5970
5973 unsigned Index, bool Final,
5974 const TemplateArgument &ArgPack) {
5975#ifndef NDEBUG
5976 for (const auto &P : ArgPack.pack_elements())
5977 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
5978#endif
5979
5980 llvm::FoldingSetNodeID ID;
5981 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
5982 ArgPack);
5983 void *InsertPos = nullptr;
5984 if (SubstTemplateTypeParmPackType *SubstParm =
5985 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
5986 return QualType(SubstParm, 0);
5987
5988 QualType Canon;
5989 {
5990 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
5991 if (!AssociatedDecl->isCanonicalDecl() ||
5992 !CanonArgPack.structurallyEquals(ArgPack)) {
5994 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
5995 [[maybe_unused]] const auto *Nothing =
5996 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
5997 assert(!Nothing);
5998 }
5999 }
6000
6001 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6002 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6003 ArgPack);
6004 Types.push_back(SubstParm);
6005 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
6006 return QualType(SubstParm, 0);
6007}
6008
6011 assert(llvm::all_of(ArgPack.pack_elements(),
6012 [](const auto &P) {
6013 return P.getKind() == TemplateArgument::Type;
6014 }) &&
6015 "Pack contains a non-type");
6016
6017 llvm::FoldingSetNodeID ID;
6018 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6019
6020 void *InsertPos = nullptr;
6021 if (auto *T =
6022 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos))
6023 return QualType(T, 0);
6024
6025 QualType Canon;
6026 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6027 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6028 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6029 // Refresh InsertPos, in case the recursive call above caused rehashing,
6030 // which would invalidate the bucket pointer.
6031 [[maybe_unused]] const auto *Nothing =
6032 SubstBuiltinTemplatePackTypes.FindNodeOrInsertPos(ID, InsertPos);
6033 assert(!Nothing);
6034 }
6035
6036 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6037 SubstBuiltinTemplatePackType(Canon, ArgPack);
6038 Types.push_back(PackType);
6039 SubstBuiltinTemplatePackTypes.InsertNode(PackType, InsertPos);
6040 return QualType(PackType, 0);
6041}
6042
6043/// Retrieve the template type parameter type for a template
6044/// parameter or parameter pack with the given depth, index, and (optionally)
6045/// name.
6047ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6048 TemplateTypeParmDecl *TTPDecl) const {
6049 assert(Depth >= 0 && "Depth must be non-negative");
6050 assert(Index >= 0 && "Index must be non-negative");
6051
6052 llvm::FoldingSetNodeID ID;
6053 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
6054 void *InsertPos = nullptr;
6055 TemplateTypeParmType *TypeParm
6056 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6057
6058 if (TypeParm)
6059 return QualType(TypeParm, 0);
6060
6061 if (TTPDecl) {
6062 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6063 TypeParm = new (*this, alignof(TemplateTypeParmType))
6064 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6065
6066 TemplateTypeParmType *TypeCheck
6067 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
6068 assert(!TypeCheck && "Template type parameter canonical type broken");
6069 (void)TypeCheck;
6070 } else
6071 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6072 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6073
6074 Types.push_back(TypeParm);
6075 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
6076
6077 return QualType(TypeParm, 0);
6078}
6079
6082 switch (Keyword) {
6083 // These are just themselves.
6089 return Keyword;
6090
6091 // These are equivalent.
6094
6095 // These are functionally equivalent, so relying on their equivalence is
6096 // IFNDR. By making them equivalent, we disallow overloading, which at least
6097 // can produce a diagnostic.
6100 }
6101 llvm_unreachable("unexpected keyword kind");
6102}
6103
6105 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6106 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6107 TemplateName Name, SourceLocation NameLoc,
6108 const TemplateArgumentListInfo &SpecifiedArgs,
6109 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6111 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6112
6115 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6116 SpecifiedArgs);
6117 return TSI;
6118}
6119
6122 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6123 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6124 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6125 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6126 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6127 SpecifiedArgVec.push_back(Arg.getArgument());
6128
6129 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6130 CanonicalArgs, Underlying);
6131}
6132
6133[[maybe_unused]] static bool
6135 for (const TemplateArgument &Arg : Args)
6136 if (Arg.isPackExpansion())
6137 return true;
6138 return false;
6139}
6140
6143 ArrayRef<TemplateArgument> Args) const {
6144 assert(Template ==
6145 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6147 Template.getAsDependentTemplateName()));
6148#ifndef NDEBUG
6149 for (const auto &Arg : Args)
6150 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6151#endif
6152
6153 llvm::FoldingSetNodeID ID;
6154 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6155 *this);
6156 void *InsertPos = nullptr;
6157 if (auto *T = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6158 return QualType(T, 0);
6159
6160 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6161 sizeof(TemplateArgument) * Args.size(),
6162 alignof(TemplateSpecializationType));
6163 auto *Spec =
6164 new (Mem) TemplateSpecializationType(Keyword, Template,
6165 /*IsAlias=*/false, Args, QualType());
6166 assert(Spec->isDependentType() &&
6167 "canonical template specialization must be dependent");
6168 Types.push_back(Spec);
6169 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
6170 return QualType(Spec, 0);
6171}
6172
6175 ArrayRef<TemplateArgument> SpecifiedArgs,
6176 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6177 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6178 bool IsTypeAlias = TD && TD->isTypeAlias();
6179 if (Underlying.isNull()) {
6180 TemplateName CanonTemplate =
6181 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6182 ElaboratedTypeKeyword CanonKeyword =
6183 CanonTemplate.getAsDependentTemplateName()
6186 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6188 if (CanonicalArgs.empty()) {
6189 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6190 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6191 CanonicalArgs = CanonArgsVec;
6192 } else {
6193 NonCanonical |= !llvm::equal(
6194 SpecifiedArgs, CanonicalArgs,
6195 [](const TemplateArgument &A, const TemplateArgument &B) {
6196 return A.structurallyEquals(B);
6197 });
6198 }
6199
6200 // We can get here with an alias template when the specialization
6201 // contains a pack expansion that does not match up with a parameter
6202 // pack, or a builtin template which cannot be resolved due to dependency.
6203 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6204 hasAnyPackExpansions(CanonicalArgs)) &&
6205 "Caller must compute aliased type");
6206 IsTypeAlias = false;
6207
6209 CanonKeyword, CanonTemplate, CanonicalArgs);
6210 if (!NonCanonical)
6211 return Underlying;
6212 }
6213 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6214 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6215 (IsTypeAlias ? sizeof(QualType) : 0),
6216 alignof(TemplateSpecializationType));
6217 auto *Spec = new (Mem) TemplateSpecializationType(
6218 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6219 Types.push_back(Spec);
6220 return QualType(Spec, 0);
6221}
6222
6225 llvm::FoldingSetNodeID ID;
6226 ParenType::Profile(ID, InnerType);
6227
6228 void *InsertPos = nullptr;
6229 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6230 if (T)
6231 return QualType(T, 0);
6232
6233 QualType Canon = InnerType;
6234 if (!Canon.isCanonical()) {
6235 Canon = getCanonicalType(InnerType);
6236 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
6237 assert(!CheckT && "Paren canonical type broken");
6238 (void)CheckT;
6239 }
6240
6241 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6242 Types.push_back(T);
6243 ParenTypes.InsertNode(T, InsertPos);
6244 return QualType(T, 0);
6245}
6246
6249 const IdentifierInfo *MacroII) const {
6250 QualType Canon = UnderlyingTy;
6251 if (!Canon.isCanonical())
6252 Canon = getCanonicalType(UnderlyingTy);
6253
6254 auto *newType = new (*this, alignof(MacroQualifiedType))
6255 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6256 Types.push_back(newType);
6257 return QualType(newType, 0);
6258}
6259
6262 const IdentifierInfo *Name) const {
6263 llvm::FoldingSetNodeID ID;
6264 DependentNameType::Profile(ID, Keyword, NNS, Name);
6265
6266 void *InsertPos = nullptr;
6267 if (DependentNameType *T =
6268 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos))
6269 return QualType(T, 0);
6270
6271 ElaboratedTypeKeyword CanonKeyword =
6273 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6274
6275 QualType Canon;
6276 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6277 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6278 [[maybe_unused]] DependentNameType *T =
6279 DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
6280 assert(!T && "broken canonicalization");
6281 assert(Canon.isCanonical());
6282 }
6283
6284 DependentNameType *T = new (*this, alignof(DependentNameType))
6285 DependentNameType(Keyword, NNS, Name, Canon);
6286 Types.push_back(T);
6287 DependentNameTypes.InsertNode(T, InsertPos);
6288 return QualType(T, 0);
6289}
6290
6292 TemplateArgument Arg;
6293 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6295 if (TTP->isParameterPack())
6296 ArgType = getPackExpansionType(ArgType, std::nullopt);
6297
6299 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6300 QualType T =
6301 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6302 // For class NTTPs, ensure we include the 'const' so the type matches that
6303 // of a real template argument.
6304 // FIXME: It would be more faithful to model this as something like an
6305 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6307 if (T->isRecordType()) {
6308 // C++ [temp.param]p8: An id-expression naming a non-type
6309 // template-parameter of class type T denotes a static storage duration
6310 // object of type const T.
6311 T.addConst();
6312 VK = VK_LValue;
6313 } else {
6314 VK = Expr::getValueKindForType(NTTP->getType());
6315 }
6316 Expr *E = new (*this)
6317 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6318 T, VK, NTTP->getLocation());
6319
6320 if (NTTP->isParameterPack())
6321 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6322 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6323 } else {
6324 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6326 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6327 TemplateName(TTP));
6328 if (TTP->isParameterPack())
6329 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6330 else
6331 Arg = TemplateArgument(Name);
6332 }
6333
6334 if (Param->isTemplateParameterPack())
6335 Arg =
6336 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6337
6338 return Arg;
6339}
6340
6342 UnsignedOrNone NumExpansions,
6343 bool ExpectPackInType) const {
6344 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6345 "Pack expansions must expand one or more parameter packs");
6346
6347 llvm::FoldingSetNodeID ID;
6348 PackExpansionType::Profile(ID, Pattern, NumExpansions);
6349
6350 void *InsertPos = nullptr;
6351 PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6352 if (T)
6353 return QualType(T, 0);
6354
6355 QualType Canon;
6356 if (!Pattern.isCanonical()) {
6357 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6358 /*ExpectPackInType=*/false);
6359
6360 // Find the insert position again, in case we inserted an element into
6361 // PackExpansionTypes and invalidated our insert position.
6362 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
6363 }
6364
6365 T = new (*this, alignof(PackExpansionType))
6366 PackExpansionType(Pattern, Canon, NumExpansions);
6367 Types.push_back(T);
6368 PackExpansionTypes.InsertNode(T, InsertPos);
6369 return QualType(T, 0);
6370}
6371
6372/// CmpProtocolNames - Comparison predicate for sorting protocols
6373/// alphabetically.
6374static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6375 ObjCProtocolDecl *const *RHS) {
6376 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6377}
6378
6380 if (Protocols.empty()) return true;
6381
6382 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6383 return false;
6384
6385 for (unsigned i = 1; i != Protocols.size(); ++i)
6386 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6387 Protocols[i]->getCanonicalDecl() != Protocols[i])
6388 return false;
6389 return true;
6390}
6391
6392static void
6394 // Sort protocols, keyed by name.
6395 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6396
6397 // Canonicalize.
6398 for (ObjCProtocolDecl *&P : Protocols)
6399 P = P->getCanonicalDecl();
6400
6401 // Remove duplicates.
6402 auto ProtocolsEnd = llvm::unique(Protocols);
6403 Protocols.erase(ProtocolsEnd, Protocols.end());
6404}
6405
6407 ObjCProtocolDecl * const *Protocols,
6408 unsigned NumProtocols) const {
6409 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6410 /*isKindOf=*/false);
6411}
6412
6414 QualType baseType,
6415 ArrayRef<QualType> typeArgs,
6417 bool isKindOf) const {
6418 // If the base type is an interface and there aren't any protocols or
6419 // type arguments to add, then the interface type will do just fine.
6420 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6421 isa<ObjCInterfaceType>(baseType))
6422 return baseType;
6423
6424 // Look in the folding set for an existing type.
6425 llvm::FoldingSetNodeID ID;
6426 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6427 void *InsertPos = nullptr;
6428 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
6429 return QualType(QT, 0);
6430
6431 // Determine the type arguments to be used for canonicalization,
6432 // which may be explicitly specified here or written on the base
6433 // type.
6434 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6435 if (effectiveTypeArgs.empty()) {
6436 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6437 effectiveTypeArgs = baseObject->getTypeArgs();
6438 }
6439
6440 // Build the canonical type, which has the canonical base type and a
6441 // sorted-and-uniqued list of protocols and the type arguments
6442 // canonicalized.
6443 QualType canonical;
6444 bool typeArgsAreCanonical = llvm::all_of(
6445 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6446 bool protocolsSorted = areSortedAndUniqued(protocols);
6447 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6448 // Determine the canonical type arguments.
6449 ArrayRef<QualType> canonTypeArgs;
6450 SmallVector<QualType, 4> canonTypeArgsVec;
6451 if (!typeArgsAreCanonical) {
6452 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6453 for (auto typeArg : effectiveTypeArgs)
6454 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6455 canonTypeArgs = canonTypeArgsVec;
6456 } else {
6457 canonTypeArgs = effectiveTypeArgs;
6458 }
6459
6460 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6461 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6462 if (!protocolsSorted) {
6463 canonProtocolsVec.append(protocols.begin(), protocols.end());
6464 SortAndUniqueProtocols(canonProtocolsVec);
6465 canonProtocols = canonProtocolsVec;
6466 } else {
6467 canonProtocols = protocols;
6468 }
6469
6470 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6471 canonProtocols, isKindOf);
6472
6473 // Regenerate InsertPos.
6474 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
6475 }
6476
6477 unsigned size = sizeof(ObjCObjectTypeImpl);
6478 size += typeArgs.size() * sizeof(QualType);
6479 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6480 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6481 auto *T =
6482 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6483 isKindOf);
6484
6485 Types.push_back(T);
6486 ObjCObjectTypes.InsertNode(T, InsertPos);
6487 return QualType(T, 0);
6488}
6489
6490/// Apply Objective-C protocol qualifiers to the given type.
6491/// If this is for the canonical type of a type parameter, we can apply
6492/// protocol qualifiers on the ObjCObjectPointerType.
6495 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6496 bool allowOnPointerType) const {
6497 hasError = false;
6498
6499 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6500 return getObjCTypeParamType(objT->getDecl(), protocols);
6501 }
6502
6503 // Apply protocol qualifiers to ObjCObjectPointerType.
6504 if (allowOnPointerType) {
6505 if (const auto *objPtr =
6506 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6507 const ObjCObjectType *objT = objPtr->getObjectType();
6508 // Merge protocol lists and construct ObjCObjectType.
6510 protocolsVec.append(objT->qual_begin(),
6511 objT->qual_end());
6512 protocolsVec.append(protocols.begin(), protocols.end());
6513 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6515 objT->getBaseType(),
6516 objT->getTypeArgsAsWritten(),
6517 protocols,
6518 objT->isKindOfTypeAsWritten());
6520 }
6521 }
6522
6523 // Apply protocol qualifiers to ObjCObjectType.
6524 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6525 // FIXME: Check for protocols to which the class type is already
6526 // known to conform.
6527
6528 return getObjCObjectType(objT->getBaseType(),
6529 objT->getTypeArgsAsWritten(),
6530 protocols,
6531 objT->isKindOfTypeAsWritten());
6532 }
6533
6534 // If the canonical type is ObjCObjectType, ...
6535 if (type->isObjCObjectType()) {
6536 // Silently overwrite any existing protocol qualifiers.
6537 // TODO: determine whether that's the right thing to do.
6538
6539 // FIXME: Check for protocols to which the class type is already
6540 // known to conform.
6541 return getObjCObjectType(type, {}, protocols, false);
6542 }
6543
6544 // id<protocol-list>
6545 if (type->isObjCIdType()) {
6546 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6547 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6548 objPtr->isKindOfType());
6550 }
6551
6552 // Class<protocol-list>
6553 if (type->isObjCClassType()) {
6554 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6555 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6556 objPtr->isKindOfType());
6558 }
6559
6560 hasError = true;
6561 return type;
6562}
6563
6566 ArrayRef<ObjCProtocolDecl *> protocols) const {
6567 // Look in the folding set for an existing type.
6568 llvm::FoldingSetNodeID ID;
6569 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
6570 void *InsertPos = nullptr;
6571 if (ObjCTypeParamType *TypeParam =
6572 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
6573 return QualType(TypeParam, 0);
6574
6575 // We canonicalize to the underlying type.
6576 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6577 if (!protocols.empty()) {
6578 // Apply the protocol qualifers.
6579 bool hasError;
6581 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6582 assert(!hasError && "Error when apply protocol qualifier to bound type");
6583 }
6584
6585 unsigned size = sizeof(ObjCTypeParamType);
6586 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6587 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6588 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6589
6590 Types.push_back(newType);
6591 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
6592 return QualType(newType, 0);
6593}
6594
6596 ObjCTypeParamDecl *New) const {
6597 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6598 // Update TypeForDecl after updating TypeSourceInfo.
6599 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6601 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6602 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6603 New->TypeForDecl = UpdatedTy.getTypePtr();
6604}
6605
6606/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6607/// protocol list adopt all protocols in QT's qualified-id protocol
6608/// list.
6610 ObjCInterfaceDecl *IC) {
6611 if (!QT->isObjCQualifiedIdType())
6612 return false;
6613
6614 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6615 // If both the right and left sides have qualifiers.
6616 for (auto *Proto : OPT->quals()) {
6617 if (!IC->ClassImplementsProtocol(Proto, false))
6618 return false;
6619 }
6620 return true;
6621 }
6622 return false;
6623}
6624
6625/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6626/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6627/// of protocols.
6629 ObjCInterfaceDecl *IDecl) {
6630 if (!QT->isObjCQualifiedIdType())
6631 return false;
6632 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6633 if (!OPT)
6634 return false;
6635 if (!IDecl->hasDefinition())
6636 return false;
6638 CollectInheritedProtocols(IDecl, InheritedProtocols);
6639 if (InheritedProtocols.empty())
6640 return false;
6641 // Check that if every protocol in list of id<plist> conforms to a protocol
6642 // of IDecl's, then bridge casting is ok.
6643 bool Conforms = false;
6644 for (auto *Proto : OPT->quals()) {
6645 Conforms = false;
6646 for (auto *PI : InheritedProtocols) {
6647 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6648 Conforms = true;
6649 break;
6650 }
6651 }
6652 if (!Conforms)
6653 break;
6654 }
6655 if (Conforms)
6656 return true;
6657
6658 for (auto *PI : InheritedProtocols) {
6659 // If both the right and left sides have qualifiers.
6660 bool Adopts = false;
6661 for (auto *Proto : OPT->quals()) {
6662 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6663 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6664 break;
6665 }
6666 if (!Adopts)
6667 return false;
6668 }
6669 return true;
6670}
6671
6672/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6673/// the given object type.
6675 llvm::FoldingSetNodeID ID;
6676 ObjCObjectPointerType::Profile(ID, ObjectT);
6677
6678 void *InsertPos = nullptr;
6679 if (ObjCObjectPointerType *QT =
6680 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
6681 return QualType(QT, 0);
6682
6683 // Find the canonical object type.
6684 QualType Canonical;
6685 if (!ObjectT.isCanonical()) {
6686 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6687
6688 // Regenerate InsertPos.
6689 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
6690 }
6691
6692 // No match.
6693 void *Mem =
6695 auto *QType =
6696 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6697
6698 Types.push_back(QType);
6699 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
6700 return QualType(QType, 0);
6701}
6702
6703/// getObjCInterfaceType - Return the unique reference to the type for the
6704/// specified ObjC interface decl. The list of protocols is optional.
6706 ObjCInterfaceDecl *PrevDecl) const {
6707 if (Decl->TypeForDecl)
6708 return QualType(Decl->TypeForDecl, 0);
6709
6710 if (PrevDecl) {
6711 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6712 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6713 return QualType(PrevDecl->TypeForDecl, 0);
6714 }
6715
6716 // Prefer the definition, if there is one.
6717 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6718 Decl = Def;
6719
6720 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6721 auto *T = new (Mem) ObjCInterfaceType(Decl);
6722 Decl->TypeForDecl = T;
6723 Types.push_back(T);
6724 return QualType(T, 0);
6725}
6726
6727/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6728/// TypeOfExprType AST's (since expression's are never shared). For example,
6729/// multiple declarations that refer to "typeof(x)" all contain different
6730/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6731/// on canonical type's (which are always unique).
6733 TypeOfExprType *toe;
6734 if (tofExpr->isTypeDependent()) {
6735 llvm::FoldingSetNodeID ID;
6736 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6737 Kind == TypeOfKind::Unqualified);
6738
6739 void *InsertPos = nullptr;
6741 DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
6742 if (Canon) {
6743 // We already have a "canonical" version of an identical, dependent
6744 // typeof(expr) type. Use that as our canonical type.
6745 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6746 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6747 } else {
6748 // Build a new, canonical typeof(expr) type.
6749 Canon = new (*this, alignof(DependentTypeOfExprType))
6750 DependentTypeOfExprType(*this, tofExpr, Kind);
6751 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
6752 toe = Canon;
6753 }
6754 } else {
6755 QualType Canonical = getCanonicalType(tofExpr->getType());
6756 toe = new (*this, alignof(TypeOfExprType))
6757 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6758 }
6759 Types.push_back(toe);
6760 return QualType(toe, 0);
6761}
6762
6763/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6764/// TypeOfType nodes. The only motivation to unique these nodes would be
6765/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6766/// an issue. This doesn't affect the type checker, since it operates
6767/// on canonical types (which are always unique).
6769 QualType Canonical = getCanonicalType(tofType);
6770 auto *tot = new (*this, alignof(TypeOfType))
6771 TypeOfType(*this, tofType, Canonical, Kind);
6772 Types.push_back(tot);
6773 return QualType(tot, 0);
6774}
6775
6776/// getReferenceQualifiedType - Given an expr, will return the type for
6777/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6778/// and class member access into account.
6780 // C++11 [dcl.type.simple]p4:
6781 // [...]
6782 QualType T = E->getType();
6783 switch (E->getValueKind()) {
6784 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6785 // type of e;
6786 case VK_XValue:
6787 return getRValueReferenceType(T);
6788 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6789 // type of e;
6790 case VK_LValue:
6791 return getLValueReferenceType(T);
6792 // - otherwise, decltype(e) is the type of e.
6793 case VK_PRValue:
6794 return T;
6795 }
6796 llvm_unreachable("Unknown value kind");
6797}
6798
6799/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6800/// nodes. This would never be helpful, since each such type has its own
6801/// expression, and would not give a significant memory saving, since there
6802/// is an Expr tree under each such type.
6804 // C++11 [temp.type]p2:
6805 // If an expression e involves a template parameter, decltype(e) denotes a
6806 // unique dependent type. Two such decltype-specifiers refer to the same
6807 // type only if their expressions are equivalent (14.5.6.1).
6808 QualType CanonType;
6809 if (!E->isInstantiationDependent()) {
6810 CanonType = getCanonicalType(UnderlyingType);
6811 } else if (!UnderlyingType.isNull()) {
6812 CanonType = getDecltypeType(E, QualType());
6813 } else {
6814 llvm::FoldingSetNodeID ID;
6815 DependentDecltypeType::Profile(ID, *this, E);
6816
6817 void *InsertPos = nullptr;
6818 if (DependentDecltypeType *Canon =
6819 DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos))
6820 return QualType(Canon, 0);
6821
6822 // Build a new, canonical decltype(expr) type.
6823 auto *DT =
6824 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6825 DependentDecltypeTypes.InsertNode(DT, InsertPos);
6826 Types.push_back(DT);
6827 return QualType(DT, 0);
6828 }
6829 auto *DT = new (*this, alignof(DecltypeType))
6830 DecltypeType(E, UnderlyingType, CanonType);
6831 Types.push_back(DT);
6832 return QualType(DT, 0);
6833}
6834
6836 bool FullySubstituted,
6837 ArrayRef<QualType> Expansions,
6838 UnsignedOrNone Index) const {
6839 QualType Canonical;
6840 if (FullySubstituted && Index) {
6841 Canonical = getCanonicalType(Expansions[*Index]);
6842 } else {
6843 llvm::FoldingSetNodeID ID;
6844 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6845 FullySubstituted, Expansions);
6846 void *InsertPos = nullptr;
6847 PackIndexingType *Canon =
6848 DependentPackIndexingTypes.FindNodeOrInsertPos(ID, InsertPos);
6849 if (!Canon) {
6850 void *Mem = Allocate(
6851 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6853 Canon =
6854 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6855 IndexExpr, FullySubstituted, Expansions);
6856 DependentPackIndexingTypes.InsertNode(Canon, InsertPos);
6857 }
6858 Canonical = QualType(Canon, 0);
6859 }
6860
6861 void *Mem =
6862 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6864 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6865 FullySubstituted, Expansions);
6866 Types.push_back(T);
6867 return QualType(T, 0);
6868}
6869
6870/// getUnaryTransformationType - We don't unique these, since the memory
6871/// savings are minimal and these are rare.
6874 UnaryTransformType::UTTKind Kind) const {
6875
6876 llvm::FoldingSetNodeID ID;
6877 UnaryTransformType::Profile(ID, BaseType, UnderlyingType, Kind);
6878
6879 void *InsertPos = nullptr;
6880 if (UnaryTransformType *UT =
6881 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos))
6882 return QualType(UT, 0);
6883
6884 QualType CanonType;
6885 if (!BaseType->isDependentType()) {
6886 CanonType = UnderlyingType.getCanonicalType();
6887 } else {
6888 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6889 UnderlyingType = QualType();
6890 if (QualType CanonBase = BaseType.getCanonicalType();
6891 BaseType != CanonBase) {
6892 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6893 assert(CanonType.isCanonical());
6894
6895 // Find the insertion position again.
6896 [[maybe_unused]] UnaryTransformType *UT =
6897 UnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
6898 assert(!UT && "broken canonicalization");
6899 }
6900 }
6901
6902 auto *UT = new (*this, alignof(UnaryTransformType))
6903 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6904 UnaryTransformTypes.InsertNode(UT, InsertPos);
6905 Types.push_back(UT);
6906 return QualType(UT, 0);
6907}
6908
6909/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6910/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6911/// canonical deduced-but-dependent 'auto' type.
6915 TemplateDecl *TypeConstraintConcept,
6916 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6918 !TypeConstraintConcept) {
6919 assert(DeducedAsType.isNull() && "");
6920 assert(TypeConstraintArgs.empty() && "");
6921 return getAutoDeductType();
6922 }
6923
6924 // Look in the folding set for an existing type.
6925 llvm::FoldingSetNodeID ID;
6926 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6927 TypeConstraintConcept, TypeConstraintArgs);
6928 if (auto const AT_iter = AutoTypes.find(ID); AT_iter != AutoTypes.end())
6929 return QualType(AT_iter->getSecond(), 0);
6930
6931 if (DK == DeducedKind::Deduced) {
6932 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6933 } else {
6934 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6935 if (TypeConstraintConcept) {
6936 bool AnyNonCanonArgs = false;
6937 auto *CanonicalConcept =
6938 cast<TemplateDecl>(TypeConstraintConcept->getCanonicalDecl());
6939 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6940 *this, TypeConstraintArgs, AnyNonCanonArgs);
6941 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6942 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6943 CanonicalConceptArgs);
6944 }
6945 }
6946
6947 void *Mem = Allocate(sizeof(AutoType) +
6948 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6949 alignof(AutoType));
6950 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6951 TypeConstraintConcept, TypeConstraintArgs);
6952#ifndef NDEBUG
6953 llvm::FoldingSetNodeID InsertedID;
6954 AT->Profile(InsertedID, *this);
6955 assert(InsertedID == ID && "ID does not match");
6956#endif
6957 Types.push_back(AT);
6958 AutoTypes.try_emplace(ID, AT);
6959 return QualType(AT, 0);
6960}
6961
6963 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6964
6965 // Remove a type-constraint from a top-level auto or decltype(auto).
6966 if (auto *AT = CanonT->getAs<AutoType>()) {
6967 if (!AT->isConstrained())
6968 return T;
6969 return getQualifiedType(
6970 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6971 T.getQualifiers());
6972 }
6973
6974 // FIXME: We only support constrained auto at the top level in the type of a
6975 // non-type template parameter at the moment. Once we lift that restriction,
6976 // we'll need to recursively build types containing auto here.
6977 assert(!CanonT->getContainedAutoType() ||
6978 !CanonT->getContainedAutoType()->isConstrained());
6979 return T;
6980}
6981
6982/// Return the uniqued reference to the deduced template specialization type
6983/// which has been deduced to the given type, or to the canonical undeduced
6984/// such type, or the canonical deduced-but-dependent such type.
6987 TemplateName Template) const {
6988 // Look in the folding set for an existing type.
6989 void *InsertPos = nullptr;
6990 llvm::FoldingSetNodeID ID;
6991 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
6992 Template);
6993 if (DeducedTemplateSpecializationType *DTST =
6994 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
6995 return QualType(DTST, 0);
6996
6997 if (DK == DeducedKind::Deduced) {
6998 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6999 } else {
7000 assert(DeducedAsType.isNull() && "deduced type must not be provided");
7001 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
7002 // FIXME: Can this be formed from a DependentTemplateName, such that the
7003 // keyword should be part of the canonical type?
7005 Template != CanonTemplateName) {
7007 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
7008 // Find the insertion position again.
7009 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
7010 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
7011 assert(!DTST && "broken canonicalization");
7012 }
7013 }
7014
7015 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7016 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7017
7018#ifndef NDEBUG
7019 llvm::FoldingSetNodeID TempID;
7020 DTST->Profile(TempID);
7021 assert(ID == TempID && "ID does not match");
7022#endif
7023 Types.push_back(DTST);
7024 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
7025 return QualType(DTST, 0);
7026}
7027
7028/// getAtomicType - Return the uniqued reference to the atomic type for
7029/// the given value type.
7031 // Unique pointers, to guarantee there is only one pointer of a particular
7032 // structure.
7033 llvm::FoldingSetNodeID ID;
7035
7036 void *InsertPos = nullptr;
7037 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
7038 return QualType(AT, 0);
7039
7040 // If the atomic value type isn't canonical, this won't be a canonical type
7041 // either, so fill in the canonical type field.
7042 QualType Canonical;
7043 if (!T.isCanonical()) {
7044 Canonical = getAtomicType(getCanonicalType(T));
7045
7046 // Get the new insert position for the node we care about.
7047 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
7048 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
7049 }
7050 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7051 Types.push_back(New);
7052 AtomicTypes.InsertNode(New, InsertPos);
7053 return QualType(New, 0);
7054}
7055
7056/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7058 if (AutoDeductTy.isNull())
7059 AutoDeductTy = QualType(new (*this, alignof(AutoType))
7060 AutoType(DeducedKind::Undeduced, QualType(),
7062 /*TypeConstraintConcept=*/nullptr,
7063 /*TypeConstraintArgs=*/{}),
7064 0);
7065 return AutoDeductTy;
7066}
7067
7068/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7070 if (AutoRRefDeductTy.isNull())
7072 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7073 return AutoRRefDeductTy;
7074}
7075
7076/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7077/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7078/// needs to agree with the definition in <stddef.h>.
7082
7084 return getFromTargetType(Target->getSizeType());
7085}
7086
7087/// Return the unique signed counterpart of the integer type
7088/// corresponding to size_t.
7092
7093/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7094/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7098
7099/// Return the unique unsigned counterpart of "ptrdiff_t"
7100/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7101/// in the definition of %tu format specifier.
7103 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7104}
7105
7106/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7108 return getFromTargetType(Target->getIntMaxType());
7109}
7110
7111/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7113 return getFromTargetType(Target->getUIntMaxType());
7114}
7115
7116/// getSignedWCharType - Return the type of "signed wchar_t".
7117/// Used when in C++, as a GCC extension.
7119 // FIXME: derive from "Target" ?
7120 return WCharTy;
7121}
7122
7123/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7124/// Used when in C++, as a GCC extension.
7126 // FIXME: derive from "Target" ?
7127 return UnsignedIntTy;
7128}
7129
7131 return getFromTargetType(Target->getIntPtrType());
7132}
7133
7137
7138/// Return the unique type for "pid_t" defined in
7139/// <sys/types.h>. We need this to compute the correct type for vfork().
7141 return getFromTargetType(Target->getProcessIDType());
7142}
7143
7144//===----------------------------------------------------------------------===//
7145// Type Operators
7146//===----------------------------------------------------------------------===//
7147
7149 // Push qualifiers into arrays, and then discard any remaining
7150 // qualifiers.
7151 T = getCanonicalType(T);
7153 const Type *Ty = T.getTypePtr();
7157 } else if (isa<ArrayType>(Ty)) {
7159 } else if (isa<FunctionType>(Ty)) {
7160 Result = getPointerType(QualType(Ty, 0));
7161 } else {
7162 Result = QualType(Ty, 0);
7163 }
7164
7166}
7167
7169 Qualifiers &quals) const {
7170 SplitQualType splitType = type.getSplitUnqualifiedType();
7171
7172 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7173 // the unqualified desugared type and then drops it on the floor.
7174 // We then have to strip that sugar back off with
7175 // getUnqualifiedDesugaredType(), which is silly.
7176 const auto *AT =
7177 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7178
7179 // If we don't have an array, just use the results in splitType.
7180 if (!AT) {
7181 quals = splitType.Quals;
7182 return QualType(splitType.Ty, 0);
7183 }
7184
7185 // Otherwise, recurse on the array's element type.
7186 QualType elementType = AT->getElementType();
7187 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7188
7189 // If that didn't change the element type, AT has no qualifiers, so we
7190 // can just use the results in splitType.
7191 if (elementType == unqualElementType) {
7192 assert(quals.empty()); // from the recursive call
7193 quals = splitType.Quals;
7194 return QualType(splitType.Ty, 0);
7195 }
7196
7197 // Otherwise, add in the qualifiers from the outermost type, then
7198 // build the type back up.
7199 quals.addConsistentQualifiers(splitType.Quals);
7200
7201 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7202 return getConstantArrayType(unqualElementType, CAT->getSize(),
7203 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7204 }
7205
7206 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7207 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7208 }
7209
7210 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7211 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7212 VAT->getSizeModifier(),
7213 VAT->getIndexTypeCVRQualifiers());
7214 }
7215
7216 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7217 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7218 DSAT->getSizeModifier(), 0);
7219}
7220
7221/// Attempt to unwrap two types that may both be array types with the same bound
7222/// (or both be array types of unknown bound) for the purpose of comparing the
7223/// cv-decomposition of two types per C++ [conv.qual].
7224///
7225/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7226/// C++20 [conv.qual], if permitted by the current language mode.
7228 bool AllowPiMismatch) const {
7229 while (true) {
7230 auto *AT1 = getAsArrayType(T1);
7231 if (!AT1)
7232 return;
7233
7234 auto *AT2 = getAsArrayType(T2);
7235 if (!AT2)
7236 return;
7237
7238 // If we don't have two array types with the same constant bound nor two
7239 // incomplete array types, we've unwrapped everything we can.
7240 // C++20 also permits one type to be a constant array type and the other
7241 // to be an incomplete array type.
7242 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7243 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7244 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7245 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7246 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7248 return;
7249 } else if (isa<IncompleteArrayType>(AT1)) {
7250 if (!(isa<IncompleteArrayType>(AT2) ||
7251 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7253 return;
7254 } else {
7255 return;
7256 }
7257
7258 T1 = AT1->getElementType();
7259 T2 = AT2->getElementType();
7260 }
7261}
7262
7263/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7264///
7265/// If T1 and T2 are both pointer types of the same kind, or both array types
7266/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7267/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7268///
7269/// This function will typically be called in a loop that successively
7270/// "unwraps" pointer and pointer-to-member types to compare them at each
7271/// level.
7272///
7273/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7274/// C++20 [conv.qual], if permitted by the current language mode.
7275///
7276/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7277/// pair of types that can't be unwrapped further.
7279 bool AllowPiMismatch) const {
7280 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7281
7282 const auto *T1PtrType = T1->getAs<PointerType>();
7283 const auto *T2PtrType = T2->getAs<PointerType>();
7284 if (T1PtrType && T2PtrType) {
7285 T1 = T1PtrType->getPointeeType();
7286 T2 = T2PtrType->getPointeeType();
7287 return true;
7288 }
7289
7290 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7291 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7292 T1MPType && T2MPType) {
7293 // Compare the qualifiers of the canonical type, as the non-canonical type
7294 // may have qualifiers pointing to a base or derived class.
7295 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7296 return false;
7297 // Get the pointee types of the non-canonical type, in order to preserve
7298 // their sugar.
7299 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7300 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7301 return true;
7302 }
7303
7304 if (getLangOpts().ObjC) {
7305 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7306 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7307 if (T1OPType && T2OPType) {
7308 T1 = T1OPType->getPointeeType();
7309 T2 = T2OPType->getPointeeType();
7310 return true;
7311 }
7312 }
7313
7314 // FIXME: Block pointers, too?
7315
7316 return false;
7317}
7318
7320 while (true) {
7321 Qualifiers Quals;
7322 T1 = getUnqualifiedArrayType(T1, Quals);
7323 T2 = getUnqualifiedArrayType(T2, Quals);
7324 if (hasSameType(T1, T2))
7325 return true;
7326 if (!UnwrapSimilarTypes(T1, T2))
7327 return false;
7328 }
7329}
7330
7332 while (true) {
7333 Qualifiers Quals1, Quals2;
7334 T1 = getUnqualifiedArrayType(T1, Quals1);
7335 T2 = getUnqualifiedArrayType(T2, Quals2);
7336
7337 Quals1.removeCVRQualifiers();
7338 Quals2.removeCVRQualifiers();
7339 if (Quals1 != Quals2)
7340 return false;
7341
7342 if (hasSameType(T1, T2))
7343 return true;
7344
7345 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7346 return false;
7347 }
7348}
7349
7352 SourceLocation NameLoc) const {
7353 switch (Name.getKind()) {
7356 // DNInfo work in progress: CHECKME: what about DNLoc?
7358 NameLoc);
7359
7362 // DNInfo work in progress: CHECKME: what about DNLoc?
7363 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7364 }
7365
7368 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7369 }
7370
7374 DeclarationName DName;
7375 if (const IdentifierInfo *II = TN.getIdentifier()) {
7376 DName = DeclarationNames.getIdentifier(II);
7377 return DeclarationNameInfo(DName, NameLoc);
7378 } else {
7379 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7380 // DNInfo work in progress: FIXME: source locations?
7381 DeclarationNameLoc DNLoc =
7383 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7384 }
7385 }
7386
7390 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7391 NameLoc);
7392 }
7393
7398 NameLoc);
7399 }
7402 NameLoc);
7405 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7406 }
7407 }
7408
7409 llvm_unreachable("bad template name kind!");
7410}
7411
7412const TemplateArgument *
7414 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7415 if (!TP->hasDefaultArgument())
7416 return nullptr;
7417 return &TP->getDefaultArgument().getArgument();
7418 };
7419 switch (P->getKind()) {
7420 case NamedDecl::TemplateTypeParm:
7421 return handleParam(cast<TemplateTypeParmDecl>(P));
7422 case NamedDecl::NonTypeTemplateParm:
7423 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7424 case NamedDecl::TemplateTemplateParm:
7425 return handleParam(cast<TemplateTemplateParmDecl>(P));
7426 default:
7427 llvm_unreachable("Unexpected template parameter kind");
7428 }
7429}
7430
7432 bool IgnoreDeduced) const {
7433 while (std::optional<TemplateName> UnderlyingOrNone =
7434 Name.desugar(IgnoreDeduced))
7435 Name = *UnderlyingOrNone;
7436
7437 switch (Name.getKind()) {
7440 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7442
7443 // The canonical template name is the canonical template declaration.
7444 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7445 }
7446
7448 // An assumed template is just a name, so it is already canonical.
7449 return Name;
7450
7452 llvm_unreachable("cannot canonicalize overloaded template");
7453
7456 assert(DTN && "Non-dependent template names must refer to template decls.");
7457 NestedNameSpecifier Qualifier = DTN->getQualifier();
7458 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7459 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7460 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7461 /*HasTemplateKeyword=*/true});
7462 return Name;
7463 }
7464
7468 TemplateArgument canonArgPack =
7471 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7472 subst->getIndex(), subst->getFinal());
7473 }
7475 assert(IgnoreDeduced == false);
7477 DefaultArguments DefArgs = DTS->getDefaultArguments();
7478 TemplateName Underlying = DTS->getUnderlying();
7479
7480 TemplateName CanonUnderlying =
7481 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7482 bool NonCanonical = CanonUnderlying != Underlying;
7483 auto CanonArgs =
7484 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7485
7486 ArrayRef<NamedDecl *> Params =
7487 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7488 assert(CanonArgs.size() <= Params.size());
7489 // A deduced template name which deduces the same default arguments already
7490 // declared in the underlying template is the same template as the
7491 // underlying template. We need need to note any arguments which differ from
7492 // the corresponding declaration. If any argument differs, we must build a
7493 // deduced template name.
7494 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7496 if (!A)
7497 break;
7498 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7499 TemplateArgument &CanonDefArg = CanonArgs[I];
7500 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7501 continue;
7502 // Keep popping from the back any deault arguments which are the same.
7503 if (I == int(CanonArgs.size() - 1))
7504 CanonArgs.pop_back();
7505 NonCanonical = true;
7506 }
7507 return NonCanonical ? getDeducedTemplateName(
7508 CanonUnderlying,
7509 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7510 : Name;
7511 }
7515 llvm_unreachable("always sugar node");
7516 }
7517
7518 llvm_unreachable("bad template name!");
7519}
7520
7522 const TemplateName &Y,
7523 bool IgnoreDeduced) const {
7524 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7525 getCanonicalTemplateName(Y, IgnoreDeduced);
7526}
7527
7529 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7530 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7531 return false;
7533 return false;
7534 return true;
7535}
7536
7537bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7538 if (!XCE != !YCE)
7539 return false;
7540
7541 if (!XCE)
7542 return true;
7543
7544 llvm::FoldingSetNodeID XCEID, YCEID;
7545 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7546 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7547 return XCEID == YCEID;
7548}
7549
7551 const TypeConstraint *YTC) const {
7552 if (!XTC != !YTC)
7553 return false;
7554
7555 if (!XTC)
7556 return true;
7557
7558 auto *NCX = XTC->getNamedConcept();
7559 auto *NCY = YTC->getNamedConcept();
7560 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7561 return false;
7564 return false;
7566 if (XTC->getConceptReference()
7568 ->NumTemplateArgs !=
7570 return false;
7571
7572 // Compare slowly by profiling.
7573 //
7574 // We couldn't compare the profiling result for the template
7575 // args here. Consider the following example in different modules:
7576 //
7577 // template <__integer_like _Tp, C<_Tp> Sentinel>
7578 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7579 // return __t;
7580 // }
7581 //
7582 // When we compare the profiling result for `C<_Tp>` in different
7583 // modules, it will compare the type of `_Tp` in different modules.
7584 // However, the type of `_Tp` in different modules refer to different
7585 // types here naturally. So we couldn't compare the profiling result
7586 // for the template args directly.
7589}
7590
7592 const NamedDecl *Y) const {
7593 if (X->getKind() != Y->getKind())
7594 return false;
7595
7596 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7597 auto *TY = cast<TemplateTypeParmDecl>(Y);
7598 if (TX->isParameterPack() != TY->isParameterPack())
7599 return false;
7600 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7601 return false;
7602 return isSameTypeConstraint(TX->getTypeConstraint(),
7603 TY->getTypeConstraint());
7604 }
7605
7606 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7607 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7608 return TX->isParameterPack() == TY->isParameterPack() &&
7609 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7610 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7611 TY->getPlaceholderTypeConstraint());
7612 }
7613
7615 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7616 return TX->isParameterPack() == TY->isParameterPack() &&
7617 isSameTemplateParameterList(TX->getTemplateParameters(),
7618 TY->getTemplateParameters());
7619}
7620
7622 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7623 if (X->size() != Y->size())
7624 return false;
7625
7626 for (unsigned I = 0, N = X->size(); I != N; ++I)
7627 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7628 return false;
7629
7630 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7631}
7632
7634 const NamedDecl *Y) const {
7635 // If the type parameter isn't the same already, we don't need to check the
7636 // default argument further.
7637 if (!isSameTemplateParameter(X, Y))
7638 return false;
7639
7640 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7641 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7642 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7643 return false;
7644
7645 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7646 TTPY->getDefaultArgument().getArgument().getAsType());
7647 }
7648
7649 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7650 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7651 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7652 return false;
7653
7654 Expr *DefaultArgumentX =
7655 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7656 Expr *DefaultArgumentY =
7657 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7658 llvm::FoldingSetNodeID XID, YID;
7659 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7660 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7661 return XID == YID;
7662 }
7663
7664 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7665 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7666
7667 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7668 return false;
7669
7670 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7671 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7672 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7673}
7674
7676 const NestedNameSpecifier Y) {
7677 if (X == Y)
7678 return true;
7679 if (!X || !Y)
7680 return false;
7681
7682 auto Kind = X.getKind();
7683 if (Kind != Y.getKind())
7684 return false;
7685
7686 // FIXME: For namespaces and types, we're permitted to check that the entity
7687 // is named via the same tokens. We should probably do so.
7688 switch (Kind) {
7690 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7691 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7692 if (!declaresSameEntity(NamespaceX->getNamespace(),
7693 NamespaceY->getNamespace()))
7694 return false;
7695 return isSameQualifier(PrefixX, PrefixY);
7696 }
7698 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7699 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7700 return false;
7701 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7702 }
7706 return true;
7707 }
7708 llvm_unreachable("unhandled qualifier kind");
7709}
7710
7711static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7712 if (!A->getASTContext().getLangOpts().CUDA)
7713 return true; // Target attributes are overloadable in CUDA compilation only.
7714 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7715 return false;
7716 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7717 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7718 return true; // unattributed and __host__ functions are the same.
7719}
7720
7721/// Determine whether the attributes we can overload on are identical for A and
7722/// B. Will ignore any overloadable attrs represented in the type of A and B.
7724 const FunctionDecl *B) {
7725 // Note that pass_object_size attributes are represented in the function's
7726 // ExtParameterInfo, so we don't need to check them here.
7727
7728 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7729 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7730 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7731
7732 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7733 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7734 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7735
7736 // Return false if the number of enable_if attributes is different.
7737 if (!Cand1A || !Cand2A)
7738 return false;
7739
7740 Cand1ID.clear();
7741 Cand2ID.clear();
7742
7743 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7744 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7745
7746 // Return false if any of the enable_if expressions of A and B are
7747 // different.
7748 if (Cand1ID != Cand2ID)
7749 return false;
7750 }
7751 return hasSameCudaAttrs(A, B);
7752}
7753
7754bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7755 // Caution: this function is called by the AST reader during deserialization,
7756 // so it cannot rely on AST invariants being met. Non-trivial accessors
7757 // should be avoided, along with any traversal of redeclaration chains.
7758
7759 if (X == Y)
7760 return true;
7761
7762 if (X->getDeclName() != Y->getDeclName())
7763 return false;
7764
7765 // Must be in the same context.
7766 //
7767 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7768 // could be two different declarations of the same function. (We will fix the
7769 // semantic DC to refer to the primary definition after merging.)
7770 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7772 return false;
7773
7774 // If either X or Y are local to the owning module, they are only possible to
7775 // be the same entity if they are in the same module.
7776 if (X->isModuleLocal() || Y->isModuleLocal())
7777 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7778 return false;
7779
7780 // Two typedefs refer to the same entity if they have the same underlying
7781 // type.
7782 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7783 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7784 return hasSameType(TypedefX->getUnderlyingType(),
7785 TypedefY->getUnderlyingType());
7786
7787 // Must have the same kind.
7788 if (X->getKind() != Y->getKind())
7789 return false;
7790
7791 // Objective-C classes and protocols with the same name always match.
7793 return true;
7794
7796 // No need to handle these here: we merge them when adding them to the
7797 // template.
7798 return false;
7799 }
7800
7801 // Compatible tags match.
7802 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7803 const auto *TagY = cast<TagDecl>(Y);
7804 return (TagX->getTagKind() == TagY->getTagKind()) ||
7805 ((TagX->getTagKind() == TagTypeKind::Struct ||
7806 TagX->getTagKind() == TagTypeKind::Class ||
7807 TagX->getTagKind() == TagTypeKind::Interface) &&
7808 (TagY->getTagKind() == TagTypeKind::Struct ||
7809 TagY->getTagKind() == TagTypeKind::Class ||
7810 TagY->getTagKind() == TagTypeKind::Interface));
7811 }
7812
7813 // Functions with the same type and linkage match.
7814 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7815 // functions, etc.
7816 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7817 const auto *FuncY = cast<FunctionDecl>(Y);
7818 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7819 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7820 if (CtorX->getInheritedConstructor() &&
7821 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7822 CtorY->getInheritedConstructor().getConstructor()))
7823 return false;
7824 }
7825
7826 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7827 return false;
7828
7829 // Multiversioned functions with different feature strings are represented
7830 // as separate declarations.
7831 if (FuncX->isMultiVersion()) {
7832 const auto *TAX = FuncX->getAttr<TargetAttr>();
7833 const auto *TAY = FuncY->getAttr<TargetAttr>();
7834 assert(TAX && TAY && "Multiversion Function without target attribute");
7835
7836 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7837 return false;
7838 }
7839
7840 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7841 // not the same entity if they are constrained.
7842 if ((FuncX->isMemberLikeConstrainedFriend() ||
7843 FuncY->isMemberLikeConstrainedFriend()) &&
7844 !FuncX->getLexicalDeclContext()->Equals(
7845 FuncY->getLexicalDeclContext())) {
7846 return false;
7847 }
7848
7849 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7850 FuncY->getTrailingRequiresClause()))
7851 return false;
7852
7853 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7854 // Map to the first declaration that we've already merged into this one.
7855 // The TSI of redeclarations might not match (due to calling conventions
7856 // being inherited onto the type but not the TSI), but the TSI type of
7857 // the first declaration of the function should match across modules.
7858 FD = FD->getCanonicalDecl();
7859 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7860 : FD->getType();
7861 };
7862 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7863 if (!hasSameType(XT, YT)) {
7864 // We can get functions with different types on the redecl chain in C++17
7865 // if they have differing exception specifications and at least one of
7866 // the excpetion specs is unresolved.
7867 auto *XFPT = XT->getAs<FunctionProtoType>();
7868 auto *YFPT = YT->getAs<FunctionProtoType>();
7869 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7870 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7873 return true;
7874 return false;
7875 }
7876
7877 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7878 hasSameOverloadableAttrs(FuncX, FuncY);
7879 }
7880
7881 // Variables with the same type and linkage match.
7882 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7883 const auto *VarY = cast<VarDecl>(Y);
7884 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7885 // During deserialization, we might compare variables before we load
7886 // their types. Assume the types will end up being the same.
7887 if (VarX->getType().isNull() || VarY->getType().isNull())
7888 return true;
7889
7890 if (hasSameType(VarX->getType(), VarY->getType()))
7891 return true;
7892
7893 // We can get decls with different types on the redecl chain. Eg.
7894 // template <typename T> struct S { static T Var[]; }; // #1
7895 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7896 // Only? happens when completing an incomplete array type. In this case
7897 // when comparing #1 and #2 we should go through their element type.
7898 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7899 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7900 if (!VarXTy || !VarYTy)
7901 return false;
7902 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7903 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7904 }
7905 return false;
7906 }
7907
7908 // Namespaces with the same name and inlinedness match.
7909 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7910 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7911 return NamespaceX->isInline() == NamespaceY->isInline();
7912 }
7913
7914 // Identical template names and kinds match if their template parameter lists
7915 // and patterns match.
7916 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7917 const auto *TemplateY = cast<TemplateDecl>(Y);
7918
7919 // ConceptDecl wouldn't be the same if their constraint expression differs.
7920 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7921 const auto *ConceptY = cast<ConceptDecl>(Y);
7922 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7923 ConceptY->getConstraintExpr()))
7924 return false;
7925 }
7926
7927 return isSameEntity(TemplateX->getTemplatedDecl(),
7928 TemplateY->getTemplatedDecl()) &&
7929 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7930 TemplateY->getTemplateParameters());
7931 }
7932
7933 // Fields with the same name and the same type match.
7934 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7935 const auto *FDY = cast<FieldDecl>(Y);
7936 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7937 return hasSameType(FDX->getType(), FDY->getType());
7938 }
7939
7940 // Indirect fields with the same target field match.
7941 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7942 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7943 return IFDX->getAnonField()->getCanonicalDecl() ==
7944 IFDY->getAnonField()->getCanonicalDecl();
7945 }
7946
7947 // Enumerators with the same name match.
7949 // FIXME: Also check the value is odr-equivalent.
7950 return true;
7951
7952 // Using shadow declarations with the same target match.
7953 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7954 const auto *USY = cast<UsingShadowDecl>(Y);
7955 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7956 }
7957
7958 // Using declarations with the same qualifier match. (We already know that
7959 // the name matches.)
7960 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7961 const auto *UY = cast<UsingDecl>(Y);
7962 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7963 UX->hasTypename() == UY->hasTypename() &&
7964 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7965 }
7966 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7967 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7968 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7969 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7970 }
7971 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7972 return isSameQualifier(
7973 UX->getQualifier(),
7974 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7975 }
7976
7977 // Using-pack declarations are only created by instantiation, and match if
7978 // they're instantiated from matching UnresolvedUsing...Decls.
7979 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7980 return declaresSameEntity(
7981 UX->getInstantiatedFromUsingDecl(),
7982 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
7983 }
7984
7985 // Namespace alias definitions with the same target match.
7986 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
7987 const auto *NAY = cast<NamespaceAliasDecl>(Y);
7988 return NAX->getNamespace()->Equals(NAY->getNamespace());
7989 }
7990
7991 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
7992 const auto *UY = cast<UsingEnumDecl>(Y);
7993 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7994 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
7995 }
7996
7997 return false;
7998}
7999
8002 switch (Arg.getKind()) {
8004 return Arg;
8005
8007 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8008 Arg.getIsDefaulted());
8009
8011 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8013 Arg.getIsDefaulted());
8014 }
8015
8018 /*isNullPtr*/ true, Arg.getIsDefaulted());
8019
8022 Arg.getIsDefaulted());
8023
8025 return TemplateArgument(
8028
8031
8033 return TemplateArgument(*this,
8036
8039 /*isNullPtr*/ false, Arg.getIsDefaulted());
8040
8042 bool AnyNonCanonArgs = false;
8043 auto CanonArgs = ::getCanonicalTemplateArguments(
8044 *this, Arg.pack_elements(), AnyNonCanonArgs);
8045 if (!AnyNonCanonArgs)
8046 return Arg;
8048 const_cast<ASTContext &>(*this), CanonArgs);
8049 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8050 return NewArg;
8051 }
8052 }
8053
8054 // Silence GCC warning
8055 llvm_unreachable("Unhandled template argument kind");
8056}
8057
8059 const TemplateArgument &Arg2) const {
8060 if (Arg1.getKind() != Arg2.getKind())
8061 return false;
8062
8063 switch (Arg1.getKind()) {
8065 llvm_unreachable("Comparing NULL template argument");
8066
8068 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8069
8071 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8073
8075 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8076
8081
8083 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8084 Arg2.getAsIntegral());
8085
8087 return Arg1.structurallyEquals(Arg2);
8088
8090 llvm::FoldingSetNodeID ID1, ID2;
8091 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8092 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8093 return ID1 == ID2;
8094 }
8095
8097 return llvm::equal(
8098 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8099 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8100 return isSameTemplateArgument(Arg1, Arg2);
8101 });
8102 }
8103
8104 llvm_unreachable("Unhandled template argument kind");
8105}
8106
8108 // Handle the non-qualified case efficiently.
8109 if (!T.hasLocalQualifiers()) {
8110 // Handle the common positive case fast.
8111 if (const auto *AT = dyn_cast<ArrayType>(T))
8112 return AT;
8113 }
8114
8115 // Handle the common negative case fast.
8116 if (!isa<ArrayType>(T.getCanonicalType()))
8117 return nullptr;
8118
8119 // Apply any qualifiers from the array type to the element type. This
8120 // implements C99 6.7.3p8: "If the specification of an array type includes
8121 // any type qualifiers, the element type is so qualified, not the array type."
8122
8123 // If we get here, we either have type qualifiers on the type, or we have
8124 // sugar such as a typedef in the way. If we have type qualifiers on the type
8125 // we must propagate them down into the element type.
8126
8127 SplitQualType split = T.getSplitDesugaredType();
8128 Qualifiers qs = split.Quals;
8129
8130 // If we have a simple case, just return now.
8131 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8132 if (!ATy || qs.empty())
8133 return ATy;
8134
8135 // Otherwise, we have an array and we have qualifiers on it. Push the
8136 // qualifiers into the array element type and return a new array type.
8137 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8138
8139 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8140 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8141 CAT->getSizeExpr(),
8142 CAT->getSizeModifier(),
8143 CAT->getIndexTypeCVRQualifiers()));
8144 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8146 IAT->getSizeModifier(),
8147 IAT->getIndexTypeCVRQualifiers()));
8148
8149 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8151 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8152 DSAT->getIndexTypeCVRQualifiers()));
8153
8154 const auto *VAT = cast<VariableArrayType>(ATy);
8155 return cast<ArrayType>(
8156 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8157 VAT->getIndexTypeCVRQualifiers()));
8158}
8159
8161 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8162 return getLValueReferenceType(T);
8163 if (getLangOpts().HLSL && T->isConstantArrayType())
8164 return getArrayParameterType(T);
8165 if (T->isArrayType() || T->isFunctionType())
8166 return getDecayedType(T);
8167 return T;
8168}
8169
8173 return T.getUnqualifiedType();
8174}
8175
8177 // C++ [except.throw]p3:
8178 // A throw-expression initializes a temporary object, called the exception
8179 // object, the type of which is determined by removing any top-level
8180 // cv-qualifiers from the static type of the operand of throw and adjusting
8181 // the type from "array of T" or "function returning T" to "pointer to T"
8182 // or "pointer to function returning T", [...]
8184 if (T->isArrayType() || T->isFunctionType())
8185 T = getDecayedType(T);
8186 return T.getUnqualifiedType();
8187}
8188
8189/// getArrayDecayedType - Return the properly qualified result of decaying the
8190/// specified array type to a pointer. This operation is non-trivial when
8191/// handling typedefs etc. The canonical type of "T" must be an array type,
8192/// this returns a pointer to a properly qualified element of the array.
8193///
8194/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8196 // Get the element type with 'getAsArrayType' so that we don't lose any
8197 // typedefs in the element type of the array. This also handles propagation
8198 // of type qualifiers from the array type into the element type if present
8199 // (C99 6.7.3p8).
8200 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8201 assert(PrettyArrayType && "Not an array type!");
8202
8203 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8204
8205 // int x[restrict 4] -> int *restrict
8207 PrettyArrayType->getIndexTypeQualifiers());
8208
8209 // int x[_Nullable] -> int * _Nullable
8210 if (auto Nullability = Ty->getNullability()) {
8211 Result = getAttributedType(*Nullability, Result, Result);
8212 }
8213 return Result;
8214}
8215
8217 return getBaseElementType(array->getElementType());
8218}
8219
8221 Qualifiers qs;
8222 while (true) {
8223 SplitQualType split = type.getSplitDesugaredType();
8224 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8225 if (!array) break;
8226
8227 type = array->getElementType();
8229 }
8230
8231 return getQualifiedType(type, qs);
8232}
8233
8234/// getConstantArrayElementCount - Returns number of constant array elements.
8235uint64_t
8237 uint64_t ElementCount = 1;
8238 do {
8239 ElementCount *= CA->getZExtSize();
8240 CA = dyn_cast_or_null<ConstantArrayType>(
8242 } while (CA);
8243 return ElementCount;
8244}
8245
8247 const ArrayInitLoopExpr *AILE) const {
8248 if (!AILE)
8249 return 0;
8250
8251 uint64_t ElementCount = 1;
8252
8253 do {
8254 ElementCount *= AILE->getArraySize().getZExtValue();
8255 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8256 } while (AILE);
8257
8258 return ElementCount;
8259}
8260
8261/// getFloatingRank - Return a relative rank for floating point types.
8262/// This routine will assert if passed a built-in type that isn't a float.
8264 if (const auto *CT = T->getAs<ComplexType>())
8265 return getFloatingRank(CT->getElementType());
8266
8267 switch (T->castAs<BuiltinType>()->getKind()) {
8268 default: llvm_unreachable("getFloatingRank(): not a floating type");
8269 case BuiltinType::Float16: return Float16Rank;
8270 case BuiltinType::Half: return HalfRank;
8271 case BuiltinType::Float: return FloatRank;
8272 case BuiltinType::Double: return DoubleRank;
8273 case BuiltinType::LongDouble: return LongDoubleRank;
8274 case BuiltinType::Float128: return Float128Rank;
8275 case BuiltinType::BFloat16: return BFloat16Rank;
8276 case BuiltinType::Ibm128: return Ibm128Rank;
8277 }
8278}
8279
8280/// getFloatingTypeOrder - Compare the rank of the two specified floating
8281/// point types, ignoring the domain of the type (i.e. 'double' ==
8282/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8283/// LHS < RHS, return -1.
8285 FloatingRank LHSR = getFloatingRank(LHS);
8286 FloatingRank RHSR = getFloatingRank(RHS);
8287
8288 if (LHSR == RHSR)
8289 return 0;
8290 if (LHSR > RHSR)
8291 return 1;
8292 return -1;
8293}
8294
8297 return 0;
8298 return getFloatingTypeOrder(LHS, RHS);
8299}
8300
8301/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8302/// routine will assert if passed a built-in type that isn't an integer or enum,
8303/// or if it is not canonicalized.
8304unsigned ASTContext::getIntegerRank(const Type *T) const {
8305 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8306
8307 // Results in this 'losing' to any type of the same size, but winning if
8308 // larger.
8309 if (const auto *EIT = dyn_cast<BitIntType>(T))
8310 return 0 + (EIT->getNumBits() << 3);
8311
8312 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8313 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8314
8315 switch (cast<BuiltinType>(T)->getKind()) {
8316 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8317 case BuiltinType::Bool:
8318 return 1 + (getIntWidth(BoolTy) << 3);
8319 case BuiltinType::Char_S:
8320 case BuiltinType::Char_U:
8321 case BuiltinType::SChar:
8322 case BuiltinType::UChar:
8323 return 2 + (getIntWidth(CharTy) << 3);
8324 case BuiltinType::Short:
8325 case BuiltinType::UShort:
8326 return 3 + (getIntWidth(ShortTy) << 3);
8327 case BuiltinType::Int:
8328 case BuiltinType::UInt:
8329 return 4 + (getIntWidth(IntTy) << 3);
8330 case BuiltinType::Long:
8331 case BuiltinType::ULong:
8332 return 5 + (getIntWidth(LongTy) << 3);
8333 case BuiltinType::LongLong:
8334 case BuiltinType::ULongLong:
8335 return 6 + (getIntWidth(LongLongTy) << 3);
8336 case BuiltinType::Int128:
8337 case BuiltinType::UInt128:
8338 return 7 + (getIntWidth(Int128Ty) << 3);
8339
8340 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8341 // their underlying types" [c++20 conv.rank]
8342 case BuiltinType::Char8:
8343 return getIntegerRank(UnsignedCharTy.getTypePtr());
8344 case BuiltinType::Char16:
8345 return getIntegerRank(
8346 getFromTargetType(Target->getChar16Type()).getTypePtr());
8347 case BuiltinType::Char32:
8348 return getIntegerRank(
8349 getFromTargetType(Target->getChar32Type()).getTypePtr());
8350 case BuiltinType::WChar_S:
8351 case BuiltinType::WChar_U:
8352 return getIntegerRank(
8353 getFromTargetType(Target->getWCharType()).getTypePtr());
8354 }
8355}
8356
8357/// Whether this is a promotable bitfield reference according
8358/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8359///
8360/// \returns the type this bit-field will promote to, or NULL if no
8361/// promotion occurs.
8363 if (E->isTypeDependent() || E->isValueDependent())
8364 return {};
8365
8366 // C++ [conv.prom]p5:
8367 // If the bit-field has an enumerated type, it is treated as any other
8368 // value of that type for promotion purposes.
8370 return {};
8371
8372 // FIXME: We should not do this unless E->refersToBitField() is true. This
8373 // matters in C where getSourceBitField() will find bit-fields for various
8374 // cases where the source expression is not a bit-field designator.
8375
8376 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8377 if (!Field)
8378 return {};
8379
8380 QualType FT = Field->getType();
8381
8382 uint64_t BitWidth = Field->getBitWidthValue();
8383 uint64_t IntSize = getTypeSize(IntTy);
8384 // C++ [conv.prom]p5:
8385 // A prvalue for an integral bit-field can be converted to a prvalue of type
8386 // int if int can represent all the values of the bit-field; otherwise, it
8387 // can be converted to unsigned int if unsigned int can represent all the
8388 // values of the bit-field. If the bit-field is larger yet, no integral
8389 // promotion applies to it.
8390 // C11 6.3.1.1/2:
8391 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8392 // If an int can represent all values of the original type (as restricted by
8393 // the width, for a bit-field), the value is converted to an int; otherwise,
8394 // it is converted to an unsigned int.
8395 //
8396 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8397 // We perform that promotion here to match GCC and C++.
8398 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8399 // greater than that of 'int'. We perform that promotion to match GCC.
8400 //
8401 // C23 6.3.1.1p2:
8402 // The value from a bit-field of a bit-precise integer type is converted to
8403 // the corresponding bit-precise integer type. (The rest is the same as in
8404 // C11.)
8405 if (QualType QT = Field->getType(); QT->isBitIntType())
8406 return QT;
8407
8408 if (BitWidth < IntSize)
8409 return IntTy;
8410
8411 if (BitWidth == IntSize)
8412 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8413
8414 // Bit-fields wider than int are not subject to promotions, and therefore act
8415 // like the base type. GCC has some weird bugs in this area that we
8416 // deliberately do not follow (GCC follows a pre-standard resolution to
8417 // C's DR315 which treats bit-width as being part of the type, and this leaks
8418 // into their semantics in some cases).
8419 return {};
8420}
8421
8422/// getPromotedIntegerType - Returns the type that Promotable will
8423/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8424/// integer type.
8426 assert(!Promotable.isNull());
8427 assert(isPromotableIntegerType(Promotable));
8428 if (const auto *ED = Promotable->getAsEnumDecl())
8429 return ED->getPromotionType();
8430
8431 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8432 // qualifier.
8433 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8434 QualType PromotedUnderlying =
8435 getPromotedIntegerType(OBT->getUnderlyingType());
8436 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8437 }
8438
8439 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8440 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8441 // (3.9.1) can be converted to a prvalue of the first of the following
8442 // types that can represent all the values of its underlying type:
8443 // int, unsigned int, long int, unsigned long int, long long int, or
8444 // unsigned long long int [...]
8445 // FIXME: Is there some better way to compute this?
8446 if (BT->getKind() == BuiltinType::WChar_S ||
8447 BT->getKind() == BuiltinType::WChar_U ||
8448 BT->getKind() == BuiltinType::Char8 ||
8449 BT->getKind() == BuiltinType::Char16 ||
8450 BT->getKind() == BuiltinType::Char32) {
8451 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8452 uint64_t FromSize = getTypeSize(BT);
8453 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8455 for (const auto &PT : PromoteTypes) {
8456 uint64_t ToSize = getTypeSize(PT);
8457 if (FromSize < ToSize ||
8458 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8459 return PT;
8460 }
8461 llvm_unreachable("char type should fit into long long");
8462 }
8463 }
8464
8465 // At this point, we should have a signed or unsigned integer type.
8466 if (Promotable->isSignedIntegerType())
8467 return IntTy;
8468 uint64_t PromotableSize = getIntWidth(Promotable);
8469 uint64_t IntSize = getIntWidth(IntTy);
8470 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8471 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8472}
8473
8474/// Recurses in pointer/array types until it finds an objc retainable
8475/// type and returns its ownership.
8477 while (!T.isNull()) {
8478 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8479 return T.getObjCLifetime();
8480 if (T->isArrayType())
8482 else if (const auto *PT = T->getAs<PointerType>())
8483 T = PT->getPointeeType();
8484 else if (const auto *RT = T->getAs<ReferenceType>())
8485 T = RT->getPointeeType();
8486 else
8487 break;
8488 }
8489
8490 return Qualifiers::OCL_None;
8491}
8492
8493static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8494 // Incomplete enum types are not treated as integer types.
8495 // FIXME: In C++, enum types are never integer types.
8496 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8497 if (ED->isComplete() && !ED->isScoped())
8498 return ED->getIntegerType().getTypePtr();
8499 return nullptr;
8500}
8501
8502/// getIntegerTypeOrder - Returns the highest ranked integer type:
8503/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8504/// LHS < RHS, return -1.
8506 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8507 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8508
8509 // Unwrap enums to their underlying type.
8510 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8511 LHSC = getIntegerTypeForEnum(ET);
8512 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8513 RHSC = getIntegerTypeForEnum(ET);
8514
8515 if (LHSC == RHSC) return 0;
8516
8517 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8518 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8519
8520 unsigned LHSRank = getIntegerRank(LHSC);
8521 unsigned RHSRank = getIntegerRank(RHSC);
8522
8523 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8524 if (LHSRank == RHSRank) return 0;
8525 return LHSRank > RHSRank ? 1 : -1;
8526 }
8527
8528 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8529 if (LHSUnsigned) {
8530 // If the unsigned [LHS] type is larger, return it.
8531 if (LHSRank >= RHSRank)
8532 return 1;
8533
8534 // If the signed type can represent all values of the unsigned type, it
8535 // wins. Because we are dealing with 2's complement and types that are
8536 // powers of two larger than each other, this is always safe.
8537 return -1;
8538 }
8539
8540 // If the unsigned [RHS] type is larger, return it.
8541 if (RHSRank >= LHSRank)
8542 return -1;
8543
8544 // If the signed type can represent all values of the unsigned type, it
8545 // wins. Because we are dealing with 2's complement and types that are
8546 // powers of two larger than each other, this is always safe.
8547 return 1;
8548}
8549
8551 if (CFConstantStringTypeDecl)
8552 return CFConstantStringTypeDecl;
8553
8554 assert(!CFConstantStringTagDecl &&
8555 "tag and typedef should be initialized together");
8556 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8557 CFConstantStringTagDecl->startDefinition();
8558
8559 struct {
8560 QualType Type;
8561 const char *Name;
8562 } Fields[5];
8563 unsigned Count = 0;
8564
8565 /// Objective-C ABI
8566 ///
8567 /// typedef struct __NSConstantString_tag {
8568 /// const int *isa;
8569 /// int flags;
8570 /// const char *str;
8571 /// long length;
8572 /// } __NSConstantString;
8573 ///
8574 /// Swift ABI (4.1, 4.2)
8575 ///
8576 /// typedef struct __NSConstantString_tag {
8577 /// uintptr_t _cfisa;
8578 /// uintptr_t _swift_rc;
8579 /// _Atomic(uint64_t) _cfinfoa;
8580 /// const char *_ptr;
8581 /// uint32_t _length;
8582 /// } __NSConstantString;
8583 ///
8584 /// Swift ABI (5.0)
8585 ///
8586 /// typedef struct __NSConstantString_tag {
8587 /// uintptr_t _cfisa;
8588 /// uintptr_t _swift_rc;
8589 /// _Atomic(uint64_t) _cfinfoa;
8590 /// const char *_ptr;
8591 /// uintptr_t _length;
8592 /// } __NSConstantString;
8593
8594 const auto CFRuntime = getLangOpts().CFRuntime;
8595 if (static_cast<unsigned>(CFRuntime) <
8596 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8597 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8598 Fields[Count++] = { IntTy, "flags" };
8599 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8600 Fields[Count++] = { LongTy, "length" };
8601 } else {
8602 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8603 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8604 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8605 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8608 Fields[Count++] = { IntTy, "_ptr" };
8609 else
8610 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8611 }
8612
8613 // Create fields
8614 for (unsigned i = 0; i < Count; ++i) {
8615 FieldDecl *Field =
8616 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8617 SourceLocation(), &Idents.get(Fields[i].Name),
8618 Fields[i].Type, /*TInfo=*/nullptr,
8619 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8620 Field->setAccess(AS_public);
8621 CFConstantStringTagDecl->addDecl(Field);
8622 }
8623
8624 CFConstantStringTagDecl->completeDefinition();
8625 // This type is designed to be compatible with NSConstantString, but cannot
8626 // use the same name, since NSConstantString is an interface.
8627 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8628 CFConstantStringTypeDecl =
8629 buildImplicitTypedef(tagType, "__NSConstantString");
8630
8631 return CFConstantStringTypeDecl;
8632}
8633
8635 if (!CFConstantStringTagDecl)
8636 getCFConstantStringDecl(); // Build the tag and the typedef.
8637 return CFConstantStringTagDecl;
8638}
8639
8640// getCFConstantStringType - Return the type used for constant CFStrings.
8645
8647 if (ObjCSuperType.isNull()) {
8648 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8649 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8650 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8651 }
8652 return ObjCSuperType;
8653}
8654
8656 const auto *TT = T->castAs<TypedefType>();
8657 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8658 CFConstantStringTagDecl = TT->castAsRecordDecl();
8659}
8660
8662 if (BlockDescriptorType)
8663 return getCanonicalTagType(BlockDescriptorType);
8664
8665 RecordDecl *RD;
8666 // FIXME: Needs the FlagAppleBlock bit.
8667 RD = buildImplicitRecord("__block_descriptor");
8668 RD->startDefinition();
8669
8670 QualType FieldTypes[] = {
8673 };
8674
8675 static const char *const FieldNames[] = {
8676 "reserved",
8677 "Size"
8678 };
8679
8680 for (size_t i = 0; i < 2; ++i) {
8682 *this, RD, SourceLocation(), SourceLocation(),
8683 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8684 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8685 Field->setAccess(AS_public);
8686 RD->addDecl(Field);
8687 }
8688
8689 RD->completeDefinition();
8690
8691 BlockDescriptorType = RD;
8692
8693 return getCanonicalTagType(BlockDescriptorType);
8694}
8695
8697 if (BlockDescriptorExtendedType)
8698 return getCanonicalTagType(BlockDescriptorExtendedType);
8699
8700 RecordDecl *RD;
8701 // FIXME: Needs the FlagAppleBlock bit.
8702 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8703 RD->startDefinition();
8704
8705 QualType FieldTypes[] = {
8710 };
8711
8712 static const char *const FieldNames[] = {
8713 "reserved",
8714 "Size",
8715 "CopyFuncPtr",
8716 "DestroyFuncPtr"
8717 };
8718
8719 for (size_t i = 0; i < 4; ++i) {
8721 *this, RD, SourceLocation(), SourceLocation(),
8722 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8723 /*BitWidth=*/nullptr,
8724 /*Mutable=*/false, ICIS_NoInit);
8725 Field->setAccess(AS_public);
8726 RD->addDecl(Field);
8727 }
8728
8729 RD->completeDefinition();
8730
8731 BlockDescriptorExtendedType = RD;
8732 return getCanonicalTagType(BlockDescriptorExtendedType);
8733}
8734
8736 const auto *BT = dyn_cast<BuiltinType>(T);
8737
8738 if (!BT) {
8739 if (isa<PipeType>(T))
8740 return OCLTK_Pipe;
8741
8742 return OCLTK_Default;
8743 }
8744
8745 switch (BT->getKind()) {
8746#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8747 case BuiltinType::Id: \
8748 return OCLTK_Image;
8749#include "clang/Basic/OpenCLImageTypes.def"
8750
8751 case BuiltinType::OCLClkEvent:
8752 return OCLTK_ClkEvent;
8753
8754 case BuiltinType::OCLEvent:
8755 return OCLTK_Event;
8756
8757 case BuiltinType::OCLQueue:
8758 return OCLTK_Queue;
8759
8760 case BuiltinType::OCLReserveID:
8761 return OCLTK_ReserveID;
8762
8763 case BuiltinType::OCLSampler:
8764 return OCLTK_Sampler;
8765
8766 default:
8767 return OCLTK_Default;
8768 }
8769}
8770
8772 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8773}
8774
8775/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8776/// requires copy/dispose. Note that this must match the logic
8777/// in buildByrefHelpers.
8779 const VarDecl *D) {
8780 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8781 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8782 if (!copyExpr && record->hasTrivialDestructor()) return false;
8783
8784 return true;
8785 }
8786
8788 return true;
8789
8790 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8791 // move or destroy.
8793 return true;
8794
8795 if (!Ty->isObjCRetainableType()) return false;
8796
8797 Qualifiers qs = Ty.getQualifiers();
8798
8799 // If we have lifetime, that dominates.
8800 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8801 switch (lifetime) {
8802 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8803
8804 // These are just bits as far as the runtime is concerned.
8807 return false;
8808
8809 // These cases should have been taken care of when checking the type's
8810 // non-triviality.
8813 llvm_unreachable("impossible");
8814 }
8815 llvm_unreachable("fell out of lifetime switch!");
8816 }
8817 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8819}
8820
8822 Qualifiers::ObjCLifetime &LifeTime,
8823 bool &HasByrefExtendedLayout) const {
8824 if (!getLangOpts().ObjC ||
8825 getLangOpts().getGC() != LangOptions::NonGC)
8826 return false;
8827
8828 HasByrefExtendedLayout = false;
8829 if (Ty->isRecordType()) {
8830 HasByrefExtendedLayout = true;
8831 LifeTime = Qualifiers::OCL_None;
8832 } else if ((LifeTime = Ty.getObjCLifetime())) {
8833 // Honor the ARC qualifiers.
8834 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8835 // The MRR rule.
8837 } else {
8838 LifeTime = Qualifiers::OCL_None;
8839 }
8840 return true;
8841}
8842
8844 assert(Target && "Expected target to be initialized");
8845 const llvm::Triple &T = Target->getTriple();
8846 // Windows is LLP64 rather than LP64
8847 if (T.isOSWindows() && T.isArch64Bit())
8848 return UnsignedLongLongTy;
8849 return UnsignedLongTy;
8850}
8851
8853 assert(Target && "Expected target to be initialized");
8854 const llvm::Triple &T = Target->getTriple();
8855 // Windows is LLP64 rather than LP64
8856 if (T.isOSWindows() && T.isArch64Bit())
8857 return LongLongTy;
8858 return LongTy;
8859}
8860
8862 if (!ObjCInstanceTypeDecl)
8863 ObjCInstanceTypeDecl =
8864 buildImplicitTypedef(getObjCIdType(), "instancetype");
8865 return ObjCInstanceTypeDecl;
8866}
8867
8868// This returns true if a type has been typedefed to BOOL:
8869// typedef <type> BOOL;
8871 if (const auto *TT = dyn_cast<TypedefType>(T))
8872 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8873 return II->isStr("BOOL");
8874
8875 return false;
8876}
8877
8878/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8879/// purpose.
8881 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8882 return CharUnits::Zero();
8883
8885
8886 // Make all integer and enum types at least as large as an int
8887 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8888 sz = std::max(sz, getTypeSizeInChars(IntTy));
8889 // Treat arrays as pointers, since that's how they're passed in.
8890 else if (type->isArrayType())
8892 return sz;
8893}
8894
8901
8904 if (!VD->isInline())
8906
8907 // In almost all cases, it's a weak definition.
8908 auto *First = VD->getFirstDecl();
8909 if (First->isInlineSpecified() || !First->isStaticDataMember())
8911
8912 // If there's a file-context declaration in this translation unit, it's a
8913 // non-discardable definition.
8914 for (auto *D : VD->redecls())
8916 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8918
8919 // If we've not seen one yet, we don't know.
8921}
8922
8923static std::string charUnitsToString(const CharUnits &CU) {
8924 return llvm::itostr(CU.getQuantity());
8925}
8926
8927/// getObjCEncodingForBlock - Return the encoded type for this block
8928/// declaration.
8930 std::string S;
8931
8932 const BlockDecl *Decl = Expr->getBlockDecl();
8933 QualType BlockTy =
8935 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8936 // Encode result type.
8937 if (getLangOpts().EncodeExtendedBlockSig)
8939 true /*Extended*/);
8940 else
8941 getObjCEncodingForType(BlockReturnTy, S);
8942 // Compute size of all parameters.
8943 // Start with computing size of a pointer in number of bytes.
8944 // FIXME: There might(should) be a better way of doing this computation!
8946 CharUnits ParmOffset = PtrSize;
8947 for (auto *PI : Decl->parameters()) {
8948 QualType PType = PI->getType();
8950 if (sz.isZero())
8951 continue;
8952 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8953 ParmOffset += sz;
8954 }
8955 // Size of the argument frame
8956 S += charUnitsToString(ParmOffset);
8957 // Block pointer and offset.
8958 S += "@?0";
8959
8960 // Argument types.
8961 ParmOffset = PtrSize;
8962 for (auto *PVDecl : Decl->parameters()) {
8963 QualType PType = PVDecl->getOriginalType();
8964 if (const auto *AT =
8965 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8966 // Use array's original type only if it has known number of
8967 // elements.
8968 if (!isa<ConstantArrayType>(AT))
8969 PType = PVDecl->getType();
8970 } else if (PType->isFunctionType())
8971 PType = PVDecl->getType();
8972 if (getLangOpts().EncodeExtendedBlockSig)
8974 S, true /*Extended*/);
8975 else
8976 getObjCEncodingForType(PType, S);
8977 S += charUnitsToString(ParmOffset);
8978 ParmOffset += getObjCEncodingTypeSize(PType);
8979 }
8980
8981 return S;
8982}
8983
8984std::string
8986 std::string S;
8987 // Encode result type.
8988 getObjCEncodingForType(Decl->getReturnType(), S);
8989 CharUnits ParmOffset;
8990 // Compute size of all parameters.
8991 for (auto *PI : Decl->parameters()) {
8992 QualType PType = PI->getType();
8994 if (sz.isZero())
8995 continue;
8996
8997 assert(sz.isPositive() &&
8998 "getObjCEncodingForFunctionDecl - Incomplete param type");
8999 ParmOffset += sz;
9000 }
9001 S += charUnitsToString(ParmOffset);
9002 ParmOffset = CharUnits::Zero();
9003
9004 // Argument types.
9005 for (auto *PVDecl : Decl->parameters()) {
9006 QualType PType = PVDecl->getOriginalType();
9007 if (const auto *AT =
9008 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9009 // Use array's original type only if it has known number of
9010 // elements.
9011 if (!isa<ConstantArrayType>(AT))
9012 PType = PVDecl->getType();
9013 } else if (PType->isFunctionType())
9014 PType = PVDecl->getType();
9015 getObjCEncodingForType(PType, S);
9016 S += charUnitsToString(ParmOffset);
9017 ParmOffset += getObjCEncodingTypeSize(PType);
9018 }
9019
9020 return S;
9021}
9022
9023/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9024/// method parameter or return type. If Extended, include class names and
9025/// block object types.
9027 QualType T, std::string& S,
9028 bool Extended) const {
9029 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9031 // Encode parameter type.
9032 ObjCEncOptions Options = ObjCEncOptions()
9033 .setExpandPointedToStructures()
9034 .setExpandStructures()
9035 .setIsOutermostType();
9036 if (Extended)
9037 Options.setEncodeBlockParameters().setEncodeClassNames();
9038 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9039}
9040
9041/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9042/// declaration.
9044 bool Extended) const {
9045 // FIXME: This is not very efficient.
9046 // Encode return type.
9047 std::string S;
9048 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9049 Decl->getReturnType(), S, Extended);
9050 // Compute size of all parameters.
9051 // Start with computing size of a pointer in number of bytes.
9052 // FIXME: There might(should) be a better way of doing this computation!
9054 // The first two arguments (self and _cmd) are pointers; account for
9055 // their size.
9056 CharUnits ParmOffset = 2 * PtrSize;
9057 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9058 E = Decl->sel_param_end(); PI != E; ++PI) {
9059 QualType PType = (*PI)->getType();
9061 if (sz.isZero())
9062 continue;
9063
9064 assert(sz.isPositive() &&
9065 "getObjCEncodingForMethodDecl - Incomplete param type");
9066 ParmOffset += sz;
9067 }
9068 S += charUnitsToString(ParmOffset);
9069 S += "@0:";
9070 S += charUnitsToString(PtrSize);
9071
9072 // Argument types.
9073 ParmOffset = 2 * PtrSize;
9074 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9075 E = Decl->sel_param_end(); PI != E; ++PI) {
9076 const ParmVarDecl *PVDecl = *PI;
9077 QualType PType = PVDecl->getOriginalType();
9078 if (const auto *AT =
9079 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9080 // Use array's original type only if it has known number of
9081 // elements.
9082 if (!isa<ConstantArrayType>(AT))
9083 PType = PVDecl->getType();
9084 } else if (PType->isFunctionType())
9085 PType = PVDecl->getType();
9087 PType, S, Extended);
9088 S += charUnitsToString(ParmOffset);
9089 ParmOffset += getObjCEncodingTypeSize(PType);
9090 }
9091
9092 return S;
9093}
9094
9097 const ObjCPropertyDecl *PD,
9098 const Decl *Container) const {
9099 if (!Container)
9100 return nullptr;
9101 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9102 for (auto *PID : CID->property_impls())
9103 if (PID->getPropertyDecl() == PD)
9104 return PID;
9105 } else {
9106 const auto *OID = cast<ObjCImplementationDecl>(Container);
9107 for (auto *PID : OID->property_impls())
9108 if (PID->getPropertyDecl() == PD)
9109 return PID;
9110 }
9111 return nullptr;
9112}
9113
9114/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9115/// property declaration. If non-NULL, Container must be either an
9116/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9117/// NULL when getting encodings for protocol properties.
9118/// Property attributes are stored as a comma-delimited C string. The simple
9119/// attributes readonly and bycopy are encoded as single characters. The
9120/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9121/// encoded as single characters, followed by an identifier. Property types
9122/// are also encoded as a parametrized attribute. The characters used to encode
9123/// these attributes are defined by the following enumeration:
9124/// @code
9125/// enum PropertyAttributes {
9126/// kPropertyReadOnly = 'R', // property is read-only.
9127/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9128/// kPropertyByref = '&', // property is a reference to the value last assigned
9129/// kPropertyDynamic = 'D', // property is dynamic
9130/// kPropertyGetter = 'G', // followed by getter selector name
9131/// kPropertySetter = 'S', // followed by setter selector name
9132/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9133/// kPropertyType = 'T' // followed by old-style type encoding.
9134/// kPropertyWeak = 'W' // 'weak' property
9135/// kPropertyStrong = 'P' // property GC'able
9136/// kPropertyNonAtomic = 'N' // property non-atomic
9137/// kPropertyOptional = '?' // property optional
9138/// };
9139/// @endcode
9140std::string
9142 const Decl *Container) const {
9143 // Collect information from the property implementation decl(s).
9144 bool Dynamic = false;
9145 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9146
9147 if (ObjCPropertyImplDecl *PropertyImpDecl =
9149 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9150 Dynamic = true;
9151 else
9152 SynthesizePID = PropertyImpDecl;
9153 }
9154
9155 // FIXME: This is not very efficient.
9156 std::string S = "T";
9157
9158 // Encode result type.
9159 // GCC has some special rules regarding encoding of properties which
9160 // closely resembles encoding of ivars.
9162
9163 if (PD->isOptional())
9164 S += ",?";
9165
9166 if (PD->isReadOnly()) {
9167 S += ",R";
9169 S += ",C";
9171 S += ",&";
9173 S += ",W";
9174 } else {
9175 switch (PD->getSetterKind()) {
9176 case ObjCPropertyDecl::Assign: break;
9177 case ObjCPropertyDecl::Copy: S += ",C"; break;
9178 case ObjCPropertyDecl::Retain: S += ",&"; break;
9179 case ObjCPropertyDecl::Weak: S += ",W"; break;
9180 }
9181 }
9182
9183 // It really isn't clear at all what this means, since properties
9184 // are "dynamic by default".
9185 if (Dynamic)
9186 S += ",D";
9187
9189 S += ",N";
9190
9192 S += ",G";
9193 S += PD->getGetterName().getAsString();
9194 }
9195
9197 S += ",S";
9198 S += PD->getSetterName().getAsString();
9199 }
9200
9201 if (SynthesizePID) {
9202 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9203 S += ",V";
9204 S += OID->getNameAsString();
9205 }
9206
9207 // FIXME: OBJCGC: weak & strong
9208 return S;
9209}
9210
9211/// getLegacyIntegralTypeEncoding -
9212/// Another legacy compatibility encoding: 32-bit longs are encoded as
9213/// 'l' or 'L' , but not always. For typedefs, we need to use
9214/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9216 if (PointeeTy->getAs<TypedefType>()) {
9217 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9218 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9219 PointeeTy = UnsignedIntTy;
9220 else
9221 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9222 PointeeTy = IntTy;
9223 }
9224 }
9225}
9226
9228 const FieldDecl *Field,
9229 QualType *NotEncodedT) const {
9230 // We follow the behavior of gcc, expanding structures which are
9231 // directly pointed to, and expanding embedded structures. Note that
9232 // these rules are sufficient to prevent recursive encoding of the
9233 // same type.
9234 getObjCEncodingForTypeImpl(T, S,
9235 ObjCEncOptions()
9236 .setExpandPointedToStructures()
9237 .setExpandStructures()
9238 .setIsOutermostType(),
9239 Field, NotEncodedT);
9240}
9241
9243 std::string& S) const {
9244 // Encode result type.
9245 // GCC has some special rules regarding encoding of properties which
9246 // closely resembles encoding of ivars.
9247 getObjCEncodingForTypeImpl(T, S,
9248 ObjCEncOptions()
9249 .setExpandPointedToStructures()
9250 .setExpandStructures()
9251 .setIsOutermostType()
9252 .setEncodingProperty(),
9253 /*Field=*/nullptr);
9254}
9255
9257 const BuiltinType *BT) {
9259 switch (kind) {
9260 case BuiltinType::Void: return 'v';
9261 case BuiltinType::Bool: return 'B';
9262 case BuiltinType::Char8:
9263 case BuiltinType::Char_U:
9264 case BuiltinType::UChar: return 'C';
9265 case BuiltinType::Char16:
9266 case BuiltinType::UShort: return 'S';
9267 case BuiltinType::Char32:
9268 case BuiltinType::UInt: return 'I';
9269 case BuiltinType::ULong:
9270 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9271 case BuiltinType::UInt128: return 'T';
9272 case BuiltinType::ULongLong: return 'Q';
9273 case BuiltinType::Char_S:
9274 case BuiltinType::SChar: return 'c';
9275 case BuiltinType::Short: return 's';
9276 case BuiltinType::WChar_S:
9277 case BuiltinType::WChar_U:
9278 case BuiltinType::Int: return 'i';
9279 case BuiltinType::Long:
9280 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9281 case BuiltinType::LongLong: return 'q';
9282 case BuiltinType::Int128: return 't';
9283 case BuiltinType::Float: return 'f';
9284 case BuiltinType::Double: return 'd';
9285 case BuiltinType::LongDouble: return 'D';
9286 case BuiltinType::NullPtr: return '*'; // like char*
9287
9288 case BuiltinType::BFloat16:
9289 case BuiltinType::Float16:
9290 case BuiltinType::Float128:
9291 case BuiltinType::Ibm128:
9292 case BuiltinType::Half:
9293 case BuiltinType::ShortAccum:
9294 case BuiltinType::Accum:
9295 case BuiltinType::LongAccum:
9296 case BuiltinType::UShortAccum:
9297 case BuiltinType::UAccum:
9298 case BuiltinType::ULongAccum:
9299 case BuiltinType::ShortFract:
9300 case BuiltinType::Fract:
9301 case BuiltinType::LongFract:
9302 case BuiltinType::UShortFract:
9303 case BuiltinType::UFract:
9304 case BuiltinType::ULongFract:
9305 case BuiltinType::SatShortAccum:
9306 case BuiltinType::SatAccum:
9307 case BuiltinType::SatLongAccum:
9308 case BuiltinType::SatUShortAccum:
9309 case BuiltinType::SatUAccum:
9310 case BuiltinType::SatULongAccum:
9311 case BuiltinType::SatShortFract:
9312 case BuiltinType::SatFract:
9313 case BuiltinType::SatLongFract:
9314 case BuiltinType::SatUShortFract:
9315 case BuiltinType::SatUFract:
9316 case BuiltinType::SatULongFract:
9317 // FIXME: potentially need @encodes for these!
9318 return ' ';
9319
9320#define SVE_TYPE(Name, Id, SingletonId) \
9321 case BuiltinType::Id:
9322#include "clang/Basic/AArch64ACLETypes.def"
9323#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9324#include "clang/Basic/RISCVVTypes.def"
9325#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9326#include "clang/Basic/WebAssemblyReferenceTypes.def"
9327#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9328#include "clang/Basic/AMDGPUTypes.def"
9329#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9330#include "clang/Basic/SPIRVTypes.def"
9331 {
9332 DiagnosticsEngine &Diags = C->getDiagnostics();
9333 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9334 << QualType(BT, 0);
9335 return ' ';
9336 }
9337
9338 case BuiltinType::ObjCId:
9339 case BuiltinType::ObjCClass:
9340 case BuiltinType::ObjCSel:
9341 llvm_unreachable("@encoding ObjC primitive type");
9342
9343 // OpenCL and placeholder types don't need @encodings.
9344#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9345 case BuiltinType::Id:
9346#include "clang/Basic/OpenCLImageTypes.def"
9347#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9348 case BuiltinType::Id:
9349#include "clang/Basic/OpenCLExtensionTypes.def"
9350 case BuiltinType::OCLEvent:
9351 case BuiltinType::OCLClkEvent:
9352 case BuiltinType::OCLQueue:
9353 case BuiltinType::OCLReserveID:
9354 case BuiltinType::OCLSampler:
9355 case BuiltinType::Dependent:
9356#define PPC_VECTOR_TYPE(Name, Id, Size) \
9357 case BuiltinType::Id:
9358#include "clang/Basic/PPCTypes.def"
9359#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9360#include "clang/Basic/HLSLIntangibleTypes.def"
9361#define BUILTIN_TYPE(KIND, ID)
9362#define PLACEHOLDER_TYPE(KIND, ID) \
9363 case BuiltinType::KIND:
9364#include "clang/AST/BuiltinTypes.def"
9365 llvm_unreachable("invalid builtin type for @encode");
9366 }
9367 llvm_unreachable("invalid BuiltinType::Kind value");
9368}
9369
9370static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9372
9373 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9374 if (!Enum->isFixed())
9375 return 'i';
9376
9377 // The encoding of a fixed enum type matches its fixed underlying type.
9378 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9380}
9381
9382static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9383 QualType T, const FieldDecl *FD) {
9384 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9385 S += 'b';
9386 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9387 // The GNU runtime requires more information; bitfields are encoded as b,
9388 // then the offset (in bits) of the first element, then the type of the
9389 // bitfield, then the size in bits. For example, in this structure:
9390 //
9391 // struct
9392 // {
9393 // int integer;
9394 // int flags:2;
9395 // };
9396 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9397 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9398 // information is not especially sensible, but we're stuck with it for
9399 // compatibility with GCC, although providing it breaks anything that
9400 // actually uses runtime introspection and wants to work on both runtimes...
9401 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9402 uint64_t Offset;
9403
9404 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9405 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9406 } else {
9407 const RecordDecl *RD = FD->getParent();
9408 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9409 Offset = RL.getFieldOffset(FD->getFieldIndex());
9410 }
9411
9412 S += llvm::utostr(Offset);
9413
9414 if (const auto *ET = T->getAsCanonical<EnumType>())
9415 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9416 else {
9417 const auto *BT = T->castAs<BuiltinType>();
9418 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9419 }
9420 }
9421 S += llvm::utostr(FD->getBitWidthValue());
9422}
9423
9424// Helper function for determining whether the encoded type string would include
9425// a template specialization type.
9427 bool VisitBasesAndFields) {
9428 T = T->getBaseElementTypeUnsafe();
9429
9430 if (auto *PT = T->getAs<PointerType>())
9432 PT->getPointeeType().getTypePtr(), false);
9433
9434 auto *CXXRD = T->getAsCXXRecordDecl();
9435
9436 if (!CXXRD)
9437 return false;
9438
9440 return true;
9441
9442 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9443 return false;
9444
9445 for (const auto &B : CXXRD->bases())
9446 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9447 true))
9448 return true;
9449
9450 for (auto *FD : CXXRD->fields())
9451 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9452 true))
9453 return true;
9454
9455 return false;
9456}
9457
9458// FIXME: Use SmallString for accumulating string.
9459void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9460 const ObjCEncOptions Options,
9461 const FieldDecl *FD,
9462 QualType *NotEncodedT) const {
9464 switch (CT->getTypeClass()) {
9465 case Type::Builtin:
9466 case Type::Enum:
9467 if (FD && FD->isBitField())
9468 return EncodeBitField(this, S, T, FD);
9469 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9470 S += getObjCEncodingForPrimitiveType(this, BT);
9471 else
9472 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9473 return;
9474
9475 case Type::Complex:
9476 S += 'j';
9477 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9478 ObjCEncOptions(),
9479 /*Field=*/nullptr);
9480 return;
9481
9482 case Type::Atomic:
9483 S += 'A';
9484 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9485 ObjCEncOptions(),
9486 /*Field=*/nullptr);
9487 return;
9488
9489 // encoding for pointer or reference types.
9490 case Type::Pointer:
9491 case Type::LValueReference:
9492 case Type::RValueReference: {
9493 QualType PointeeTy;
9494 if (isa<PointerType>(CT)) {
9495 const auto *PT = T->castAs<PointerType>();
9496 if (PT->isObjCSelType()) {
9497 S += ':';
9498 return;
9499 }
9500 PointeeTy = PT->getPointeeType();
9501 } else {
9502 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9503 }
9504
9505 bool isReadOnly = false;
9506 // For historical/compatibility reasons, the read-only qualifier of the
9507 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9508 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9509 // Also, do not emit the 'r' for anything but the outermost type!
9510 if (T->getAs<TypedefType>()) {
9511 if (Options.IsOutermostType() && T.isConstQualified()) {
9512 isReadOnly = true;
9513 S += 'r';
9514 }
9515 } else if (Options.IsOutermostType()) {
9516 QualType P = PointeeTy;
9517 while (auto PT = P->getAs<PointerType>())
9518 P = PT->getPointeeType();
9519 if (P.isConstQualified()) {
9520 isReadOnly = true;
9521 S += 'r';
9522 }
9523 }
9524 if (isReadOnly) {
9525 // Another legacy compatibility encoding. Some ObjC qualifier and type
9526 // combinations need to be rearranged.
9527 // Rewrite "in const" from "nr" to "rn"
9528 if (StringRef(S).ends_with("nr"))
9529 S.replace(S.end()-2, S.end(), "rn");
9530 }
9531
9532 if (PointeeTy->isCharType()) {
9533 // char pointer types should be encoded as '*' unless it is a
9534 // type that has been typedef'd to 'BOOL'.
9535 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9536 S += '*';
9537 return;
9538 }
9539 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9540 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9541 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9542 if (II == &Idents.get("objc_class")) {
9543 S += '#';
9544 return;
9545 }
9546 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9547 if (II == &Idents.get("objc_object")) {
9548 S += '@';
9549 return;
9550 }
9551 // If the encoded string for the class includes template names, just emit
9552 // "^v" for pointers to the class.
9553 if (getLangOpts().CPlusPlus &&
9554 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9556 RTy, Options.ExpandPointedToStructures()))) {
9557 S += "^v";
9558 return;
9559 }
9560 // fall through...
9561 }
9562 S += '^';
9564
9565 ObjCEncOptions NewOptions;
9566 if (Options.ExpandPointedToStructures())
9567 NewOptions.setExpandStructures();
9568 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9569 /*Field=*/nullptr, NotEncodedT);
9570 return;
9571 }
9572
9573 case Type::ConstantArray:
9574 case Type::IncompleteArray:
9575 case Type::VariableArray: {
9576 const auto *AT = cast<ArrayType>(CT);
9577
9578 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9579 // Incomplete arrays are encoded as a pointer to the array element.
9580 S += '^';
9581
9582 getObjCEncodingForTypeImpl(
9583 AT->getElementType(), S,
9584 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9585 } else {
9586 S += '[';
9587
9588 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9589 S += llvm::utostr(CAT->getZExtSize());
9590 else {
9591 //Variable length arrays are encoded as a regular array with 0 elements.
9593 "Unknown array type!");
9594 S += '0';
9595 }
9596
9597 getObjCEncodingForTypeImpl(
9598 AT->getElementType(), S,
9599 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9600 NotEncodedT);
9601 S += ']';
9602 }
9603 return;
9604 }
9605
9606 case Type::FunctionNoProto:
9607 case Type::FunctionProto:
9608 S += '?';
9609 return;
9610
9611 case Type::Record: {
9612 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9613 S += RDecl->isUnion() ? '(' : '{';
9614 // Anonymous structures print as '?'
9615 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9616 S += II->getName();
9617 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9618 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9619 llvm::raw_string_ostream OS(S);
9620 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9622 }
9623 } else {
9624 S += '?';
9625 }
9626 if (Options.ExpandStructures()) {
9627 S += '=';
9628 if (!RDecl->isUnion()) {
9629 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9630 } else {
9631 for (const auto *Field : RDecl->fields()) {
9632 if (FD) {
9633 S += '"';
9634 S += Field->getNameAsString();
9635 S += '"';
9636 }
9637
9638 // Special case bit-fields.
9639 if (Field->isBitField()) {
9640 getObjCEncodingForTypeImpl(Field->getType(), S,
9641 ObjCEncOptions().setExpandStructures(),
9642 Field);
9643 } else {
9644 QualType qt = Field->getType();
9646 getObjCEncodingForTypeImpl(
9647 qt, S,
9648 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9649 NotEncodedT);
9650 }
9651 }
9652 }
9653 }
9654 S += RDecl->isUnion() ? ')' : '}';
9655 return;
9656 }
9657
9658 case Type::BlockPointer: {
9659 const auto *BT = T->castAs<BlockPointerType>();
9660 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9661 if (Options.EncodeBlockParameters()) {
9662 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9663
9664 S += '<';
9665 // Block return type
9666 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9667 Options.forComponentType(), FD, NotEncodedT);
9668 // Block self
9669 S += "@?";
9670 // Block parameters
9671 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9672 for (const auto &I : FPT->param_types())
9673 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9674 NotEncodedT);
9675 }
9676 S += '>';
9677 }
9678 return;
9679 }
9680
9681 case Type::ObjCObject: {
9682 // hack to match legacy encoding of *id and *Class
9683 QualType Ty = getObjCObjectPointerType(CT);
9684 if (Ty->isObjCIdType()) {
9685 S += "{objc_object=}";
9686 return;
9687 }
9688 else if (Ty->isObjCClassType()) {
9689 S += "{objc_class=}";
9690 return;
9691 }
9692 // TODO: Double check to make sure this intentionally falls through.
9693 [[fallthrough]];
9694 }
9695
9696 case Type::ObjCInterface: {
9697 // Ignore protocol qualifiers when mangling at this level.
9698 // @encode(class_name)
9699 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9700 S += '{';
9701 S += OI->getObjCRuntimeNameAsString();
9702 if (Options.ExpandStructures()) {
9703 S += '=';
9704 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9705 DeepCollectObjCIvars(OI, true, Ivars);
9706 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9707 const FieldDecl *Field = Ivars[i];
9708 if (Field->isBitField())
9709 getObjCEncodingForTypeImpl(Field->getType(), S,
9710 ObjCEncOptions().setExpandStructures(),
9711 Field);
9712 else
9713 getObjCEncodingForTypeImpl(Field->getType(), S,
9714 ObjCEncOptions().setExpandStructures(), FD,
9715 NotEncodedT);
9716 }
9717 }
9718 S += '}';
9719 return;
9720 }
9721
9722 case Type::ObjCObjectPointer: {
9723 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9724 if (OPT->isObjCIdType()) {
9725 S += '@';
9726 return;
9727 }
9728
9729 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9730 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9731 // Since this is a binary compatibility issue, need to consult with
9732 // runtime folks. Fortunately, this is a *very* obscure construct.
9733 S += '#';
9734 return;
9735 }
9736
9737 if (OPT->isObjCQualifiedIdType()) {
9738 getObjCEncodingForTypeImpl(
9739 getObjCIdType(), S,
9740 Options.keepingOnly(ObjCEncOptions()
9741 .setExpandPointedToStructures()
9742 .setExpandStructures()),
9743 FD);
9744 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9745 // Note that we do extended encoding of protocol qualifier list
9746 // Only when doing ivar or property encoding.
9747 S += '"';
9748 for (const auto *I : OPT->quals()) {
9749 S += '<';
9750 S += I->getObjCRuntimeNameAsString();
9751 S += '>';
9752 }
9753 S += '"';
9754 }
9755 return;
9756 }
9757
9758 S += '@';
9759 if (OPT->getInterfaceDecl() &&
9760 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9761 S += '"';
9762 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9763 for (const auto *I : OPT->quals()) {
9764 S += '<';
9765 S += I->getObjCRuntimeNameAsString();
9766 S += '>';
9767 }
9768 S += '"';
9769 }
9770 return;
9771 }
9772
9773 // gcc just blithely ignores member pointers.
9774 // FIXME: we should do better than that. 'M' is available.
9775 case Type::MemberPointer:
9776 // This matches gcc's encoding, even though technically it is insufficient.
9777 //FIXME. We should do a better job than gcc.
9778 case Type::Vector:
9779 case Type::ExtVector:
9780 // Until we have a coherent encoding of these three types, issue warning.
9781 if (NotEncodedT)
9782 *NotEncodedT = T;
9783 return;
9784
9785 case Type::ConstantMatrix:
9786 if (NotEncodedT)
9787 *NotEncodedT = T;
9788 return;
9789
9790 case Type::BitInt:
9791 if (NotEncodedT)
9792 *NotEncodedT = T;
9793 return;
9794
9795 // We could see an undeduced auto type here during error recovery.
9796 // Just ignore it.
9797 case Type::Auto:
9798 case Type::DeducedTemplateSpecialization:
9799 return;
9800
9801 case Type::HLSLAttributedResource:
9802 case Type::HLSLInlineSpirv:
9803 case Type::OverflowBehavior:
9804 llvm_unreachable("unexpected type");
9805
9806 case Type::ArrayParameter:
9807 case Type::Pipe:
9808#define ABSTRACT_TYPE(KIND, BASE)
9809#define TYPE(KIND, BASE)
9810#define DEPENDENT_TYPE(KIND, BASE) \
9811 case Type::KIND:
9812#define NON_CANONICAL_TYPE(KIND, BASE) \
9813 case Type::KIND:
9814#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9815 case Type::KIND:
9816#include "clang/AST/TypeNodes.inc"
9817 llvm_unreachable("@encode for dependent type!");
9818 }
9819 llvm_unreachable("bad type kind!");
9820}
9821
9822void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9823 std::string &S,
9824 const FieldDecl *FD,
9825 bool includeVBases,
9826 QualType *NotEncodedT) const {
9827 assert(RDecl && "Expected non-null RecordDecl");
9828 assert(!RDecl->isUnion() && "Should not be called for unions");
9829 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9830 return;
9831
9832 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9833 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9834 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9835
9836 if (CXXRec) {
9837 for (const auto &BI : CXXRec->bases()) {
9838 if (!BI.isVirtual()) {
9839 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9840 if (base->isEmpty())
9841 continue;
9842 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9843 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9844 std::make_pair(offs, base));
9845 }
9846 }
9847 }
9848
9849 for (FieldDecl *Field : RDecl->fields()) {
9850 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9851 continue;
9852 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9853 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9854 std::make_pair(offs, Field));
9855 }
9856
9857 if (CXXRec && includeVBases) {
9858 for (const auto &BI : CXXRec->vbases()) {
9859 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9860 if (base->isEmpty())
9861 continue;
9862 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9863 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9864 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9865 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9866 std::make_pair(offs, base));
9867 }
9868 }
9869
9870 CharUnits size;
9871 if (CXXRec) {
9872 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9873 } else {
9874 size = layout.getSize();
9875 }
9876
9877#ifndef NDEBUG
9878 uint64_t CurOffs = 0;
9879#endif
9880 std::multimap<uint64_t, NamedDecl *>::iterator
9881 CurLayObj = FieldOrBaseOffsets.begin();
9882
9883 if (CXXRec && CXXRec->isDynamicClass() &&
9884 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9885 if (FD) {
9886 S += "\"_vptr$";
9887 std::string recname = CXXRec->getNameAsString();
9888 if (recname.empty()) recname = "?";
9889 S += recname;
9890 S += '"';
9891 }
9892 S += "^^?";
9893#ifndef NDEBUG
9894 CurOffs += getTypeSize(VoidPtrTy);
9895#endif
9896 }
9897
9898 if (!RDecl->hasFlexibleArrayMember()) {
9899 // Mark the end of the structure.
9900 uint64_t offs = toBits(size);
9901 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9902 std::make_pair(offs, nullptr));
9903 }
9904
9905 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9906#ifndef NDEBUG
9907 assert(CurOffs <= CurLayObj->first);
9908 if (CurOffs < CurLayObj->first) {
9909 uint64_t padding = CurLayObj->first - CurOffs;
9910 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9911 // packing/alignment of members is different that normal, in which case
9912 // the encoding will be out-of-sync with the real layout.
9913 // If the runtime switches to just consider the size of types without
9914 // taking into account alignment, we could make padding explicit in the
9915 // encoding (e.g. using arrays of chars). The encoding strings would be
9916 // longer then though.
9917 CurOffs += padding;
9918 }
9919#endif
9920
9921 NamedDecl *dcl = CurLayObj->second;
9922 if (!dcl)
9923 break; // reached end of structure.
9924
9925 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9926 // We expand the bases without their virtual bases since those are going
9927 // in the initial structure. Note that this differs from gcc which
9928 // expands virtual bases each time one is encountered in the hierarchy,
9929 // making the encoding type bigger than it really is.
9930 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9931 NotEncodedT);
9932 assert(!base->isEmpty());
9933#ifndef NDEBUG
9934 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9935#endif
9936 } else {
9937 const auto *field = cast<FieldDecl>(dcl);
9938 if (FD) {
9939 S += '"';
9940 S += field->getNameAsString();
9941 S += '"';
9942 }
9943
9944 if (field->isBitField()) {
9945 EncodeBitField(this, S, field->getType(), field);
9946#ifndef NDEBUG
9947 CurOffs += field->getBitWidthValue();
9948#endif
9949 } else {
9950 QualType qt = field->getType();
9952 getObjCEncodingForTypeImpl(
9953 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9954 FD, NotEncodedT);
9955#ifndef NDEBUG
9956 CurOffs += getTypeSize(field->getType());
9957#endif
9958 }
9959 }
9960 }
9961}
9962
9964 std::string& S) const {
9965 if (QT & Decl::OBJC_TQ_In)
9966 S += 'n';
9967 if (QT & Decl::OBJC_TQ_Inout)
9968 S += 'N';
9969 if (QT & Decl::OBJC_TQ_Out)
9970 S += 'o';
9971 if (QT & Decl::OBJC_TQ_Bycopy)
9972 S += 'O';
9973 if (QT & Decl::OBJC_TQ_Byref)
9974 S += 'R';
9975 if (QT & Decl::OBJC_TQ_Oneway)
9976 S += 'V';
9977}
9978
9980 if (!ObjCIdDecl) {
9983 ObjCIdDecl = buildImplicitTypedef(T, "id");
9984 }
9985 return ObjCIdDecl;
9986}
9987
9989 if (!ObjCSelDecl) {
9991 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
9992 }
9993 return ObjCSelDecl;
9994}
9995
9997 if (!ObjCClassDecl) {
10000 ObjCClassDecl = buildImplicitTypedef(T, "Class");
10001 }
10002 return ObjCClassDecl;
10003}
10004
10006 if (!ObjCProtocolClassDecl) {
10007 ObjCProtocolClassDecl
10010 &Idents.get("Protocol"),
10011 /*typeParamList=*/nullptr,
10012 /*PrevDecl=*/nullptr,
10013 SourceLocation(), true);
10014 }
10015
10016 return ObjCProtocolClassDecl;
10017}
10018
10020 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10021 return PointerAuthQualifier();
10023 getLangOpts().PointerAuthObjcInterfaceSelKey,
10024 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10026 /*isIsaPointer=*/false,
10027 /*authenticatesNullValues=*/false);
10028}
10029
10030//===----------------------------------------------------------------------===//
10031// __builtin_va_list Construction Functions
10032//===----------------------------------------------------------------------===//
10033
10035 StringRef Name) {
10036 // typedef char* __builtin[_ms]_va_list;
10037 QualType T = Context->getPointerType(Context->CharTy);
10038 return Context->buildImplicitTypedef(T, Name);
10039}
10040
10042 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10043}
10044
10046 // typedef char *__builtin_zos_va_list[2];
10047 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10048 QualType T = Context->getPointerType(Context->CharTy);
10049 QualType ArrayType = Context->getConstantArrayType(
10050 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10051 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10052}
10053
10055 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10056}
10057
10059 // typedef void* __builtin_va_list;
10060 QualType T = Context->getPointerType(Context->VoidTy);
10061 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10062}
10063
10064static TypedefDecl *
10066 // struct __va_list
10067 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10068 if (Context->getLangOpts().CPlusPlus) {
10069 // namespace std { struct __va_list {
10070 auto *NS = NamespaceDecl::Create(
10071 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10072 /*Inline=*/false, SourceLocation(), SourceLocation(),
10073 &Context->Idents.get("std"),
10074 /*PrevDecl=*/nullptr, /*Nested=*/false);
10075 NS->setImplicit();
10077 }
10078
10079 VaListTagDecl->startDefinition();
10080
10081 const size_t NumFields = 5;
10082 QualType FieldTypes[NumFields];
10083 const char *FieldNames[NumFields];
10084
10085 // void *__stack;
10086 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10087 FieldNames[0] = "__stack";
10088
10089 // void *__gr_top;
10090 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10091 FieldNames[1] = "__gr_top";
10092
10093 // void *__vr_top;
10094 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10095 FieldNames[2] = "__vr_top";
10096
10097 // int __gr_offs;
10098 FieldTypes[3] = Context->IntTy;
10099 FieldNames[3] = "__gr_offs";
10100
10101 // int __vr_offs;
10102 FieldTypes[4] = Context->IntTy;
10103 FieldNames[4] = "__vr_offs";
10104
10105 // Create fields
10106 for (unsigned i = 0; i < NumFields; ++i) {
10107 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10111 &Context->Idents.get(FieldNames[i]),
10112 FieldTypes[i], /*TInfo=*/nullptr,
10113 /*BitWidth=*/nullptr,
10114 /*Mutable=*/false,
10115 ICIS_NoInit);
10116 Field->setAccess(AS_public);
10117 VaListTagDecl->addDecl(Field);
10118 }
10119 VaListTagDecl->completeDefinition();
10120 Context->VaListTagDecl = VaListTagDecl;
10121 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10122
10123 // } __builtin_va_list;
10124 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10125}
10126
10128 // typedef struct __va_list_tag {
10130
10131 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10132 VaListTagDecl->startDefinition();
10133
10134 const size_t NumFields = 5;
10135 QualType FieldTypes[NumFields];
10136 const char *FieldNames[NumFields];
10137
10138 // unsigned char gpr;
10139 FieldTypes[0] = Context->UnsignedCharTy;
10140 FieldNames[0] = "gpr";
10141
10142 // unsigned char fpr;
10143 FieldTypes[1] = Context->UnsignedCharTy;
10144 FieldNames[1] = "fpr";
10145
10146 // unsigned short reserved;
10147 FieldTypes[2] = Context->UnsignedShortTy;
10148 FieldNames[2] = "reserved";
10149
10150 // void* overflow_arg_area;
10151 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10152 FieldNames[3] = "overflow_arg_area";
10153
10154 // void* reg_save_area;
10155 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10156 FieldNames[4] = "reg_save_area";
10157
10158 // Create fields
10159 for (unsigned i = 0; i < NumFields; ++i) {
10160 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10163 &Context->Idents.get(FieldNames[i]),
10164 FieldTypes[i], /*TInfo=*/nullptr,
10165 /*BitWidth=*/nullptr,
10166 /*Mutable=*/false,
10167 ICIS_NoInit);
10168 Field->setAccess(AS_public);
10169 VaListTagDecl->addDecl(Field);
10170 }
10171 VaListTagDecl->completeDefinition();
10172 Context->VaListTagDecl = VaListTagDecl;
10173 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10174
10175 // } __va_list_tag;
10176 TypedefDecl *VaListTagTypedefDecl =
10177 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10178
10179 QualType VaListTagTypedefType =
10180 Context->getTypedefType(ElaboratedTypeKeyword::None,
10181 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10182
10183 // typedef __va_list_tag __builtin_va_list[1];
10184 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10185 QualType VaListTagArrayType = Context->getConstantArrayType(
10186 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10187 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10188}
10189
10190static TypedefDecl *
10192 // struct __va_list_tag {
10194 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10195 VaListTagDecl->startDefinition();
10196
10197 const size_t NumFields = 4;
10198 QualType FieldTypes[NumFields];
10199 const char *FieldNames[NumFields];
10200
10201 // unsigned gp_offset;
10202 FieldTypes[0] = Context->UnsignedIntTy;
10203 FieldNames[0] = "gp_offset";
10204
10205 // unsigned fp_offset;
10206 FieldTypes[1] = Context->UnsignedIntTy;
10207 FieldNames[1] = "fp_offset";
10208
10209 // void* overflow_arg_area;
10210 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10211 FieldNames[2] = "overflow_arg_area";
10212
10213 // void* reg_save_area;
10214 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10215 FieldNames[3] = "reg_save_area";
10216
10217 // Create fields
10218 for (unsigned i = 0; i < NumFields; ++i) {
10219 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10223 &Context->Idents.get(FieldNames[i]),
10224 FieldTypes[i], /*TInfo=*/nullptr,
10225 /*BitWidth=*/nullptr,
10226 /*Mutable=*/false,
10227 ICIS_NoInit);
10228 Field->setAccess(AS_public);
10229 VaListTagDecl->addDecl(Field);
10230 }
10231 VaListTagDecl->completeDefinition();
10232 Context->VaListTagDecl = VaListTagDecl;
10233 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10234
10235 // };
10236
10237 // typedef struct __va_list_tag __builtin_va_list[1];
10238 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10239 QualType VaListTagArrayType = Context->getConstantArrayType(
10240 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10241 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10242}
10243
10244static TypedefDecl *
10246 // struct __va_list
10247 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10248 if (Context->getLangOpts().CPlusPlus) {
10249 // namespace std { struct __va_list {
10250 NamespaceDecl *NS;
10251 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10252 Context->getTranslationUnitDecl(),
10253 /*Inline=*/false, SourceLocation(),
10254 SourceLocation(), &Context->Idents.get("std"),
10255 /*PrevDecl=*/nullptr, /*Nested=*/false);
10256 NS->setImplicit();
10257 VaListDecl->setDeclContext(NS);
10258 }
10259
10260 VaListDecl->startDefinition();
10261
10262 // void * __ap;
10263 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10264 VaListDecl,
10267 &Context->Idents.get("__ap"),
10268 Context->getPointerType(Context->VoidTy),
10269 /*TInfo=*/nullptr,
10270 /*BitWidth=*/nullptr,
10271 /*Mutable=*/false,
10272 ICIS_NoInit);
10273 Field->setAccess(AS_public);
10274 VaListDecl->addDecl(Field);
10275
10276 // };
10277 VaListDecl->completeDefinition();
10278 Context->VaListTagDecl = VaListDecl;
10279
10280 // typedef struct __va_list __builtin_va_list;
10281 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10282 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10283}
10284
10285static TypedefDecl *
10287 // struct __va_list_tag {
10289 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10290 VaListTagDecl->startDefinition();
10291
10292 const size_t NumFields = 4;
10293 QualType FieldTypes[NumFields];
10294 const char *FieldNames[NumFields];
10295
10296 // long __gpr;
10297 FieldTypes[0] = Context->LongTy;
10298 FieldNames[0] = "__gpr";
10299
10300 // long __fpr;
10301 FieldTypes[1] = Context->LongTy;
10302 FieldNames[1] = "__fpr";
10303
10304 // void *__overflow_arg_area;
10305 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10306 FieldNames[2] = "__overflow_arg_area";
10307
10308 // void *__reg_save_area;
10309 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10310 FieldNames[3] = "__reg_save_area";
10311
10312 // Create fields
10313 for (unsigned i = 0; i < NumFields; ++i) {
10314 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10318 &Context->Idents.get(FieldNames[i]),
10319 FieldTypes[i], /*TInfo=*/nullptr,
10320 /*BitWidth=*/nullptr,
10321 /*Mutable=*/false,
10322 ICIS_NoInit);
10323 Field->setAccess(AS_public);
10324 VaListTagDecl->addDecl(Field);
10325 }
10326 VaListTagDecl->completeDefinition();
10327 Context->VaListTagDecl = VaListTagDecl;
10328 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10329
10330 // };
10331
10332 // typedef __va_list_tag __builtin_va_list[1];
10333 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10334 QualType VaListTagArrayType = Context->getConstantArrayType(
10335 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10336
10337 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10338}
10339
10341 // typedef struct __va_list_tag {
10343 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10344 VaListTagDecl->startDefinition();
10345
10346 const size_t NumFields = 3;
10347 QualType FieldTypes[NumFields];
10348 const char *FieldNames[NumFields];
10349
10350 // void *CurrentSavedRegisterArea;
10351 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10352 FieldNames[0] = "__current_saved_reg_area_pointer";
10353
10354 // void *SavedRegAreaEnd;
10355 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10356 FieldNames[1] = "__saved_reg_area_end_pointer";
10357
10358 // void *OverflowArea;
10359 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10360 FieldNames[2] = "__overflow_area_pointer";
10361
10362 // Create fields
10363 for (unsigned i = 0; i < NumFields; ++i) {
10365 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10366 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10367 /*TInfo=*/nullptr,
10368 /*BitWidth=*/nullptr,
10369 /*Mutable=*/false, ICIS_NoInit);
10370 Field->setAccess(AS_public);
10371 VaListTagDecl->addDecl(Field);
10372 }
10373 VaListTagDecl->completeDefinition();
10374 Context->VaListTagDecl = VaListTagDecl;
10375 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10376
10377 // } __va_list_tag;
10378 TypedefDecl *VaListTagTypedefDecl =
10379 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10380
10381 QualType VaListTagTypedefType =
10382 Context->getTypedefType(ElaboratedTypeKeyword::None,
10383 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10384
10385 // typedef __va_list_tag __builtin_va_list[1];
10386 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10387 QualType VaListTagArrayType = Context->getConstantArrayType(
10388 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10389
10390 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10391}
10392
10393static TypedefDecl *
10395 // typedef struct __va_list_tag {
10396 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10397
10398 VaListTagDecl->startDefinition();
10399
10400 // int* __va_stk;
10401 // int* __va_reg;
10402 // int __va_ndx;
10403 constexpr size_t NumFields = 3;
10404 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10405 Context->getPointerType(Context->IntTy),
10406 Context->IntTy};
10407 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10408
10409 // Create fields
10410 for (unsigned i = 0; i < NumFields; ++i) {
10413 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10414 /*BitWidth=*/nullptr,
10415 /*Mutable=*/false, ICIS_NoInit);
10416 Field->setAccess(AS_public);
10417 VaListTagDecl->addDecl(Field);
10418 }
10419 VaListTagDecl->completeDefinition();
10420 Context->VaListTagDecl = VaListTagDecl;
10421 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10422
10423 // } __va_list_tag;
10424 TypedefDecl *VaListTagTypedefDecl =
10425 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10426
10427 return VaListTagTypedefDecl;
10428}
10429
10432 switch (Kind) {
10434 return CreateCharPtrBuiltinVaListDecl(Context);
10436 return CreateVoidPtrBuiltinVaListDecl(Context);
10438 return CreateAArch64ABIBuiltinVaListDecl(Context);
10440 return CreatePowerABIBuiltinVaListDecl(Context);
10442 return CreateX86_64ABIBuiltinVaListDecl(Context);
10444 return CreateAAPCSABIBuiltinVaListDecl(Context);
10446 return CreateSystemZBuiltinVaListDecl(Context);
10448 return CreateHexagonBuiltinVaListDecl(Context);
10450 return CreateXtensaABIBuiltinVaListDecl(Context);
10451 }
10452
10453 llvm_unreachable("Unhandled __builtin_va_list type kind");
10454}
10455
10457 if (!BuiltinVaListDecl) {
10458 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10459 assert(BuiltinVaListDecl->isImplicit());
10460 }
10461
10462 return BuiltinVaListDecl;
10463}
10464
10466 // Force the creation of VaListTagDecl by building the __builtin_va_list
10467 // declaration.
10468 if (!VaListTagDecl)
10469 (void)getBuiltinVaListDecl();
10470
10471 return VaListTagDecl;
10472}
10473
10475 if (!BuiltinMSVaListDecl)
10476 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10477
10478 return BuiltinMSVaListDecl;
10479}
10480
10482 if (!BuiltinZOSVaListDecl)
10483 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10484
10485 return BuiltinZOSVaListDecl;
10486}
10487
10489 // Allow redecl custom type checking builtin for HLSL.
10490 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10491 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10492 return true;
10493 // Allow redecl custom type checking builtin for SPIR-V.
10494 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10495 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10496 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10497 return true;
10498 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10499}
10500
10502 assert(ObjCConstantStringType.isNull() &&
10503 "'NSConstantString' type already set!");
10504
10505 ObjCConstantStringType = getObjCInterfaceType(Decl);
10506}
10507
10508/// Retrieve the template name that corresponds to a non-empty
10509/// lookup.
10512 UnresolvedSetIterator End) const {
10513 unsigned size = End - Begin;
10514 assert(size > 1 && "set is not overloaded!");
10515
10516 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10517 size * sizeof(FunctionTemplateDecl*));
10518 auto *OT = new (memory) OverloadedTemplateStorage(size);
10519
10520 NamedDecl **Storage = OT->getStorage();
10521 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10522 NamedDecl *D = *I;
10523 assert(isa<FunctionTemplateDecl>(D) ||
10527 *Storage++ = D;
10528 }
10529
10530 return TemplateName(OT);
10531}
10532
10533/// Retrieve a template name representing an unqualified-id that has been
10534/// assumed to name a template for ADL purposes.
10536 auto *OT = new (*this) AssumedTemplateStorage(Name);
10537 return TemplateName(OT);
10538}
10539
10540/// Retrieve the template name that represents a qualified
10541/// template name such as \c std::vector.
10543 bool TemplateKeyword,
10544 TemplateName Template) const {
10545 assert(Template.getKind() == TemplateName::Template ||
10547
10548 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10549 assert(!Qualifier && "unexpected qualified template template parameter");
10550 assert(TemplateKeyword == false);
10551 return Template;
10552 }
10553
10554 // FIXME: Canonicalization?
10555 llvm::FoldingSetNodeID ID;
10556 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10557
10558 void *InsertPos = nullptr;
10560 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
10561 if (!QTN) {
10562 QTN = new (*this, alignof(QualifiedTemplateName))
10563 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10564 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
10565 }
10566
10567 return TemplateName(QTN);
10568}
10569
10570/// Retrieve the template name that represents a dependent
10571/// template name such as \c MetaFun::template operator+.
10574 llvm::FoldingSetNodeID ID;
10575 S.Profile(ID);
10576
10577 void *InsertPos = nullptr;
10578 if (DependentTemplateName *QTN =
10579 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos))
10580 return TemplateName(QTN);
10581
10583 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10584 DependentTemplateNames.InsertNode(QTN, InsertPos);
10585 return TemplateName(QTN);
10586}
10587
10589 Decl *AssociatedDecl,
10590 unsigned Index,
10592 bool Final) const {
10593 llvm::FoldingSetNodeID ID;
10594 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10595 Index, PackIndex, Final);
10596
10597 void *insertPos = nullptr;
10599 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
10600
10601 if (!subst) {
10602 subst = new (*this) SubstTemplateTemplateParmStorage(
10603 Replacement, AssociatedDecl, Index, PackIndex, Final);
10604 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
10605 }
10606
10607 return TemplateName(subst);
10608}
10609
10612 Decl *AssociatedDecl,
10613 unsigned Index, bool Final) const {
10614 auto &Self = const_cast<ASTContext &>(*this);
10615 llvm::FoldingSetNodeID ID;
10617 AssociatedDecl, Index, Final);
10618
10619 void *InsertPos = nullptr;
10621 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
10622
10623 if (!Subst) {
10624 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10625 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10626 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
10627 }
10628
10629 return TemplateName(Subst);
10630}
10631
10632/// Retrieve the template name that represents a template name
10633/// deduced from a specialization.
10636 DefaultArguments DefaultArgs) const {
10637 if (!DefaultArgs)
10638 return Underlying;
10639
10640 llvm::FoldingSetNodeID ID;
10641 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10642
10643 void *InsertPos = nullptr;
10645 DeducedTemplates.FindNodeOrInsertPos(ID, InsertPos);
10646 if (!DTS) {
10647 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10648 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10649 alignof(DeducedTemplateStorage));
10650 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10651 DeducedTemplates.InsertNode(DTS, InsertPos);
10652 }
10653 return TemplateName(DTS);
10654}
10655
10656/// getFromTargetType - Given one of the integer types provided by
10657/// TargetInfo, produce the corresponding type. The unsigned @p Type
10658/// is actually a value of type @c TargetInfo::IntType.
10659CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10660 switch (Type) {
10661 case TargetInfo::NoInt: return {};
10664 case TargetInfo::SignedShort: return ShortTy;
10666 case TargetInfo::SignedInt: return IntTy;
10668 case TargetInfo::SignedLong: return LongTy;
10672 }
10673
10674 llvm_unreachable("Unhandled TargetInfo::IntType value");
10675}
10676
10677//===----------------------------------------------------------------------===//
10678// Type Predicates.
10679//===----------------------------------------------------------------------===//
10680
10681/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10682/// garbage collection attribute.
10683///
10685 if (getLangOpts().getGC() == LangOptions::NonGC)
10686 return Qualifiers::GCNone;
10687
10688 assert(getLangOpts().ObjC);
10689 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10690
10691 // Default behaviour under objective-C's gc is for ObjC pointers
10692 // (or pointers to them) be treated as though they were declared
10693 // as __strong.
10694 if (GCAttrs == Qualifiers::GCNone) {
10696 return Qualifiers::Strong;
10697 else if (Ty->isPointerType())
10699 } else {
10700 // It's not valid to set GC attributes on anything that isn't a
10701 // pointer.
10702#ifndef NDEBUG
10704 while (const auto *AT = dyn_cast<ArrayType>(CT))
10705 CT = AT->getElementType();
10706 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10707#endif
10708 }
10709 return GCAttrs;
10710}
10711
10712//===----------------------------------------------------------------------===//
10713// Type Compatibility Testing
10714//===----------------------------------------------------------------------===//
10715
10716/// areCompatVectorTypes - Return true if the two specified vector types are
10717/// compatible.
10718static bool areCompatVectorTypes(const VectorType *LHS,
10719 const VectorType *RHS) {
10720 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10721 return LHS->getElementType() == RHS->getElementType() &&
10722 LHS->getNumElements() == RHS->getNumElements();
10723}
10724
10725/// areCompatMatrixTypes - Return true if the two specified matrix types are
10726/// compatible.
10728 const ConstantMatrixType *RHS) {
10729 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10730 return LHS->getElementType() == RHS->getElementType() &&
10731 LHS->getNumRows() == RHS->getNumRows() &&
10732 LHS->getNumColumns() == RHS->getNumColumns();
10733}
10734
10736 QualType SecondVec) {
10737 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10738 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10739
10740 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10741 return true;
10742
10743 // Treat Neon vector types and most AltiVec vector types as if they are the
10744 // equivalent GCC vector types.
10745 const auto *First = FirstVec->castAs<VectorType>();
10746 const auto *Second = SecondVec->castAs<VectorType>();
10747 if (First->getNumElements() == Second->getNumElements() &&
10748 hasSameType(First->getElementType(), Second->getElementType()) &&
10749 First->getVectorKind() != VectorKind::AltiVecPixel &&
10750 First->getVectorKind() != VectorKind::AltiVecBool &&
10753 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10754 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10757 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10759 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10761 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10763 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10765 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10767 return true;
10768
10769 // In OpenCL, treat half and _Float16 vector types as compatible.
10770 if (getLangOpts().OpenCL &&
10771 First->getNumElements() == Second->getNumElements()) {
10772 QualType FirstElt = First->getElementType();
10773 QualType SecondElt = Second->getElementType();
10774
10775 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10776 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10777 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10778 First->getVectorKind() != VectorKind::AltiVecBool &&
10781 return true;
10782 }
10783 }
10784 return false;
10785}
10786
10792
10795 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10796 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10797
10798 if (!LHSOBT && !RHSOBT)
10800
10801 if (LHSOBT && RHSOBT) {
10802 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10805 }
10806
10807 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10808 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10809
10810 if (RHSOBT && !LHSOBT) {
10811 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10813 }
10814
10816}
10817
10818/// getRVVTypeSize - Return RVV vector register size.
10819static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10820 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10821 auto VScale = Context.getTargetInfo().getVScaleRange(
10822 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10823 if (!VScale)
10824 return 0;
10825
10826 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10827
10828 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10829 if (Info.ElementType == Context.BoolTy)
10830 EltSize = 1;
10831
10832 uint64_t MinElts = Info.EC.getKnownMinValue();
10833 return VScale->first * MinElts * EltSize;
10834}
10835
10837 QualType SecondType) {
10838 assert(
10839 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10840 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10841 "Expected RVV builtin type and vector type!");
10842
10843 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10844 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10845 if (const auto *VT = SecondType->getAs<VectorType>()) {
10846 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10848 return FirstType->isRVVVLSBuiltinType() &&
10849 Info.ElementType == BoolTy &&
10850 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10851 }
10852 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10854 return FirstType->isRVVVLSBuiltinType() &&
10855 Info.ElementType == BoolTy &&
10856 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10857 }
10858 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10860 return FirstType->isRVVVLSBuiltinType() &&
10861 Info.ElementType == BoolTy &&
10862 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10863 }
10864 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10866 return FirstType->isRVVVLSBuiltinType() &&
10867 Info.ElementType == BoolTy &&
10868 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10869 }
10870 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10871 VT->getVectorKind() == VectorKind::Generic)
10872 return FirstType->isRVVVLSBuiltinType() &&
10873 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10874 hasSameType(VT->getElementType(),
10875 getBuiltinVectorTypeInfo(BT).ElementType);
10876 }
10877 }
10878 return false;
10879 };
10880
10881 return IsValidCast(FirstType, SecondType) ||
10882 IsValidCast(SecondType, FirstType);
10883}
10884
10886 QualType SecondType) {
10887 assert(
10888 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10889 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10890 "Expected RVV builtin type and vector type!");
10891
10892 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10893 const auto *BT = FirstType->getAs<BuiltinType>();
10894 if (!BT)
10895 return false;
10896
10897 if (!BT->isRVVVLSBuiltinType())
10898 return false;
10899
10900 const auto *VecTy = SecondType->getAs<VectorType>();
10901 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10903 getLangOpts().getLaxVectorConversions();
10904
10905 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10906 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10907 return false;
10908
10909 // If -flax-vector-conversions=all is specified, the types are
10910 // certainly compatible.
10912 return true;
10913
10914 // If -flax-vector-conversions=integer is specified, the types are
10915 // compatible if the elements are integer types.
10917 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10918 FirstType->getRVVEltType(*this)->isIntegerType();
10919 }
10920
10921 return false;
10922 };
10923
10924 return IsLaxCompatible(FirstType, SecondType) ||
10925 IsLaxCompatible(SecondType, FirstType);
10926}
10927
10929 while (true) {
10930 // __strong id
10931 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10932 if (Attr->getAttrKind() == attr::ObjCOwnership)
10933 return true;
10934
10935 Ty = Attr->getModifiedType();
10936
10937 // X *__strong (...)
10938 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10939 Ty = Paren->getInnerType();
10940
10941 // We do not want to look through typedefs, typeof(expr),
10942 // typeof(type), or any other way that the type is somehow
10943 // abstracted.
10944 } else {
10945 return false;
10946 }
10947 }
10948}
10949
10950//===----------------------------------------------------------------------===//
10951// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10952//===----------------------------------------------------------------------===//
10953
10954/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10955/// inheritance hierarchy of 'rProto'.
10956bool
10958 ObjCProtocolDecl *rProto) const {
10959 if (declaresSameEntity(lProto, rProto))
10960 return true;
10961 for (auto *PI : rProto->protocols())
10962 if (ProtocolCompatibleWithProtocol(lProto, PI))
10963 return true;
10964 return false;
10965}
10966
10967/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
10968/// Class<pr1, ...>.
10970 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
10971 for (auto *lhsProto : lhs->quals()) {
10972 bool match = false;
10973 for (auto *rhsProto : rhs->quals()) {
10974 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
10975 match = true;
10976 break;
10977 }
10978 }
10979 if (!match)
10980 return false;
10981 }
10982 return true;
10983}
10984
10985/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
10986/// ObjCQualifiedIDType.
10988 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
10989 bool compare) {
10990 // Allow id<P..> and an 'id' in all cases.
10991 if (lhs->isObjCIdType() || rhs->isObjCIdType())
10992 return true;
10993
10994 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
10995 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
10997 return false;
10998
10999 if (lhs->isObjCQualifiedIdType()) {
11000 if (rhs->qual_empty()) {
11001 // If the RHS is a unqualified interface pointer "NSString*",
11002 // make sure we check the class hierarchy.
11003 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11004 for (auto *I : lhs->quals()) {
11005 // when comparing an id<P> on lhs with a static type on rhs,
11006 // see if static class implements all of id's protocols, directly or
11007 // through its super class and categories.
11008 if (!rhsID->ClassImplementsProtocol(I, true))
11009 return false;
11010 }
11011 }
11012 // If there are no qualifiers and no interface, we have an 'id'.
11013 return true;
11014 }
11015 // Both the right and left sides have qualifiers.
11016 for (auto *lhsProto : lhs->quals()) {
11017 bool match = false;
11018
11019 // when comparing an id<P> on lhs with a static type on rhs,
11020 // see if static class implements all of id's protocols, directly or
11021 // through its super class and categories.
11022 for (auto *rhsProto : rhs->quals()) {
11023 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11024 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11025 match = true;
11026 break;
11027 }
11028 }
11029 // If the RHS is a qualified interface pointer "NSString<P>*",
11030 // make sure we check the class hierarchy.
11031 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11032 for (auto *I : lhs->quals()) {
11033 // when comparing an id<P> on lhs with a static type on rhs,
11034 // see if static class implements all of id's protocols, directly or
11035 // through its super class and categories.
11036 if (rhsID->ClassImplementsProtocol(I, true)) {
11037 match = true;
11038 break;
11039 }
11040 }
11041 }
11042 if (!match)
11043 return false;
11044 }
11045
11046 return true;
11047 }
11048
11049 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11050
11051 if (lhs->getInterfaceType()) {
11052 // If both the right and left sides have qualifiers.
11053 for (auto *lhsProto : lhs->quals()) {
11054 bool match = false;
11055
11056 // when comparing an id<P> on rhs with a static type on lhs,
11057 // see if static class implements all of id's protocols, directly or
11058 // through its super class and categories.
11059 // First, lhs protocols in the qualifier list must be found, direct
11060 // or indirect in rhs's qualifier list or it is a mismatch.
11061 for (auto *rhsProto : rhs->quals()) {
11062 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11063 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11064 match = true;
11065 break;
11066 }
11067 }
11068 if (!match)
11069 return false;
11070 }
11071
11072 // Static class's protocols, or its super class or category protocols
11073 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11074 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11075 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11076 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11077 // This is rather dubious but matches gcc's behavior. If lhs has
11078 // no type qualifier and its class has no static protocol(s)
11079 // assume that it is mismatch.
11080 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11081 return false;
11082 for (auto *lhsProto : LHSInheritedProtocols) {
11083 bool match = false;
11084 for (auto *rhsProto : rhs->quals()) {
11085 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11086 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11087 match = true;
11088 break;
11089 }
11090 }
11091 if (!match)
11092 return false;
11093 }
11094 }
11095 return true;
11096 }
11097 return false;
11098}
11099
11100/// canAssignObjCInterfaces - Return true if the two interface types are
11101/// compatible for assignment from RHS to LHS. This handles validation of any
11102/// protocol qualifiers on the LHS or RHS.
11104 const ObjCObjectPointerType *RHSOPT) {
11105 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11106 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11107
11108 // If either type represents the built-in 'id' type, return true.
11109 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11110 return true;
11111
11112 // Function object that propagates a successful result or handles
11113 // __kindof types.
11114 auto finish = [&](bool succeeded) -> bool {
11115 if (succeeded)
11116 return true;
11117
11118 if (!RHS->isKindOfType())
11119 return false;
11120
11121 // Strip off __kindof and protocol qualifiers, then check whether
11122 // we can assign the other way.
11124 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11125 };
11126
11127 // Casts from or to id<P> are allowed when the other side has compatible
11128 // protocols.
11129 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11130 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11131 }
11132
11133 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11134 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11135 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11136 }
11137
11138 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11139 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11140 return true;
11141 }
11142
11143 // If we have 2 user-defined types, fall into that path.
11144 if (LHS->getInterface() && RHS->getInterface()) {
11145 return finish(canAssignObjCInterfaces(LHS, RHS));
11146 }
11147
11148 return false;
11149}
11150
11151/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11152/// for providing type-safety for objective-c pointers used to pass/return
11153/// arguments in block literals. When passed as arguments, passing 'A*' where
11154/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11155/// not OK. For the return type, the opposite is not OK.
11157 const ObjCObjectPointerType *LHSOPT,
11158 const ObjCObjectPointerType *RHSOPT,
11159 bool BlockReturnType) {
11160
11161 // Function object that propagates a successful result or handles
11162 // __kindof types.
11163 auto finish = [&](bool succeeded) -> bool {
11164 if (succeeded)
11165 return true;
11166
11167 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11168 if (!Expected->isKindOfType())
11169 return false;
11170
11171 // Strip off __kindof and protocol qualifiers, then check whether
11172 // we can assign the other way.
11174 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11175 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11176 BlockReturnType);
11177 };
11178
11179 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11180 return true;
11181
11182 if (LHSOPT->isObjCBuiltinType()) {
11183 return finish(RHSOPT->isObjCBuiltinType() ||
11184 RHSOPT->isObjCQualifiedIdType());
11185 }
11186
11187 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11188 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11189 // Use for block parameters previous type checking for compatibility.
11190 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11191 // Or corrected type checking as in non-compat mode.
11192 (!BlockReturnType &&
11193 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11194 else
11196 (BlockReturnType ? LHSOPT : RHSOPT),
11197 (BlockReturnType ? RHSOPT : LHSOPT), false));
11198 }
11199
11200 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11201 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11202 if (LHS && RHS) { // We have 2 user-defined types.
11203 if (LHS != RHS) {
11204 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11205 return finish(BlockReturnType);
11206 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11207 return finish(!BlockReturnType);
11208 }
11209 else
11210 return true;
11211 }
11212 return false;
11213}
11214
11215/// Comparison routine for Objective-C protocols to be used with
11216/// llvm::array_pod_sort.
11218 ObjCProtocolDecl * const *rhs) {
11219 return (*lhs)->getName().compare((*rhs)->getName());
11220}
11221
11222/// getIntersectionOfProtocols - This routine finds the intersection of set
11223/// of protocols inherited from two distinct objective-c pointer objects with
11224/// the given common base.
11225/// It is used to build composite qualifier list of the composite type of
11226/// the conditional expression involving two objective-c pointer objects.
11227static
11229 const ObjCInterfaceDecl *CommonBase,
11230 const ObjCObjectPointerType *LHSOPT,
11231 const ObjCObjectPointerType *RHSOPT,
11232 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11233
11234 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11235 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11236 assert(LHS->getInterface() && "LHS must have an interface base");
11237 assert(RHS->getInterface() && "RHS must have an interface base");
11238
11239 // Add all of the protocols for the LHS.
11241
11242 // Start with the protocol qualifiers.
11243 for (auto *proto : LHS->quals()) {
11244 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11245 }
11246
11247 // Also add the protocols associated with the LHS interface.
11248 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11249
11250 // Add all of the protocols for the RHS.
11252
11253 // Start with the protocol qualifiers.
11254 for (auto *proto : RHS->quals()) {
11255 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11256 }
11257
11258 // Also add the protocols associated with the RHS interface.
11259 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11260
11261 // Compute the intersection of the collected protocol sets.
11262 for (auto *proto : LHSProtocolSet) {
11263 if (RHSProtocolSet.count(proto))
11264 IntersectionSet.push_back(proto);
11265 }
11266
11267 // Compute the set of protocols that is implied by either the common type or
11268 // the protocols within the intersection.
11270 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11271
11272 // Remove any implied protocols from the list of inherited protocols.
11273 if (!ImpliedProtocols.empty()) {
11274 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11275 return ImpliedProtocols.contains(proto);
11276 });
11277 }
11278
11279 // Sort the remaining protocols by name.
11280 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11282}
11283
11284/// Determine whether the first type is a subtype of the second.
11286 QualType rhs) {
11287 // Common case: two object pointers.
11288 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11289 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11290 if (lhsOPT && rhsOPT)
11291 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11292
11293 // Two block pointers.
11294 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11295 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11296 if (lhsBlock && rhsBlock)
11297 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11298
11299 // If either is an unqualified 'id' and the other is a block, it's
11300 // acceptable.
11301 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11302 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11303 return true;
11304
11305 return false;
11306}
11307
11308// Check that the given Objective-C type argument lists are equivalent.
11310 const ObjCInterfaceDecl *iface,
11311 ArrayRef<QualType> lhsArgs,
11312 ArrayRef<QualType> rhsArgs,
11313 bool stripKindOf) {
11314 if (lhsArgs.size() != rhsArgs.size())
11315 return false;
11316
11317 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11318 if (!typeParams)
11319 return false;
11320
11321 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11322 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11323 continue;
11324
11325 switch (typeParams->begin()[i]->getVariance()) {
11327 if (!stripKindOf ||
11328 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11329 rhsArgs[i].stripObjCKindOfType(ctx))) {
11330 return false;
11331 }
11332 break;
11333
11335 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11336 return false;
11337 break;
11338
11340 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11341 return false;
11342 break;
11343 }
11344 }
11345
11346 return true;
11347}
11348
11350 const ObjCObjectPointerType *Lptr,
11351 const ObjCObjectPointerType *Rptr) {
11352 const ObjCObjectType *LHS = Lptr->getObjectType();
11353 const ObjCObjectType *RHS = Rptr->getObjectType();
11354 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11355 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11356
11357 if (!LDecl || !RDecl)
11358 return {};
11359
11360 // When either LHS or RHS is a kindof type, we should return a kindof type.
11361 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11362 // kindof(A).
11363 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11364
11365 // Follow the left-hand side up the class hierarchy until we either hit a
11366 // root or find the RHS. Record the ancestors in case we don't find it.
11367 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11368 LHSAncestors;
11369 while (true) {
11370 // Record this ancestor. We'll need this if the common type isn't in the
11371 // path from the LHS to the root.
11372 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11373
11374 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11375 // Get the type arguments.
11376 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11377 bool anyChanges = false;
11378 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11379 // Both have type arguments, compare them.
11380 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11381 LHS->getTypeArgs(), RHS->getTypeArgs(),
11382 /*stripKindOf=*/true))
11383 return {};
11384 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11385 // If only one has type arguments, the result will not have type
11386 // arguments.
11387 LHSTypeArgs = {};
11388 anyChanges = true;
11389 }
11390
11391 // Compute the intersection of protocols.
11393 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11394 Protocols);
11395 if (!Protocols.empty())
11396 anyChanges = true;
11397
11398 // If anything in the LHS will have changed, build a new result type.
11399 // If we need to return a kindof type but LHS is not a kindof type, we
11400 // build a new result type.
11401 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11402 QualType Result = getObjCInterfaceType(LHS->getInterface());
11403 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11404 anyKindOf || LHS->isKindOfType());
11406 }
11407
11408 return getObjCObjectPointerType(QualType(LHS, 0));
11409 }
11410
11411 // Find the superclass.
11412 QualType LHSSuperType = LHS->getSuperClassType();
11413 if (LHSSuperType.isNull())
11414 break;
11415
11416 LHS = LHSSuperType->castAs<ObjCObjectType>();
11417 }
11418
11419 // We didn't find anything by following the LHS to its root; now check
11420 // the RHS against the cached set of ancestors.
11421 while (true) {
11422 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11423 if (KnownLHS != LHSAncestors.end()) {
11424 LHS = KnownLHS->second;
11425
11426 // Get the type arguments.
11427 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11428 bool anyChanges = false;
11429 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11430 // Both have type arguments, compare them.
11431 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11432 LHS->getTypeArgs(), RHS->getTypeArgs(),
11433 /*stripKindOf=*/true))
11434 return {};
11435 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11436 // If only one has type arguments, the result will not have type
11437 // arguments.
11438 RHSTypeArgs = {};
11439 anyChanges = true;
11440 }
11441
11442 // Compute the intersection of protocols.
11444 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11445 Protocols);
11446 if (!Protocols.empty())
11447 anyChanges = true;
11448
11449 // If we need to return a kindof type but RHS is not a kindof type, we
11450 // build a new result type.
11451 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11452 QualType Result = getObjCInterfaceType(RHS->getInterface());
11453 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11454 anyKindOf || RHS->isKindOfType());
11456 }
11457
11458 return getObjCObjectPointerType(QualType(RHS, 0));
11459 }
11460
11461 // Find the superclass of the RHS.
11462 QualType RHSSuperType = RHS->getSuperClassType();
11463 if (RHSSuperType.isNull())
11464 break;
11465
11466 RHS = RHSSuperType->castAs<ObjCObjectType>();
11467 }
11468
11469 return {};
11470}
11471
11473 const ObjCObjectType *RHS) {
11474 assert(LHS->getInterface() && "LHS is not an interface type");
11475 assert(RHS->getInterface() && "RHS is not an interface type");
11476
11477 // Verify that the base decls are compatible: the RHS must be a subclass of
11478 // the LHS.
11479 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11480 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11481 if (!IsSuperClass)
11482 return false;
11483
11484 // If the LHS has protocol qualifiers, determine whether all of them are
11485 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11486 // LHS).
11487 if (LHS->getNumProtocols() > 0) {
11488 // OK if conversion of LHS to SuperClass results in narrowing of types
11489 // ; i.e., SuperClass may implement at least one of the protocols
11490 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11491 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11492 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11493 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11494 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11495 // qualifiers.
11496 for (auto *RHSPI : RHS->quals())
11497 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11498 // If there is no protocols associated with RHS, it is not a match.
11499 if (SuperClassInheritedProtocols.empty())
11500 return false;
11501
11502 for (const auto *LHSProto : LHS->quals()) {
11503 bool SuperImplementsProtocol = false;
11504 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11505 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11506 SuperImplementsProtocol = true;
11507 break;
11508 }
11509 if (!SuperImplementsProtocol)
11510 return false;
11511 }
11512 }
11513
11514 // If the LHS is specialized, we may need to check type arguments.
11515 if (LHS->isSpecialized()) {
11516 // Follow the superclass chain until we've matched the LHS class in the
11517 // hierarchy. This substitutes type arguments through.
11518 const ObjCObjectType *RHSSuper = RHS;
11519 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11520 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11521
11522 // If the RHS is specializd, compare type arguments.
11523 if (RHSSuper->isSpecialized() &&
11524 !sameObjCTypeArgs(*this, LHS->getInterface(),
11525 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11526 /*stripKindOf=*/true)) {
11527 return false;
11528 }
11529 }
11530
11531 return true;
11532}
11533
11535 // get the "pointed to" types
11536 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11537 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11538
11539 if (!LHSOPT || !RHSOPT)
11540 return false;
11541
11542 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11543 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11544}
11545
11548 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11549 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11550}
11551
11552/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11553/// both shall have the identically qualified version of a compatible type.
11554/// C99 6.2.7p1: Two types have compatible types if their types are the
11555/// same. See 6.7.[2,3,5] for additional rules.
11557 bool CompareUnqualified) {
11558 if (getLangOpts().CPlusPlus)
11559 return hasSameType(LHS, RHS);
11560
11561 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11562}
11563
11565 return typesAreCompatible(LHS, RHS);
11566}
11567
11569 return !mergeTypes(LHS, RHS, true).isNull();
11570}
11571
11572/// mergeTransparentUnionType - if T is a transparent union type and a member
11573/// of T is compatible with SubType, return the merged type, else return
11574/// QualType()
11576 bool OfBlockPointer,
11577 bool Unqualified) {
11578 if (const RecordType *UT = T->getAsUnionType()) {
11579 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11580 if (UD->hasAttr<TransparentUnionAttr>()) {
11581 for (const auto *I : UD->fields()) {
11582 QualType ET = I->getType().getUnqualifiedType();
11583 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11584 if (!MT.isNull())
11585 return MT;
11586 }
11587 }
11588 }
11589
11590 return {};
11591}
11592
11593/// mergeFunctionParameterTypes - merge two types which appear as function
11594/// parameter types
11596 bool OfBlockPointer,
11597 bool Unqualified) {
11598 // GNU extension: two types are compatible if they appear as a function
11599 // argument, one of the types is a transparent union type and the other
11600 // type is compatible with a union member
11601 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11602 Unqualified);
11603 if (!lmerge.isNull())
11604 return lmerge;
11605
11606 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11607 Unqualified);
11608 if (!rmerge.isNull())
11609 return rmerge;
11610
11611 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11612}
11613
11615 bool OfBlockPointer, bool Unqualified,
11616 bool AllowCXX,
11617 bool IsConditionalOperator) {
11618 const auto *lbase = lhs->castAs<FunctionType>();
11619 const auto *rbase = rhs->castAs<FunctionType>();
11620 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11621 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11622 bool allLTypes = true;
11623 bool allRTypes = true;
11624
11625 // Check return type
11626 QualType retType;
11627 if (OfBlockPointer) {
11628 QualType RHS = rbase->getReturnType();
11629 QualType LHS = lbase->getReturnType();
11630 bool UnqualifiedResult = Unqualified;
11631 if (!UnqualifiedResult)
11632 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11633 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11634 }
11635 else
11636 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11637 Unqualified);
11638 if (retType.isNull())
11639 return {};
11640
11641 if (Unqualified)
11642 retType = retType.getUnqualifiedType();
11643
11644 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11645 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11646 if (Unqualified) {
11647 LRetType = LRetType.getUnqualifiedType();
11648 RRetType = RRetType.getUnqualifiedType();
11649 }
11650
11651 if (getCanonicalType(retType) != LRetType)
11652 allLTypes = false;
11653 if (getCanonicalType(retType) != RRetType)
11654 allRTypes = false;
11655
11656 // FIXME: double check this
11657 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11658 // rbase->getRegParmAttr() != 0 &&
11659 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11660 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11661 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11662
11663 // Compatible functions must have compatible calling conventions
11664 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11665 return {};
11666
11667 // Regparm is part of the calling convention.
11668 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11669 return {};
11670 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11671 return {};
11672
11673 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11674 return {};
11675 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11676 return {};
11677 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11678 return {};
11679
11680 // When merging declarations, it's common for supplemental information like
11681 // attributes to only be present in one of the declarations, and we generally
11682 // want type merging to preserve the union of information. So a merged
11683 // function type should be noreturn if it was noreturn in *either* operand
11684 // type.
11685 //
11686 // But for the conditional operator, this is backwards. The result of the
11687 // operator could be either operand, and its type should conservatively
11688 // reflect that. So a function type in a composite type is noreturn only
11689 // if it's noreturn in *both* operand types.
11690 //
11691 // Arguably, noreturn is a kind of subtype, and the conditional operator
11692 // ought to produce the most specific common supertype of its operand types.
11693 // That would differ from this rule in contravariant positions. However,
11694 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11695 // as a practical matter, it would only affect C code that does abstraction of
11696 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11697 // say the least. So we use the simpler rule.
11698 bool NoReturn = IsConditionalOperator
11699 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11700 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11701 if (lbaseInfo.getNoReturn() != NoReturn)
11702 allLTypes = false;
11703 if (rbaseInfo.getNoReturn() != NoReturn)
11704 allRTypes = false;
11705
11706 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11707
11708 std::optional<FunctionEffectSet> MergedFX;
11709
11710 if (lproto && rproto) { // two C99 style function prototypes
11711 assert((AllowCXX ||
11712 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11713 "C++ shouldn't be here");
11714 // Compatible functions must have the same number of parameters
11715 if (lproto->getNumParams() != rproto->getNumParams())
11716 return {};
11717
11718 // Variadic and non-variadic functions aren't compatible
11719 if (lproto->isVariadic() != rproto->isVariadic())
11720 return {};
11721
11722 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11723 return {};
11724
11725 // Function protos with different 'cfi_salt' values aren't compatible.
11726 if (lproto->getExtraAttributeInfo().CFISalt !=
11727 rproto->getExtraAttributeInfo().CFISalt)
11728 return {};
11729
11730 // Function effects are handled similarly to noreturn, see above.
11731 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11732 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11733 if (LHSFX != RHSFX) {
11734 if (IsConditionalOperator)
11735 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11736 else {
11738 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11739 // Here we're discarding a possible error due to conflicts in the effect
11740 // sets. But we're not in a context where we can report it. The
11741 // operation does however guarantee maintenance of invariants.
11742 }
11743 if (*MergedFX != LHSFX)
11744 allLTypes = false;
11745 if (*MergedFX != RHSFX)
11746 allRTypes = false;
11747 }
11748
11750 bool canUseLeft, canUseRight;
11751 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11752 newParamInfos))
11753 return {};
11754
11755 if (!canUseLeft)
11756 allLTypes = false;
11757 if (!canUseRight)
11758 allRTypes = false;
11759
11760 // Check parameter type compatibility
11762 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11763 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11764 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11766 lParamType, rParamType, OfBlockPointer, Unqualified);
11767 if (paramType.isNull())
11768 return {};
11769
11770 if (Unqualified)
11771 paramType = paramType.getUnqualifiedType();
11772
11773 types.push_back(paramType);
11774 if (Unqualified) {
11775 lParamType = lParamType.getUnqualifiedType();
11776 rParamType = rParamType.getUnqualifiedType();
11777 }
11778
11779 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11780 allLTypes = false;
11781 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11782 allRTypes = false;
11783 }
11784
11785 if (allLTypes) return lhs;
11786 if (allRTypes) return rhs;
11787
11788 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11789 EPI.ExtInfo = einfo;
11790 EPI.ExtParameterInfos =
11791 newParamInfos.empty() ? nullptr : newParamInfos.data();
11792 if (MergedFX)
11793 EPI.FunctionEffects = *MergedFX;
11794 return getFunctionType(retType, types, EPI);
11795 }
11796
11797 if (lproto) allRTypes = false;
11798 if (rproto) allLTypes = false;
11799
11800 const FunctionProtoType *proto = lproto ? lproto : rproto;
11801 if (proto) {
11802 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11803 if (proto->isVariadic())
11804 return {};
11805 // Check that the types are compatible with the types that
11806 // would result from default argument promotions (C99 6.7.5.3p15).
11807 // The only types actually affected are promotable integer
11808 // types and floats, which would be passed as a different
11809 // type depending on whether the prototype is visible.
11810 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11811 QualType paramTy = proto->getParamType(i);
11812
11813 // Look at the converted type of enum types, since that is the type used
11814 // to pass enum values.
11815 if (const auto *ED = paramTy->getAsEnumDecl()) {
11816 paramTy = ED->getIntegerType();
11817 if (paramTy.isNull())
11818 return {};
11819 }
11820
11821 if (isPromotableIntegerType(paramTy) ||
11822 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11823 return {};
11824 }
11825
11826 if (allLTypes) return lhs;
11827 if (allRTypes) return rhs;
11828
11830 EPI.ExtInfo = einfo;
11831 if (MergedFX)
11832 EPI.FunctionEffects = *MergedFX;
11833 return getFunctionType(retType, proto->getParamTypes(), EPI);
11834 }
11835
11836 if (allLTypes) return lhs;
11837 if (allRTypes) return rhs;
11838 return getFunctionNoProtoType(retType, einfo);
11839}
11840
11841/// Given that we have an enum type and a non-enum type, try to merge them.
11842static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11843 QualType other, bool isBlockReturnType) {
11844 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11845 // a signed integer type, or an unsigned integer type.
11846 // Compatibility is based on the underlying type, not the promotion
11847 // type.
11848 QualType underlyingType =
11849 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11850 if (underlyingType.isNull())
11851 return {};
11852 if (Context.hasSameType(underlyingType, other))
11853 return other;
11854
11855 // In block return types, we're more permissive and accept any
11856 // integral type of the same size.
11857 if (isBlockReturnType && other->isIntegerType() &&
11858 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11859 return other;
11860
11861 return {};
11862}
11863
11865 // C17 and earlier and C++ disallow two tag definitions within the same TU
11866 // from being compatible.
11867 if (LangOpts.CPlusPlus || !LangOpts.C23)
11868 return {};
11869
11870 // Nameless tags are comparable only within outer definitions. At the top
11871 // level they are not comparable.
11872 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11873 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11874 return {};
11875
11876 // C23, on the other hand, requires the members to be "the same enough", so
11877 // we use a structural equivalence check.
11880 getLangOpts(), *this, *this, NonEquivalentDecls,
11881 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11882 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11883 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11884}
11885
11887 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11888 bool BlockReturnType, bool IsConditionalOperator) {
11889 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11890 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11891
11892 if (!LHSOBT && !RHSOBT)
11893 return std::nullopt;
11894
11895 if (LHSOBT) {
11896 if (RHSOBT) {
11897 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11898 return QualType();
11899
11900 QualType MergedUnderlying = mergeTypes(
11901 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11902 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11903
11904 if (MergedUnderlying.isNull())
11905 return QualType();
11906
11907 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11908 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11909 return getCommonSugaredType(LHS, RHS);
11911 LHSOBT->getBehaviorKind(),
11912 getCanonicalType(LHSOBT->getUnderlyingType()));
11913 }
11914
11915 // For different underlying types that successfully merge, wrap the
11916 // merged underlying type with the common overflow behavior
11917 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11918 MergedUnderlying);
11919 }
11920 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11921 Unqualified, BlockReturnType, IsConditionalOperator);
11922 }
11923
11924 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11925 Unqualified, BlockReturnType, IsConditionalOperator);
11926}
11927
11928QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11929 bool Unqualified, bool BlockReturnType,
11930 bool IsConditionalOperator) {
11931 // For C++ we will not reach this code with reference types (see below),
11932 // for OpenMP variant call overloading we might.
11933 //
11934 // C++ [expr]: If an expression initially has the type "reference to T", the
11935 // type is adjusted to "T" prior to any further analysis, the expression
11936 // designates the object or function denoted by the reference, and the
11937 // expression is an lvalue unless the reference is an rvalue reference and
11938 // the expression is a function call (possibly inside parentheses).
11939 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11940 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11941 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11942 LHS->getTypeClass() == RHS->getTypeClass())
11943 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11944 OfBlockPointer, Unqualified, BlockReturnType);
11945 if (LHSRefTy || RHSRefTy)
11946 return {};
11947
11948 if (std::optional<QualType> MergedOBT =
11949 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11950 BlockReturnType, IsConditionalOperator))
11951 return *MergedOBT;
11952
11953 if (Unqualified) {
11954 LHS = LHS.getUnqualifiedType();
11955 RHS = RHS.getUnqualifiedType();
11956 }
11957
11958 QualType LHSCan = getCanonicalType(LHS),
11959 RHSCan = getCanonicalType(RHS);
11960
11961 // If two types are identical, they are compatible.
11962 if (LHSCan == RHSCan)
11963 return LHS;
11964
11965 // If the qualifiers are different, the types aren't compatible... mostly.
11966 Qualifiers LQuals = LHSCan.getLocalQualifiers();
11967 Qualifiers RQuals = RHSCan.getLocalQualifiers();
11968 if (LQuals != RQuals) {
11969 // If any of these qualifiers are different, we have a type
11970 // mismatch.
11971 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
11972 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
11973 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
11974 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
11975 LQuals.hasUnaligned() != RQuals.hasUnaligned())
11976 return {};
11977
11978 // Exactly one GC qualifier difference is allowed: __strong is
11979 // okay if the other type has no GC qualifier but is an Objective
11980 // C object pointer (i.e. implicitly strong by default). We fix
11981 // this by pretending that the unqualified type was actually
11982 // qualified __strong.
11983 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
11984 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
11985 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
11986
11987 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
11988 return {};
11989
11990 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
11992 }
11993 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
11995 }
11996 return {};
11997 }
11998
11999 // Okay, qualifiers are equal.
12000
12001 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12002 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12003
12004 // We want to consider the two function types to be the same for these
12005 // comparisons, just force one to the other.
12006 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12007 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12008
12009 // Same as above for arrays
12010 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12011 LHSClass = Type::ConstantArray;
12012 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12013 RHSClass = Type::ConstantArray;
12014
12015 // ObjCInterfaces are just specialized ObjCObjects.
12016 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12017 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12018
12019 // Canonicalize ExtVector -> Vector.
12020 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12021 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12022
12023 // If the canonical type classes don't match.
12024 if (LHSClass != RHSClass) {
12025 // Note that we only have special rules for turning block enum
12026 // returns into block int returns, not vice-versa.
12027 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12028 return mergeEnumWithInteger(*this, ETy, RHS, false);
12029 }
12030 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12031 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12032 }
12033 // allow block pointer type to match an 'id' type.
12034 if (OfBlockPointer && !BlockReturnType) {
12035 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12036 return LHS;
12037 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12038 return RHS;
12039 }
12040 // Allow __auto_type to match anything; it merges to the type with more
12041 // information.
12042 if (const auto *AT = LHS->getAs<AutoType>()) {
12043 if (!AT->isDeduced() && AT->isGNUAutoType())
12044 return RHS;
12045 }
12046 if (const auto *AT = RHS->getAs<AutoType>()) {
12047 if (!AT->isDeduced() && AT->isGNUAutoType())
12048 return LHS;
12049 }
12050 return {};
12051 }
12052
12053 // The canonical type classes match.
12054 switch (LHSClass) {
12055#define TYPE(Class, Base)
12056#define ABSTRACT_TYPE(Class, Base)
12057#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12058#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12059#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12060#include "clang/AST/TypeNodes.inc"
12061 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12062
12063 case Type::Auto:
12064 case Type::DeducedTemplateSpecialization:
12065 case Type::LValueReference:
12066 case Type::RValueReference:
12067 case Type::MemberPointer:
12068 llvm_unreachable("C++ should never be in mergeTypes");
12069
12070 case Type::ObjCInterface:
12071 case Type::IncompleteArray:
12072 case Type::VariableArray:
12073 case Type::FunctionProto:
12074 case Type::ExtVector:
12075 case Type::OverflowBehavior:
12076 llvm_unreachable("Types are eliminated above");
12077
12078 case Type::Pointer:
12079 {
12080 // Merge two pointer types, while trying to preserve typedef info
12081 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12082 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12083 if (Unqualified) {
12084 LHSPointee = LHSPointee.getUnqualifiedType();
12085 RHSPointee = RHSPointee.getUnqualifiedType();
12086 }
12087 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12088 Unqualified);
12089 if (ResultType.isNull())
12090 return {};
12091 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12092 return LHS;
12093 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12094 return RHS;
12095 return getPointerType(ResultType);
12096 }
12097 case Type::BlockPointer:
12098 {
12099 // Merge two block pointer types, while trying to preserve typedef info
12100 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12101 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12102 if (Unqualified) {
12103 LHSPointee = LHSPointee.getUnqualifiedType();
12104 RHSPointee = RHSPointee.getUnqualifiedType();
12105 }
12106 if (getLangOpts().OpenCL) {
12107 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12108 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12109 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12110 // 6.12.5) thus the following check is asymmetric.
12111 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12112 return {};
12113 LHSPteeQual.removeAddressSpace();
12114 RHSPteeQual.removeAddressSpace();
12115 LHSPointee =
12116 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12117 RHSPointee =
12118 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12119 }
12120 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12121 Unqualified);
12122 if (ResultType.isNull())
12123 return {};
12124 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12125 return LHS;
12126 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12127 return RHS;
12128 return getBlockPointerType(ResultType);
12129 }
12130 case Type::Atomic:
12131 {
12132 // Merge two pointer types, while trying to preserve typedef info
12133 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12134 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12135 if (Unqualified) {
12136 LHSValue = LHSValue.getUnqualifiedType();
12137 RHSValue = RHSValue.getUnqualifiedType();
12138 }
12139 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12140 Unqualified);
12141 if (ResultType.isNull())
12142 return {};
12143 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12144 return LHS;
12145 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12146 return RHS;
12147 return getAtomicType(ResultType);
12148 }
12149 case Type::ConstantArray:
12150 {
12151 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12152 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12153 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12154 return {};
12155
12156 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12157 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12158 if (Unqualified) {
12159 LHSElem = LHSElem.getUnqualifiedType();
12160 RHSElem = RHSElem.getUnqualifiedType();
12161 }
12162
12163 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12164 if (ResultType.isNull())
12165 return {};
12166
12167 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12168 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12169
12170 // If either side is a variable array, and both are complete, check whether
12171 // the current dimension is definite.
12172 if (LVAT || RVAT) {
12173 auto SizeFetch = [this](const VariableArrayType* VAT,
12174 const ConstantArrayType* CAT)
12175 -> std::pair<bool,llvm::APInt> {
12176 if (VAT) {
12177 std::optional<llvm::APSInt> TheInt;
12178 Expr *E = VAT->getSizeExpr();
12179 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12180 return std::make_pair(true, *TheInt);
12181 return std::make_pair(false, llvm::APSInt());
12182 }
12183 if (CAT)
12184 return std::make_pair(true, CAT->getSize());
12185 return std::make_pair(false, llvm::APInt());
12186 };
12187
12188 bool HaveLSize, HaveRSize;
12189 llvm::APInt LSize, RSize;
12190 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12191 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12192 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12193 return {}; // Definite, but unequal, array dimension
12194 }
12195
12196 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12197 return LHS;
12198 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12199 return RHS;
12200 if (LCAT)
12201 return getConstantArrayType(ResultType, LCAT->getSize(),
12202 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12203 if (RCAT)
12204 return getConstantArrayType(ResultType, RCAT->getSize(),
12205 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12206 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12207 return LHS;
12208 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12209 return RHS;
12210 if (LVAT) {
12211 // FIXME: This isn't correct! But tricky to implement because
12212 // the array's size has to be the size of LHS, but the type
12213 // has to be different.
12214 return LHS;
12215 }
12216 if (RVAT) {
12217 // FIXME: This isn't correct! But tricky to implement because
12218 // the array's size has to be the size of RHS, but the type
12219 // has to be different.
12220 return RHS;
12221 }
12222 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12223 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12224 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12225 }
12226 case Type::FunctionNoProto:
12227 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12228 /*AllowCXX=*/false, IsConditionalOperator);
12229 case Type::Record:
12230 case Type::Enum:
12231 return mergeTagDefinitions(LHS, RHS);
12232 case Type::Builtin:
12233 // Only exactly equal builtin types are compatible, which is tested above.
12234 return {};
12235 case Type::Complex:
12236 // Distinct complex types are incompatible.
12237 return {};
12238 case Type::Vector:
12239 // FIXME: The merged type should be an ExtVector!
12240 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12241 RHSCan->castAs<VectorType>()))
12242 return LHS;
12243 return {};
12244 case Type::ConstantMatrix:
12246 RHSCan->castAs<ConstantMatrixType>()))
12247 return LHS;
12248 return {};
12249 case Type::ObjCObject: {
12250 // Check if the types are assignment compatible.
12251 // FIXME: This should be type compatibility, e.g. whether
12252 // "LHS x; RHS x;" at global scope is legal.
12254 RHS->castAs<ObjCObjectType>()))
12255 return LHS;
12256 return {};
12257 }
12258 case Type::ObjCObjectPointer:
12259 if (OfBlockPointer) {
12262 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12263 return LHS;
12264 return {};
12265 }
12268 return LHS;
12269 return {};
12270 case Type::Pipe:
12271 assert(LHS != RHS &&
12272 "Equivalent pipe types should have already been handled!");
12273 return {};
12274 case Type::ArrayParameter:
12275 assert(LHS != RHS &&
12276 "Equivalent ArrayParameter types should have already been handled!");
12277 return {};
12278 case Type::BitInt: {
12279 // Merge two bit-precise int types, while trying to preserve typedef info.
12280 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12281 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12282 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12283 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12284
12285 // Like unsigned/int, shouldn't have a type if they don't match.
12286 if (LHSUnsigned != RHSUnsigned)
12287 return {};
12288
12289 if (LHSBits != RHSBits)
12290 return {};
12291 return LHS;
12292 }
12293 case Type::HLSLAttributedResource: {
12294 const HLSLAttributedResourceType *LHSTy =
12295 LHS->castAs<HLSLAttributedResourceType>();
12296 const HLSLAttributedResourceType *RHSTy =
12297 RHS->castAs<HLSLAttributedResourceType>();
12298 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12299 LHSTy->getWrappedType()->isHLSLResourceType() &&
12300 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12301
12302 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12303 LHSTy->getContainedType() == RHSTy->getContainedType())
12304 return LHS;
12305 return {};
12306 }
12307 case Type::HLSLInlineSpirv:
12308 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12309 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12310
12311 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12312 LHSTy->getSize() == RHSTy->getSize() &&
12313 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12314 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12315 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12316 return {};
12317
12318 return LHS;
12319 }
12320 return {};
12321 }
12322
12323 llvm_unreachable("Invalid Type::Class!");
12324}
12325
12327 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12328 bool &CanUseFirst, bool &CanUseSecond,
12330 assert(NewParamInfos.empty() && "param info list not empty");
12331 CanUseFirst = CanUseSecond = true;
12332 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12333 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12334
12335 // Fast path: if the first type doesn't have ext parameter infos,
12336 // we match if and only if the second type also doesn't have them.
12337 if (!FirstHasInfo && !SecondHasInfo)
12338 return true;
12339
12340 bool NeedParamInfo = false;
12341 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12342 : SecondFnType->getExtParameterInfos().size();
12343
12344 for (size_t I = 0; I < E; ++I) {
12345 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12346 if (FirstHasInfo)
12347 FirstParam = FirstFnType->getExtParameterInfo(I);
12348 if (SecondHasInfo)
12349 SecondParam = SecondFnType->getExtParameterInfo(I);
12350
12351 // Cannot merge unless everything except the noescape flag matches.
12352 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12353 return false;
12354
12355 bool FirstNoEscape = FirstParam.isNoEscape();
12356 bool SecondNoEscape = SecondParam.isNoEscape();
12357 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12358 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12359 if (NewParamInfos.back().getOpaqueValue())
12360 NeedParamInfo = true;
12361 if (FirstNoEscape != IsNoEscape)
12362 CanUseFirst = false;
12363 if (SecondNoEscape != IsNoEscape)
12364 CanUseSecond = false;
12365 }
12366
12367 if (!NeedParamInfo)
12368 NewParamInfos.clear();
12369
12370 return true;
12371}
12372
12374 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12375 It->second = nullptr;
12376 for (auto *SubClass : ObjCSubClasses.lookup(D))
12377 ResetObjCLayout(SubClass);
12378 }
12379}
12380
12381/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12382/// 'RHS' attributes and returns the merged version; including for function
12383/// return types.
12385 QualType LHSCan = getCanonicalType(LHS),
12386 RHSCan = getCanonicalType(RHS);
12387 // If two types are identical, they are compatible.
12388 if (LHSCan == RHSCan)
12389 return LHS;
12390 if (RHSCan->isFunctionType()) {
12391 if (!LHSCan->isFunctionType())
12392 return {};
12393 QualType OldReturnType =
12394 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12395 QualType NewReturnType =
12396 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12397 QualType ResReturnType =
12398 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12399 if (ResReturnType.isNull())
12400 return {};
12401 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12402 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12403 // In either case, use OldReturnType to build the new function type.
12404 const auto *F = LHS->castAs<FunctionType>();
12405 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12406 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12407 EPI.ExtInfo = getFunctionExtInfo(LHS);
12408 QualType ResultType =
12409 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12410 return ResultType;
12411 }
12412 }
12413 return {};
12414 }
12415
12416 // If the qualifiers are different, the types can still be merged.
12417 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12418 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12419 if (LQuals != RQuals) {
12420 // If any of these qualifiers are different, we have a type mismatch.
12421 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12422 LQuals.getAddressSpace() != RQuals.getAddressSpace())
12423 return {};
12424
12425 // Exactly one GC qualifier difference is allowed: __strong is
12426 // okay if the other type has no GC qualifier but is an Objective
12427 // C object pointer (i.e. implicitly strong by default). We fix
12428 // this by pretending that the unqualified type was actually
12429 // qualified __strong.
12430 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12431 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12432 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12433
12434 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12435 return {};
12436
12437 if (GC_L == Qualifiers::Strong)
12438 return LHS;
12439 if (GC_R == Qualifiers::Strong)
12440 return RHS;
12441 return {};
12442 }
12443
12444 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12445 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12446 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12447 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12448 if (ResQT == LHSBaseQT)
12449 return LHS;
12450 if (ResQT == RHSBaseQT)
12451 return RHS;
12452 }
12453 return {};
12454}
12455
12456//===----------------------------------------------------------------------===//
12457// Integer Predicates
12458//===----------------------------------------------------------------------===//
12459
12461 if (const auto *ED = T->getAsEnumDecl())
12462 T = ED->getIntegerType();
12463 if (T->isBooleanType())
12464 return 1;
12465 if (const auto *EIT = T->getAs<BitIntType>())
12466 return EIT->getNumBits();
12467 // For builtin types, just use the standard type sizing method
12468 return (unsigned)getTypeSize(T);
12469}
12470
12472 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12473 T->isFixedPointType()) &&
12474 "Unexpected type");
12475
12476 // Turn <4 x signed int> -> <4 x unsigned int>
12477 if (const auto *VTy = T->getAs<VectorType>())
12478 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12479 VTy->getNumElements(), VTy->getVectorKind());
12480
12481 // For _BitInt, return an unsigned _BitInt with same width.
12482 if (const auto *EITy = T->getAs<BitIntType>())
12483 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12484
12485 // For the overflow behavior types, construct a new unsigned variant
12486 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12488 OBT->getBehaviorKind(),
12489 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12490
12491 // For enums, get the underlying integer type of the enum, and let the general
12492 // integer type signchanging code handle it.
12493 if (const auto *ED = T->getAsEnumDecl())
12494 T = ED->getIntegerType();
12495
12496 switch (T->castAs<BuiltinType>()->getKind()) {
12497 case BuiltinType::Char_U:
12498 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12499 case BuiltinType::Char_S:
12500 case BuiltinType::SChar:
12501 case BuiltinType::Char8:
12502 return UnsignedCharTy;
12503 case BuiltinType::Short:
12504 return UnsignedShortTy;
12505 case BuiltinType::Int:
12506 return UnsignedIntTy;
12507 case BuiltinType::Long:
12508 return UnsignedLongTy;
12509 case BuiltinType::LongLong:
12510 return UnsignedLongLongTy;
12511 case BuiltinType::Int128:
12512 return UnsignedInt128Ty;
12513 // wchar_t is special. It is either signed or not, but when it's signed,
12514 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12515 // version of its underlying type instead.
12516 case BuiltinType::WChar_S:
12517 return getUnsignedWCharType();
12518
12519 case BuiltinType::ShortAccum:
12520 return UnsignedShortAccumTy;
12521 case BuiltinType::Accum:
12522 return UnsignedAccumTy;
12523 case BuiltinType::LongAccum:
12524 return UnsignedLongAccumTy;
12525 case BuiltinType::SatShortAccum:
12527 case BuiltinType::SatAccum:
12528 return SatUnsignedAccumTy;
12529 case BuiltinType::SatLongAccum:
12531 case BuiltinType::ShortFract:
12532 return UnsignedShortFractTy;
12533 case BuiltinType::Fract:
12534 return UnsignedFractTy;
12535 case BuiltinType::LongFract:
12536 return UnsignedLongFractTy;
12537 case BuiltinType::SatShortFract:
12539 case BuiltinType::SatFract:
12540 return SatUnsignedFractTy;
12541 case BuiltinType::SatLongFract:
12543 default:
12544 assert((T->hasUnsignedIntegerRepresentation() ||
12545 T->isUnsignedFixedPointType()) &&
12546 "Unexpected signed integer or fixed point type");
12547 return T;
12548 }
12549}
12550
12552 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12553 T->isFixedPointType()) &&
12554 "Unexpected type");
12555
12556 // Turn <4 x unsigned int> -> <4 x signed int>
12557 if (const auto *VTy = T->getAs<VectorType>())
12558 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12559 VTy->getNumElements(), VTy->getVectorKind());
12560
12561 // For _BitInt, return a signed _BitInt with same width.
12562 if (const auto *EITy = T->getAs<BitIntType>())
12563 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12564
12565 // For enums, get the underlying integer type of the enum, and let the general
12566 // integer type signchanging code handle it.
12567 if (const auto *ED = T->getAsEnumDecl())
12568 T = ED->getIntegerType();
12569
12570 switch (T->castAs<BuiltinType>()->getKind()) {
12571 case BuiltinType::Char_S:
12572 // Plain `char` is mapped to `signed char` even if it's already signed
12573 case BuiltinType::Char_U:
12574 case BuiltinType::UChar:
12575 case BuiltinType::Char8:
12576 return SignedCharTy;
12577 case BuiltinType::UShort:
12578 return ShortTy;
12579 case BuiltinType::UInt:
12580 return IntTy;
12581 case BuiltinType::ULong:
12582 return LongTy;
12583 case BuiltinType::ULongLong:
12584 return LongLongTy;
12585 case BuiltinType::UInt128:
12586 return Int128Ty;
12587 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12588 // there's no matching "signed wchar_t". Therefore we return the signed
12589 // version of its underlying type instead.
12590 case BuiltinType::WChar_U:
12591 return getSignedWCharType();
12592
12593 case BuiltinType::UShortAccum:
12594 return ShortAccumTy;
12595 case BuiltinType::UAccum:
12596 return AccumTy;
12597 case BuiltinType::ULongAccum:
12598 return LongAccumTy;
12599 case BuiltinType::SatUShortAccum:
12600 return SatShortAccumTy;
12601 case BuiltinType::SatUAccum:
12602 return SatAccumTy;
12603 case BuiltinType::SatULongAccum:
12604 return SatLongAccumTy;
12605 case BuiltinType::UShortFract:
12606 return ShortFractTy;
12607 case BuiltinType::UFract:
12608 return FractTy;
12609 case BuiltinType::ULongFract:
12610 return LongFractTy;
12611 case BuiltinType::SatUShortFract:
12612 return SatShortFractTy;
12613 case BuiltinType::SatUFract:
12614 return SatFractTy;
12615 case BuiltinType::SatULongFract:
12616 return SatLongFractTy;
12617 default:
12618 assert(
12619 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12620 "Unexpected signed integer or fixed point type");
12621 return T;
12622 }
12623}
12624
12626
12629
12630//===----------------------------------------------------------------------===//
12631// Builtin Type Computation
12632//===----------------------------------------------------------------------===//
12633
12634/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12635/// pointer over the consumed characters. This returns the resultant type. If
12636/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12637/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12638/// a vector of "i*".
12639///
12640/// RequiresICE is filled in on return to indicate whether the value is required
12641/// to be an Integer Constant Expression.
12642static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12644 bool &RequiresICE,
12645 bool AllowTypeModifiers) {
12646 // Modifiers.
12647 int HowLong = 0;
12648 bool Signed = false, Unsigned = false;
12649 bool IsChar = false, IsShort = false;
12650 RequiresICE = false;
12651
12652 // Read the prefixed modifiers first.
12653 bool Done = false;
12654 #ifndef NDEBUG
12655 bool IsSpecial = false;
12656 #endif
12657 while (!Done) {
12658 switch (*Str++) {
12659 default: Done = true; --Str; break;
12660 case 'I':
12661 RequiresICE = true;
12662 break;
12663 case 'S':
12664 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12665 assert(!Signed && "Can't use 'S' modifier multiple times!");
12666 Signed = true;
12667 break;
12668 case 'U':
12669 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12670 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12671 Unsigned = true;
12672 break;
12673 case 'B':
12674 // This modifier represents int8 type (byte-width).
12675 assert(!IsSpecial &&
12676 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12677 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12678#ifndef NDEBUG
12679 IsSpecial = true;
12680#endif
12681 IsChar = true;
12682 break;
12683 case 'T':
12684 // This modifier represents int16 type (short-width).
12685 assert(!IsSpecial &&
12686 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12687 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12688#ifndef NDEBUG
12689 IsSpecial = true;
12690#endif
12691 IsShort = true;
12692 break;
12693 case 'L':
12694 assert(!IsSpecial &&
12695 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12696 assert(HowLong <= 2 && "Can't have LLLL modifier");
12697 ++HowLong;
12698 break;
12699 case 'N':
12700 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12701 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12702 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12703 #ifndef NDEBUG
12704 IsSpecial = true;
12705 #endif
12706 if (Context.getTargetInfo().getLongWidth() == 32)
12707 ++HowLong;
12708 break;
12709 case 'W':
12710 // This modifier represents int64 type.
12711 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12712 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12713 #ifndef NDEBUG
12714 IsSpecial = true;
12715 #endif
12716 switch (Context.getTargetInfo().getInt64Type()) {
12717 default:
12718 llvm_unreachable("Unexpected integer type");
12720 HowLong = 1;
12721 break;
12723 HowLong = 2;
12724 break;
12725 }
12726 break;
12727 case 'Z':
12728 // This modifier represents int32 type.
12729 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12730 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12731 #ifndef NDEBUG
12732 IsSpecial = true;
12733 #endif
12734 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12735 default:
12736 llvm_unreachable("Unexpected integer type");
12738 HowLong = 0;
12739 break;
12741 HowLong = 1;
12742 break;
12744 HowLong = 2;
12745 break;
12746 }
12747 break;
12748 case 'O':
12749 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12750 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12751 #ifndef NDEBUG
12752 IsSpecial = true;
12753 #endif
12754 if (Context.getLangOpts().OpenCL)
12755 HowLong = 1;
12756 else
12757 HowLong = 2;
12758 break;
12759 }
12760 }
12761
12762 QualType Type;
12763
12764 // Read the base type.
12765 switch (*Str++) {
12766 default:
12767 llvm_unreachable("Unknown builtin type letter!");
12768 case 'x':
12769 assert(HowLong == 0 && !Signed && !Unsigned &&
12770 "Bad modifiers used with 'x'!");
12771 Type = Context.Float16Ty;
12772 break;
12773 case 'y':
12774 assert(HowLong == 0 && !Signed && !Unsigned &&
12775 "Bad modifiers used with 'y'!");
12776 Type = Context.BFloat16Ty;
12777 break;
12778 case 'v':
12779 assert(HowLong == 0 && !Signed && !Unsigned &&
12780 "Bad modifiers used with 'v'!");
12781 Type = Context.VoidTy;
12782 break;
12783 case 'h':
12784 assert(HowLong == 0 && !Signed && !Unsigned &&
12785 "Bad modifiers used with 'h'!");
12786 Type = Context.HalfTy;
12787 break;
12788 case 'f':
12789 assert(HowLong == 0 && !Signed && !Unsigned &&
12790 "Bad modifiers used with 'f'!");
12791 Type = Context.FloatTy;
12792 break;
12793 case 'd':
12794 assert(HowLong < 3 && !Signed && !Unsigned &&
12795 "Bad modifiers used with 'd'!");
12796 if (HowLong == 1)
12797 Type = Context.LongDoubleTy;
12798 else if (HowLong == 2)
12799 Type = Context.Float128Ty;
12800 else
12801 Type = Context.DoubleTy;
12802 break;
12803 case 's':
12804 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12805 if (Unsigned)
12806 Type = Context.UnsignedShortTy;
12807 else
12808 Type = Context.ShortTy;
12809 break;
12810 case 'i':
12811 if (IsChar)
12812 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12813 else if (IsShort)
12814 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12815 else if (HowLong == 3)
12816 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12817 else if (HowLong == 2)
12818 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12819 else if (HowLong == 1)
12820 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12821 else
12822 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12823 break;
12824 case 'c':
12825 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12826 if (Signed)
12827 Type = Context.SignedCharTy;
12828 else if (Unsigned)
12829 Type = Context.UnsignedCharTy;
12830 else
12831 Type = Context.CharTy;
12832 break;
12833 case 'b': // boolean
12834 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12835 Type = Context.BoolTy;
12836 break;
12837 case 'z': // size_t.
12838 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12839 Type = Context.getSizeType();
12840 break;
12841 case 'w': // wchar_t.
12842 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12843 Type = Context.getWideCharType();
12844 break;
12845 case 'F':
12846 Type = Context.getCFConstantStringType();
12847 break;
12848 case 'G':
12849 Type = Context.getObjCIdType();
12850 break;
12851 case 'H':
12852 Type = Context.getObjCSelType();
12853 break;
12854 case 'M':
12855 Type = Context.getObjCSuperType();
12856 break;
12857 case 'a':
12858 Type = Context.getBuiltinVaListType();
12859 assert(!Type.isNull() && "builtin va list type not initialized!");
12860 break;
12861 case 'A':
12862 // This is a "reference" to a va_list; however, what exactly
12863 // this means depends on how va_list is defined. There are two
12864 // different kinds of va_list: ones passed by value, and ones
12865 // passed by reference. An example of a by-value va_list is
12866 // x86, where va_list is a char*. An example of by-ref va_list
12867 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12868 // we want this argument to be a char*&; for x86-64, we want
12869 // it to be a __va_list_tag*.
12870 Type = Context.getBuiltinVaListType();
12871 assert(!Type.isNull() && "builtin va list type not initialized!");
12872 if (Type->isArrayType())
12873 Type = Context.getArrayDecayedType(Type);
12874 else
12875 Type = Context.getLValueReferenceType(Type);
12876 break;
12877 case 'q': {
12878 char *End;
12879 unsigned NumElements = strtoul(Str, &End, 10);
12880 assert(End != Str && "Missing vector size");
12881 Str = End;
12882
12883 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12884 RequiresICE, false);
12885 assert(!RequiresICE && "Can't require vector ICE");
12886
12887 Type = Context.getScalableVectorType(ElementType, NumElements);
12888 break;
12889 }
12890 case 'Q': {
12891 switch (*Str++) {
12892 case 'a': {
12893 Type = Context.SveCountTy;
12894 break;
12895 }
12896 case 'b': {
12897 Type = Context.AMDGPUBufferRsrcTy;
12898 break;
12899 }
12900 case 'c': {
12901 Type = Context.AMDGPUFeaturePredicateTy;
12902 break;
12903 }
12904 case 't': {
12905 Type = Context.AMDGPUTextureTy;
12906 break;
12907 }
12908 case 'r': {
12909 Type = Context.HLSLResourceTy;
12910 break;
12911 }
12912 default:
12913 llvm_unreachable("Unexpected target builtin type");
12914 }
12915 break;
12916 }
12917 case 'V': {
12918 char *End;
12919 unsigned NumElements = strtoul(Str, &End, 10);
12920 assert(End != Str && "Missing vector size");
12921 Str = End;
12922
12923 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12924 RequiresICE, false);
12925 assert(!RequiresICE && "Can't require vector ICE");
12926
12927 // TODO: No way to make AltiVec vectors in builtins yet.
12928 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12929 break;
12930 }
12931 case 'E': {
12932 char *End;
12933
12934 unsigned NumElements = strtoul(Str, &End, 10);
12935 assert(End != Str && "Missing vector size");
12936
12937 Str = End;
12938
12939 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12940 false);
12941 Type = Context.getExtVectorType(ElementType, NumElements);
12942 break;
12943 }
12944 case 'X': {
12945 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12946 false);
12947 assert(!RequiresICE && "Can't require complex ICE");
12948 Type = Context.getComplexType(ElementType);
12949 break;
12950 }
12951 case 'Y':
12952 Type = Context.getPointerDiffType();
12953 break;
12954 case 'P':
12955 Type = Context.getFILEType();
12956 if (Type.isNull()) {
12958 return {};
12959 }
12960 break;
12961 case 'J':
12962 if (Signed)
12963 Type = Context.getsigjmp_bufType();
12964 else
12965 Type = Context.getjmp_bufType();
12966
12967 if (Type.isNull()) {
12969 return {};
12970 }
12971 break;
12972 case 'K':
12973 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
12974 Type = Context.getucontext_tType();
12975
12976 if (Type.isNull()) {
12978 return {};
12979 }
12980 break;
12981 case 'p':
12982 Type = Context.getProcessIDType();
12983 break;
12984 case 'm':
12985 Type = Context.MFloat8Ty;
12986 break;
12987 }
12988
12989 // If there are modifiers and if we're allowed to parse them, go for it.
12990 Done = !AllowTypeModifiers;
12991 while (!Done) {
12992 switch (char c = *Str++) {
12993 default: Done = true; --Str; break;
12994 case '*':
12995 case '&': {
12996 // Both pointers and references can have their pointee types
12997 // qualified with an address space.
12998 char *End;
12999 unsigned AddrSpace = strtoul(Str, &End, 10);
13000 if (End != Str) {
13001 // Note AddrSpace == 0 is not the same as an unspecified address space.
13002 Type = Context.getAddrSpaceQualType(
13003 Type,
13004 Context.getLangASForBuiltinAddressSpace(AddrSpace));
13005 Str = End;
13006 }
13007 if (c == '*')
13008 Type = Context.getPointerType(Type);
13009 else
13010 Type = Context.getLValueReferenceType(Type);
13011 break;
13012 }
13013 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13014 case 'C':
13015 Type = Type.withConst();
13016 break;
13017 case 'D':
13018 Type = Context.getVolatileType(Type);
13019 break;
13020 case 'R':
13021 Type = Type.withRestrict();
13022 break;
13023 }
13024 }
13025
13026 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13027 "Integer constant 'I' type must be an integer");
13028
13029 return Type;
13030}
13031
13032// On some targets such as PowerPC, some of the builtins are defined with custom
13033// type descriptors for target-dependent types. These descriptors are decoded in
13034// other functions, but it may be useful to be able to fall back to default
13035// descriptor decoding to define builtins mixing target-dependent and target-
13036// independent types. This function allows decoding one type descriptor with
13037// default decoding.
13038QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13039 GetBuiltinTypeError &Error, bool &RequireICE,
13040 bool AllowTypeModifiers) const {
13041 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13042}
13043
13044/// GetBuiltinType - Return the type for the specified builtin.
13047 unsigned *IntegerConstantArgs) const {
13048 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13049 if (TypeStr[0] == '\0') {
13051 return {};
13052 }
13053
13054 SmallVector<QualType, 8> ArgTypes;
13055
13056 bool RequiresICE = false;
13057 Error = GE_None;
13058 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13059 RequiresICE, true);
13060 if (Error != GE_None)
13061 return {};
13062
13063 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13064
13065 while (TypeStr[0] && TypeStr[0] != '.') {
13066 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13067 if (Error != GE_None)
13068 return {};
13069
13070 // If this argument is required to be an IntegerConstantExpression and the
13071 // caller cares, fill in the bitmask we return.
13072 if (RequiresICE && IntegerConstantArgs)
13073 *IntegerConstantArgs |= 1 << ArgTypes.size();
13074
13075 // Do array -> pointer decay. The builtin should use the decayed type.
13076 if (Ty->isArrayType())
13077 Ty = getArrayDecayedType(Ty);
13078
13079 ArgTypes.push_back(Ty);
13080 }
13081
13082 if (Id == Builtin::BI__GetExceptionInfo)
13083 return {};
13084
13085 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13086 "'.' should only occur at end of builtin type list!");
13087
13088 bool Variadic = (TypeStr[0] == '.');
13089
13090 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13091 if (BuiltinInfo.isNoReturn(Id))
13092 EI = EI.withNoReturn(true);
13093
13094 // We really shouldn't be making a no-proto type here.
13095 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13096 return getFunctionNoProtoType(ResType, EI);
13097
13099 EPI.ExtInfo = EI;
13100 EPI.Variadic = Variadic;
13101 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13102 EPI.ExceptionSpec.Type =
13104
13105 return getFunctionType(ResType, ArgTypes, EPI);
13106}
13107
13109 const FunctionDecl *FD) {
13110 if (!FD->isExternallyVisible())
13111 return GVA_Internal;
13112
13113 // Non-user-provided functions get emitted as weak definitions with every
13114 // use, no matter whether they've been explicitly instantiated etc.
13115 if (!FD->isUserProvided())
13116 return GVA_DiscardableODR;
13117
13119 switch (FD->getTemplateSpecializationKind()) {
13120 case TSK_Undeclared:
13123 break;
13124
13126 return GVA_StrongODR;
13127
13128 // C++11 [temp.explicit]p10:
13129 // [ Note: The intent is that an inline function that is the subject of
13130 // an explicit instantiation declaration will still be implicitly
13131 // instantiated when used so that the body can be considered for
13132 // inlining, but that no out-of-line copy of the inline function would be
13133 // generated in the translation unit. -- end note ]
13136
13139 break;
13140 }
13141
13142 if (!FD->isInlined())
13143 return External;
13144
13145 if ((!Context.getLangOpts().CPlusPlus &&
13146 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13147 !FD->hasAttr<DLLExportAttr>()) ||
13148 FD->hasAttr<GNUInlineAttr>()) {
13149 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13150
13151 // GNU or C99 inline semantics. Determine whether this symbol should be
13152 // externally visible.
13153 if (auto *Def = FD->getDefinition();
13155 return External;
13156
13157 // C99 inline semantics, where the symbol is not externally visible.
13159 }
13160
13161 // Functions specified with extern and inline in -fms-compatibility mode
13162 // forcibly get emitted. While the body of the function cannot be later
13163 // replaced, the function definition cannot be discarded.
13164 if (FD->isMSExternInline())
13165 return GVA_StrongODR;
13166
13167 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13169 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13170 !FD->hasAttr<DLLExportAttr>()) {
13171 // Both Clang and MSVC implement inherited constructors as forwarding
13172 // thunks that delegate to the base constructor. Keep non-dllexport
13173 // inheriting constructor thunks internal since they are not needed
13174 // outside the translation unit.
13175 //
13176 // dllexport inherited constructors are exempted so they are externally
13177 // visible, matching MSVC's export behavior. Inherited constructors
13178 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13179 // cleanup types) are excluded from export in Sema to avoid silent
13180 // runtime mismatches.
13181 return GVA_Internal;
13182 }
13183
13184 return GVA_DiscardableODR;
13185}
13186
13188 const Decl *D, GVALinkage L) {
13189 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13190 // dllexport/dllimport on inline functions.
13191 if (D->hasAttr<DLLImportAttr>()) {
13192 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13194 } else if (D->hasAttr<DLLExportAttr>()) {
13195 if (L == GVA_DiscardableODR)
13196 return GVA_StrongODR;
13197 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13198 // Device-side functions with __global__ attribute must always be
13199 // visible externally so they can be launched from host.
13200 if (D->hasAttr<CUDAGlobalAttr>() &&
13201 (L == GVA_DiscardableODR || L == GVA_Internal))
13202 return GVA_StrongODR;
13203 // Single source offloading languages like CUDA/HIP need to be able to
13204 // access static device variables from host code of the same compilation
13205 // unit. This is done by externalizing the static variable with a shared
13206 // name between the host and device compilation which is the same for the
13207 // same compilation unit whereas different among different compilation
13208 // units.
13209 if (Context.shouldExternalize(D))
13210 return GVA_StrongExternal;
13211 }
13212 return L;
13213}
13214
13215/// Adjust the GVALinkage for a declaration based on what an external AST source
13216/// knows about whether there can be other definitions of this declaration.
13217static GVALinkage
13219 GVALinkage L) {
13220 ExternalASTSource *Source = Ctx.getExternalSource();
13221 if (!Source)
13222 return L;
13223
13224 switch (Source->hasExternalDefinitions(D)) {
13226 // Other translation units rely on us to provide the definition.
13227 if (L == GVA_DiscardableODR)
13228 return GVA_StrongODR;
13229 break;
13230
13233
13235 break;
13236 }
13237 return L;
13238}
13239
13245
13247 const VarDecl *VD) {
13248 // As an extension for interactive REPLs, make sure constant variables are
13249 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13250 // marking them as internal.
13251 if (Context.getLangOpts().CPlusPlus &&
13252 Context.getLangOpts().IncrementalExtensions &&
13253 VD->getType().isConstQualified() &&
13254 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13256 return GVA_DiscardableODR;
13257
13258 if (!VD->isExternallyVisible())
13259 return GVA_Internal;
13260
13261 if (VD->isStaticLocal()) {
13262 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13263 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13264 LexicalContext = LexicalContext->getLexicalParent();
13265
13266 // ObjC Blocks can create local variables that don't have a FunctionDecl
13267 // LexicalContext.
13268 if (!LexicalContext)
13269 return GVA_DiscardableODR;
13270
13271 // Otherwise, let the static local variable inherit its linkage from the
13272 // nearest enclosing function.
13273 auto StaticLocalLinkage =
13274 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13275
13276 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13277 // be emitted in any object with references to the symbol for the object it
13278 // contains, whether inline or out-of-line."
13279 // Similar behavior is observed with MSVC. An alternative ABI could use
13280 // StrongODR/AvailableExternally to match the function, but none are
13281 // known/supported currently.
13282 if (StaticLocalLinkage == GVA_StrongODR ||
13283 StaticLocalLinkage == GVA_AvailableExternally)
13284 return GVA_DiscardableODR;
13285 return StaticLocalLinkage;
13286 }
13287
13288 // MSVC treats in-class initialized static data members as definitions.
13289 // By giving them non-strong linkage, out-of-line definitions won't
13290 // cause link errors.
13291 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13292 return GVA_DiscardableODR;
13293
13294 // Most non-template variables have strong linkage; inline variables are
13295 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13296 GVALinkage StrongLinkage;
13297 switch (Context.getInlineVariableDefinitionKind(VD)) {
13299 StrongLinkage = GVA_StrongExternal;
13300 break;
13303 StrongLinkage = GVA_DiscardableODR;
13304 break;
13306 StrongLinkage = GVA_StrongODR;
13307 break;
13308 }
13309
13310 switch (VD->getTemplateSpecializationKind()) {
13311 case TSK_Undeclared:
13312 return StrongLinkage;
13313
13315 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13316 VD->isStaticDataMember()
13318 : StrongLinkage;
13319
13321 return GVA_StrongODR;
13322
13325
13327 return GVA_DiscardableODR;
13328 }
13329
13330 llvm_unreachable("Invalid Linkage!");
13331}
13332
13338
13340 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13341 if (!VD->isFileVarDecl())
13342 return false;
13343 // Global named register variables (GNU extension) are never emitted.
13344 if (VD->getStorageClass() == SC_Register)
13345 return false;
13346 if (VD->getDescribedVarTemplate() ||
13348 return false;
13349 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13350 // We never need to emit an uninstantiated function template.
13351 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13352 return false;
13353 } else if (isa<PragmaCommentDecl>(D))
13354 return true;
13356 return true;
13357 else if (isa<OMPRequiresDecl>(D))
13358 return true;
13359 else if (isa<OMPThreadPrivateDecl>(D))
13360 return !D->getDeclContext()->isDependentContext();
13361 else if (isa<OMPAllocateDecl>(D))
13362 return !D->getDeclContext()->isDependentContext();
13364 return !D->getDeclContext()->isDependentContext();
13365 else if (isa<ImportDecl>(D))
13366 return true;
13367 else
13368 return false;
13369
13370 // If this is a member of a class template, we do not need to emit it.
13372 return false;
13373
13374 // Weak references don't produce any output by themselves.
13375 if (D->hasAttr<WeakRefAttr>())
13376 return false;
13377
13378 // SYCL device compilation requires that functions defined with the
13379 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13380 // other entities are emitted only if they are used by a function
13381 // defined with one of those attributes.
13382 if (LangOpts.SYCLIsDevice)
13383 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13384 D->hasAttr<SYCLExternalAttr>());
13385
13386 // Aliases and used decls are required.
13387 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13388 return true;
13389
13390 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13391 // Forward declarations aren't required.
13392 if (!FD->doesThisDeclarationHaveABody())
13393 return FD->doesDeclarationForceExternallyVisibleDefinition();
13394
13395 // Constructors and destructors are required.
13396 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13397 return true;
13398
13399 // The key function for a class is required. This rule only comes
13400 // into play when inline functions can be key functions, though.
13401 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13402 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13403 const CXXRecordDecl *RD = MD->getParent();
13404 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13405 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13406 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13407 return true;
13408 }
13409 }
13410 }
13411
13413
13414 // static, static inline, always_inline, and extern inline functions can
13415 // always be deferred. Normal inline functions can be deferred in C99/C++.
13416 // Implicit template instantiations can also be deferred in C++.
13418 }
13419
13420 const auto *VD = cast<VarDecl>(D);
13421 assert(VD->isFileVarDecl() && "Expected file scoped var");
13422
13423 // If the decl is marked as `declare target to`, it should be emitted for the
13424 // host and for the device.
13425 if (LangOpts.OpenMP &&
13426 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13427 return true;
13428
13429 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13431 return false;
13432
13433 if (VD->shouldEmitInExternalSource())
13434 return false;
13435
13436 // Variables that can be needed in other TUs are required.
13439 return true;
13440
13441 // We never need to emit a variable that is available in another TU.
13443 return false;
13444
13445 // Variables that have destruction with side-effects are required.
13446 if (VD->needsDestruction(*this))
13447 return true;
13448
13449 // Variables that have initialization with side-effects are required.
13450 if (VD->hasInitWithSideEffects())
13451 return true;
13452
13453 // Likewise, variables with tuple-like bindings are required if their
13454 // bindings have side-effects.
13455 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13456 for (const auto *BD : DD->flat_bindings())
13457 if (const auto *BindingVD = BD->getHoldingVar())
13458 if (DeclMustBeEmitted(BindingVD))
13459 return true;
13460 }
13461
13462 return false;
13463}
13464
13466 const FunctionDecl *FD,
13467 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13468 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13469 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13470 FD = FD->getMostRecentDecl();
13471 // FIXME: The order of traversal here matters and depends on the order of
13472 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13473 // shouldn't rely on that.
13474 for (auto *CurDecl :
13476 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13477 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13478 SeenDecls.insert(CurFD).second) {
13479 Pred(CurFD);
13480 }
13481 }
13482}
13483
13485 bool IsCXXMethod) const {
13486 // Pass through to the C++ ABI object
13487 if (IsCXXMethod)
13488 return ABI->getDefaultMethodCallConv(IsVariadic);
13489
13490 switch (LangOpts.getDefaultCallingConv()) {
13492 break;
13494 return CC_C;
13496 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13497 return CC_X86FastCall;
13498 break;
13500 if (!IsVariadic)
13501 return CC_X86StdCall;
13502 break;
13504 // __vectorcall cannot be applied to variadic functions.
13505 if (!IsVariadic)
13506 return CC_X86VectorCall;
13507 break;
13509 // __regcall cannot be applied to variadic functions.
13510 if (!IsVariadic)
13511 return CC_X86RegCall;
13512 break;
13514 if (!IsVariadic)
13515 return CC_M68kRTD;
13516 break;
13517 }
13518 return Target->getDefaultCallingConv();
13519}
13520
13522 // Pass through to the C++ ABI object
13523 return ABI->isNearlyEmpty(RD);
13524}
13525
13527 if (!VTContext) {
13528 auto ABI = Target->getCXXABI();
13529 if (ABI.isMicrosoft())
13530 VTContext.reset(new MicrosoftVTableContext(*this));
13531 else {
13532 VTContext.reset(new ItaniumVTableContext(*this));
13533 }
13534 }
13535 return VTContext.get();
13536}
13537
13539 if (!T)
13540 T = Target;
13541 switch (T->getCXXABI().getKind()) {
13542 case TargetCXXABI::AppleARM64:
13543 case TargetCXXABI::Fuchsia:
13544 case TargetCXXABI::GenericAArch64:
13545 case TargetCXXABI::GenericItanium:
13546 case TargetCXXABI::GenericARM:
13547 case TargetCXXABI::GenericMIPS:
13548 case TargetCXXABI::iOS:
13549 case TargetCXXABI::WebAssembly:
13550 case TargetCXXABI::WatchOS:
13551 case TargetCXXABI::XL:
13553 case TargetCXXABI::Microsoft:
13555 }
13556 llvm_unreachable("Unsupported ABI");
13557}
13558
13560 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13561 "Device mangle context does not support Microsoft mangling.");
13562 switch (T.getCXXABI().getKind()) {
13563 case TargetCXXABI::AppleARM64:
13564 case TargetCXXABI::Fuchsia:
13565 case TargetCXXABI::GenericAArch64:
13566 case TargetCXXABI::GenericItanium:
13567 case TargetCXXABI::GenericARM:
13568 case TargetCXXABI::GenericMIPS:
13569 case TargetCXXABI::iOS:
13570 case TargetCXXABI::WebAssembly:
13571 case TargetCXXABI::WatchOS:
13572 case TargetCXXABI::XL:
13574 *this, getDiagnostics(),
13575 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13576 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13577 return RD->getDeviceLambdaManglingNumber();
13578 return std::nullopt;
13579 },
13580 /*IsAux=*/true);
13581 case TargetCXXABI::Microsoft:
13583 /*IsAux=*/true);
13584 }
13585 llvm_unreachable("Unsupported ABI");
13586}
13587
13589 // If the host and device have different C++ ABIs, mark it as the device
13590 // mangle context so that the mangling needs to retrieve the additional
13591 // device lambda mangling number instead of the regular host one.
13592 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13593 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13595 }
13596
13598}
13599
13600CXXABI::~CXXABI() = default;
13601
13603 return ASTRecordLayouts.getMemorySize() +
13604 llvm::capacity_in_bytes(ObjCLayouts) +
13605 llvm::capacity_in_bytes(KeyFunctions) +
13606 llvm::capacity_in_bytes(ObjCImpls) +
13607 llvm::capacity_in_bytes(BlockVarCopyInits) +
13608 llvm::capacity_in_bytes(DeclAttrs) +
13609 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13610 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13611 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13612 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13613 llvm::capacity_in_bytes(OverriddenMethods) +
13614 llvm::capacity_in_bytes(Types) +
13615 llvm::capacity_in_bytes(VariableArrayTypes);
13616}
13617
13618/// getIntTypeForBitwidth -
13619/// sets integer QualTy according to specified details:
13620/// bitwidth, signed/unsigned.
13621/// Returns empty type if there is no appropriate target types.
13623 unsigned Signed) const {
13625 CanQualType QualTy = getFromTargetType(Ty);
13626 if (!QualTy && DestWidth == 128)
13627 return Signed ? Int128Ty : UnsignedInt128Ty;
13628 return QualTy;
13629}
13630
13632 unsigned Signed) const {
13633 return getFromTargetType(
13634 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13635}
13636
13637/// getRealTypeForBitwidth -
13638/// sets floating point QualTy according to specified bitwidth.
13639/// Returns empty type if there is no appropriate target types.
13641 FloatModeKind ExplicitType) const {
13642 FloatModeKind Ty =
13643 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13644 switch (Ty) {
13646 return HalfTy;
13648 return FloatTy;
13650 return DoubleTy;
13652 return LongDoubleTy;
13654 return Float128Ty;
13656 return Ibm128Ty;
13658 return {};
13659 }
13660
13661 llvm_unreachable("Unhandled TargetInfo::RealType value");
13662}
13663
13664void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13665 if (Number <= 1)
13666 return;
13667
13668 MangleNumbers[ND] = Number;
13669
13670 if (Listener)
13671 Listener->AddedManglingNumber(ND, Number);
13672}
13673
13675 bool ForAuxTarget) const {
13676 auto I = MangleNumbers.find(ND);
13677 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13678 // CUDA/HIP host compilation encodes host and device mangling numbers
13679 // as lower and upper half of 32 bit integer.
13680 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13681 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13682 } else {
13683 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13684 "number for aux target");
13685 }
13686 return Res > 1 ? Res : 1;
13687}
13688
13689void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13690 if (Number <= 1)
13691 return;
13692
13693 StaticLocalNumbers[VD] = Number;
13694
13695 if (Listener)
13696 Listener->AddedStaticLocalNumbers(VD, Number);
13697}
13698
13700 auto I = StaticLocalNumbers.find(VD);
13701 return I != StaticLocalNumbers.end() ? I->second : 1;
13702}
13703
13705 bool IsDestroying) {
13706 if (!IsDestroying) {
13707 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13708 return;
13709 }
13710 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13711}
13712
13714 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13715}
13716
13718 bool IsTypeAware) {
13719 if (!IsTypeAware) {
13720 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13721 return;
13722 }
13723 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13724}
13725
13727 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13728}
13729
13731 FunctionDecl *OperatorDelete,
13732 OperatorDeleteKind K) const {
13733 switch (K) {
13735 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13736 break;
13738 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13739 OperatorDelete;
13740 break;
13742 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13743 OperatorDelete;
13744 break;
13746 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13747 OperatorDelete;
13748 break;
13749 }
13750}
13751
13753 OperatorDeleteKind K) const {
13754 switch (K) {
13756 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13758 return GlobalOperatorDeletesForVirtualDtor.contains(
13759 Dtor->getCanonicalDecl());
13761 return ArrayOperatorDeletesForVirtualDtor.contains(
13762 Dtor->getCanonicalDecl());
13764 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13765 Dtor->getCanonicalDecl());
13766 }
13767 return false;
13768}
13769
13772 OperatorDeleteKind K) const {
13773 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13774 switch (K) {
13776 if (OperatorDeletesForVirtualDtor.contains(Canon))
13777 return OperatorDeletesForVirtualDtor[Canon];
13778 return nullptr;
13780 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13781 return GlobalOperatorDeletesForVirtualDtor[Canon];
13782 return nullptr;
13784 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13785 return ArrayOperatorDeletesForVirtualDtor[Canon];
13786 return nullptr;
13788 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13789 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13790 return nullptr;
13791 }
13792 return nullptr;
13793}
13794
13796 const CXXRecordDecl *RD) {
13797 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13798 return false;
13799
13800 return MaybeRequireVectorDeletingDtor.count(RD);
13801}
13802
13804 const CXXRecordDecl *RD) {
13805 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13806 return;
13807
13808 MaybeRequireVectorDeletingDtor.insert(RD);
13809}
13810
13813 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13814 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13815 if (!MCtx)
13817 return *MCtx;
13818}
13819
13822 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13823 std::unique_ptr<MangleNumberingContext> &MCtx =
13824 ExtraMangleNumberingContexts[D];
13825 if (!MCtx)
13827 return *MCtx;
13828}
13829
13830std::unique_ptr<MangleNumberingContext>
13832 return ABI->createMangleNumberingContext();
13833}
13834
13835const CXXConstructorDecl *
13837 return ABI->getCopyConstructorForExceptionObject(
13839}
13840
13842 CXXConstructorDecl *CD) {
13843 return ABI->addCopyConstructorForExceptionObject(
13846}
13847
13849 TypedefNameDecl *DD) {
13850 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13851}
13852
13855 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13856}
13857
13859 DeclaratorDecl *DD) {
13860 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13861}
13862
13864 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13865}
13866
13868 ParamIndices[D] = index;
13869}
13870
13872 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13873 assert(I != ParamIndices.end() &&
13874 "ParmIndices lacks entry set by ParmVarDecl");
13875 return I->second;
13876}
13877
13879 unsigned Length) const {
13880 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13881 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13882 EltTy = EltTy.withConst();
13883
13884 EltTy = adjustStringLiteralBaseType(EltTy);
13885
13886 // Get an array type for the string, according to C99 6.4.5. This includes
13887 // the null terminator character.
13888 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13889 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13890}
13891
13894 StringLiteral *&Result = StringLiteralCache[Key];
13895 if (!Result)
13897 *this, Key, StringLiteralKind::Ordinary,
13898 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13899 SourceLocation());
13900 return Result;
13901}
13902
13903MSGuidDecl *
13905 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13906
13907 llvm::FoldingSetNodeID ID;
13908 MSGuidDecl::Profile(ID, Parts);
13909
13910 void *InsertPos;
13911 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
13912 return Existing;
13913
13914 QualType GUIDType = getMSGuidType().withConst();
13915 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13916 MSGuidDecls.InsertNode(New, InsertPos);
13917 return New;
13918}
13919
13922 const APValue &APVal) const {
13923 llvm::FoldingSetNodeID ID;
13925
13926 void *InsertPos;
13927 if (UnnamedGlobalConstantDecl *Existing =
13928 UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
13929 return Existing;
13930
13932 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
13933 UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
13934 return New;
13935}
13936
13939 assert(T->isRecordType() && "template param object of unexpected type");
13940
13941 // C++ [temp.param]p8:
13942 // [...] a static storage duration object of type 'const T' [...]
13943 T.addConst();
13944
13945 llvm::FoldingSetNodeID ID;
13947
13948 void *InsertPos;
13949 if (TemplateParamObjectDecl *Existing =
13950 TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
13951 return Existing;
13952
13953 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
13954 TemplateParamObjectDecls.InsertNode(New, InsertPos);
13955 return New;
13956}
13957
13959 const llvm::Triple &T = getTargetInfo().getTriple();
13960 if (!T.isOSDarwin())
13961 return false;
13962
13963 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
13964 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
13965 return false;
13966
13967 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
13968 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
13969 uint64_t Size = sizeChars.getQuantity();
13970 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
13971 unsigned Align = alignChars.getQuantity();
13972 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
13973 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
13974}
13975
13976bool
13978 const ObjCMethodDecl *MethodImpl) {
13979 // No point trying to match an unavailable/deprecated mothod.
13980 if (MethodDecl->hasAttr<UnavailableAttr>()
13981 || MethodDecl->hasAttr<DeprecatedAttr>())
13982 return false;
13983 if (MethodDecl->getObjCDeclQualifier() !=
13984 MethodImpl->getObjCDeclQualifier())
13985 return false;
13986 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
13987 return false;
13988
13989 if (MethodDecl->param_size() != MethodImpl->param_size())
13990 return false;
13991
13992 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
13993 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
13994 EF = MethodDecl->param_end();
13995 IM != EM && IF != EF; ++IM, ++IF) {
13996 const ParmVarDecl *DeclVar = (*IF);
13997 const ParmVarDecl *ImplVar = (*IM);
13998 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
13999 return false;
14000 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
14001 return false;
14002 }
14003
14004 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14005}
14006
14008 LangAS AS;
14010 AS = LangAS::Default;
14011 else
14012 AS = QT->getPointeeType().getAddressSpace();
14013
14015}
14016
14019}
14020
14021bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14022 if (X == Y)
14023 return true;
14024 if (!X || !Y)
14025 return false;
14026 llvm::FoldingSetNodeID IDX, IDY;
14027 X->Profile(IDX, *this, /*Canonical=*/true);
14028 Y->Profile(IDY, *this, /*Canonical=*/true);
14029 return IDX == IDY;
14030}
14031
14032// The getCommon* helpers return, for given 'same' X and Y entities given as
14033// inputs, another entity which is also the 'same' as the inputs, but which
14034// is closer to the canonical form of the inputs, each according to a given
14035// criteria.
14036// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14037// the regular ones.
14038
14040 if (!declaresSameEntity(X, Y))
14041 return nullptr;
14042 for (const Decl *DX : X->redecls()) {
14043 // If we reach Y before reaching the first decl, that means X is older.
14044 if (DX == Y)
14045 return X;
14046 // If we reach the first decl, then Y is older.
14047 if (DX->isFirstDecl())
14048 return Y;
14049 }
14050 llvm_unreachable("Corrupt redecls chain");
14051}
14052
14053template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14054static T *getCommonDecl(T *X, T *Y) {
14055 return cast_or_null<T>(
14056 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14057 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14058}
14059
14060template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14061static T *getCommonDeclChecked(T *X, T *Y) {
14062 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14063 const_cast<Decl *>(cast<Decl>(Y))));
14064}
14065
14067 TemplateName Y,
14068 bool IgnoreDeduced = false) {
14069 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14070 return X;
14071 // FIXME: There are cases here where we could find a common template name
14072 // with more sugar. For example one could be a SubstTemplateTemplate*
14073 // replacing the other.
14074 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14075 if (CX.getAsVoidPointer() !=
14077 return TemplateName();
14078 return CX;
14079}
14080
14083 bool IgnoreDeduced) {
14084 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14085 assert(R.getAsVoidPointer() != nullptr);
14086 return R;
14087}
14088
14090 ArrayRef<QualType> Ys, bool Unqualified = false) {
14091 assert(Xs.size() == Ys.size());
14092 SmallVector<QualType, 8> Rs(Xs.size());
14093 for (size_t I = 0; I < Rs.size(); ++I)
14094 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14095 return Rs;
14096}
14097
14098template <class T>
14099static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14100 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14101 : SourceLocation();
14102}
14103
14105 const TemplateArgument &X,
14106 const TemplateArgument &Y) {
14107 if (X.getKind() != Y.getKind())
14108 return TemplateArgument();
14109
14110 switch (X.getKind()) {
14112 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14113 return TemplateArgument();
14114 return TemplateArgument(
14115 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14117 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14118 return TemplateArgument();
14119 return TemplateArgument(
14120 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14121 /*Unqualified=*/true);
14123 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14124 return TemplateArgument();
14125 // FIXME: Try to keep the common sugar.
14126 return X;
14128 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14129 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14130 if (!CTN.getAsVoidPointer())
14131 return TemplateArgument();
14132 return TemplateArgument(CTN);
14133 }
14135 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14137 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14138 if (!CTN.getAsVoidPointer())
14139 return TemplateName();
14140 auto NExpX = X.getNumTemplateExpansions();
14141 assert(NExpX == Y.getNumTemplateExpansions());
14142 return TemplateArgument(CTN, NExpX);
14143 }
14144 default:
14145 // FIXME: Handle the other argument kinds.
14146 return X;
14147 }
14148}
14149
14154 if (Xs.size() != Ys.size())
14155 return true;
14156 R.resize(Xs.size());
14157 for (size_t I = 0; I < R.size(); ++I) {
14158 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14159 if (R[I].isNull())
14160 return true;
14161 }
14162 return false;
14163}
14164
14169 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14170 assert(!Different);
14171 (void)Different;
14172 return R;
14173}
14174
14175template <class T>
14177 bool IsSame) {
14178 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14179 if (KX == KY)
14180 return KX;
14182 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14183 return KX;
14184}
14185
14186/// Returns a NestedNameSpecifier which has only the common sugar
14187/// present in both NNS1 and NNS2.
14190 NestedNameSpecifier NNS2, bool IsSame) {
14191 // If they are identical, all sugar is common.
14192 if (NNS1 == NNS2)
14193 return NNS1;
14194
14195 // IsSame implies both Qualifiers are equivalent.
14196 NestedNameSpecifier Canon = NNS1.getCanonical();
14197 if (Canon != NNS2.getCanonical()) {
14198 assert(!IsSame && "Should be the same NestedNameSpecifier");
14199 // If they are not the same, there is nothing to unify.
14200 return std::nullopt;
14201 }
14202
14203 NestedNameSpecifier R = std::nullopt;
14204 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14205 assert(Kind == NNS2.getKind());
14206 switch (Kind) {
14208 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14209 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14210 auto Kind = Namespace1->getKind();
14211 if (Kind != Namespace2->getKind() ||
14212 (Kind == Decl::NamespaceAlias &&
14213 !declaresSameEntity(Namespace1, Namespace2))) {
14215 Ctx,
14216 ::getCommonDeclChecked(Namespace1->getNamespace(),
14217 Namespace2->getNamespace()),
14218 /*Prefix=*/std::nullopt);
14219 break;
14220 }
14221 // The prefixes for namespaces are not significant, its declaration
14222 // identifies it uniquely.
14223 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14224 /*IsSame=*/false);
14225 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14226 Prefix);
14227 break;
14228 }
14230 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14231 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14232 /*Unqualified=*/true)
14233 .getTypePtr();
14235 break;
14236 }
14238 // FIXME: Can __super even be used with data members?
14239 // If it's only usable in functions, we will never see it here,
14240 // unless we save the qualifiers used in function types.
14241 // In that case, it might be possible NNS2 is a type,
14242 // in which case we should degrade the result to
14243 // a CXXRecordType.
14245 NNS2.getAsMicrosoftSuper()));
14246 break;
14247 }
14250 // These are singletons.
14251 llvm_unreachable("singletons did not compare equal");
14252 }
14253 assert(R.getCanonical() == Canon);
14254 return R;
14255}
14256
14257template <class T>
14259 const T *Y, bool IsSame) {
14260 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14261}
14262
14263template <class T>
14264static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14265 const T *Y) {
14266 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14267}
14268
14270 QualType X, QualType Y,
14271 Qualifiers &QX,
14272 Qualifiers &QY) {
14273 QualType R = Ctx.getCommonSugaredType(X, Y,
14274 /*Unqualified=*/true);
14275 // Qualifiers common to both element types.
14276 Qualifiers RQ = R.getQualifiers();
14277 // For each side, move to the top level any qualifiers which are not common to
14278 // both element types. The caller must assume top level qualifiers might
14279 // be different, even if they are the same type, and can be treated as sugar.
14280 QX += X.getQualifiers() - RQ;
14281 QY += Y.getQualifiers() - RQ;
14282 return R;
14283}
14284
14285template <class T>
14287 Qualifiers &QX, const T *Y,
14288 Qualifiers &QY) {
14289 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14290 Y->getElementType(), QX, QY);
14291}
14292
14293template <class T>
14294static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14295 const T *Y) {
14296 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14297}
14298
14299template <class T>
14300static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14301 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14302 return X->getSizeExpr();
14303}
14304
14305static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14306 assert(X->getSizeModifier() == Y->getSizeModifier());
14307 return X->getSizeModifier();
14308}
14309
14311 const ArrayType *Y) {
14312 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14313 return X->getIndexTypeCVRQualifiers();
14314}
14315
14316// Merges two type lists such that the resulting vector will contain
14317// each type (in a canonical sense) only once, in the order they appear
14318// from X to Y. If they occur in both X and Y, the result will contain
14319// the common sugared type between them.
14320static void mergeTypeLists(const ASTContext &Ctx,
14323 llvm::DenseMap<QualType, unsigned> Found;
14324 for (auto Ts : {X, Y}) {
14325 for (QualType T : Ts) {
14326 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14327 if (!Res.second) {
14328 QualType &U = Out[Res.first->second];
14329 U = Ctx.getCommonSugaredType(U, T);
14330 } else {
14331 Out.emplace_back(T);
14332 }
14333 }
14334 }
14335}
14336
14337FunctionProtoType::ExceptionSpecInfo
14340 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14341 bool AcceptDependent) const {
14342 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14343
14344 // If either of them can throw anything, that is the result.
14345 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14346 if (EST1 == I)
14347 return ESI1;
14348 if (EST2 == I)
14349 return ESI2;
14350 }
14351
14352 // If either of them is non-throwing, the result is the other.
14353 for (auto I :
14355 if (EST1 == I)
14356 return ESI2;
14357 if (EST2 == I)
14358 return ESI1;
14359 }
14360
14361 // If we're left with value-dependent computed noexcept expressions, we're
14362 // stuck. Before C++17, we can just drop the exception specification entirely,
14363 // since it's not actually part of the canonical type. And this should never
14364 // happen in C++17, because it would mean we were computing the composite
14365 // pointer type of dependent types, which should never happen.
14366 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14367 assert(AcceptDependent &&
14368 "computing composite pointer type of dependent types");
14370 }
14371
14372 // Switch over the possibilities so that people adding new values know to
14373 // update this function.
14374 switch (EST1) {
14375 case EST_None:
14376 case EST_DynamicNone:
14377 case EST_MSAny:
14378 case EST_BasicNoexcept:
14380 case EST_NoexceptFalse:
14381 case EST_NoexceptTrue:
14382 case EST_NoThrow:
14383 llvm_unreachable("These ESTs should be handled above");
14384
14385 case EST_Dynamic: {
14386 // This is the fun case: both exception specifications are dynamic. Form
14387 // the union of the two lists.
14388 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14389 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14390 ESI2.Exceptions);
14392 Result.Exceptions = ExceptionTypeStorage;
14393 return Result;
14394 }
14395
14396 case EST_Unevaluated:
14397 case EST_Uninstantiated:
14398 case EST_Unparsed:
14399 llvm_unreachable("shouldn't see unresolved exception specifications here");
14400 }
14401
14402 llvm_unreachable("invalid ExceptionSpecificationType");
14403}
14404
14406 Qualifiers &QX, const Type *Y,
14407 Qualifiers &QY) {
14408 Type::TypeClass TC = X->getTypeClass();
14409 assert(TC == Y->getTypeClass());
14410 switch (TC) {
14411#define UNEXPECTED_TYPE(Class, Kind) \
14412 case Type::Class: \
14413 llvm_unreachable("Unexpected " Kind ": " #Class);
14414
14415#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14416#define TYPE(Class, Base)
14417#include "clang/AST/TypeNodes.inc"
14418
14419#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14421 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14422 SUGAR_FREE_TYPE(DependentBitInt)
14424 SUGAR_FREE_TYPE(ObjCInterface)
14425 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14426 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14427 SUGAR_FREE_TYPE(UnresolvedUsing)
14428 SUGAR_FREE_TYPE(HLSLAttributedResource)
14429 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14430#undef SUGAR_FREE_TYPE
14431#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14432 NON_UNIQUE_TYPE(TypeOfExpr)
14433 NON_UNIQUE_TYPE(VariableArray)
14434#undef NON_UNIQUE_TYPE
14435
14436 UNEXPECTED_TYPE(TypeOf, "sugar")
14437
14438#undef UNEXPECTED_TYPE
14439
14440 case Type::Auto: {
14441 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14442 assert(AX->getDeducedKind() == AY->getDeducedKind());
14443 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14444 assert(AX->getKeyword() == AY->getKeyword());
14445 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14446 AY->getTypeConstraintConcept());
14448 if (CD &&
14449 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14450 AY->getTypeConstraintArguments())) {
14451 CD = nullptr; // The arguments differ, so make it unconstrained.
14452 As.clear();
14453 }
14454 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14455 CD, As);
14456 }
14457 case Type::IncompleteArray: {
14458 const auto *AX = cast<IncompleteArrayType>(X),
14460 return Ctx.getIncompleteArrayType(
14461 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14463 }
14464 case Type::DependentSizedArray: {
14465 const auto *AX = cast<DependentSizedArrayType>(X),
14467 return Ctx.getDependentSizedArrayType(
14468 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14469 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14471 }
14472 case Type::ConstantArray: {
14473 const auto *AX = cast<ConstantArrayType>(X),
14474 *AY = cast<ConstantArrayType>(Y);
14475 assert(AX->getSize() == AY->getSize());
14476 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14477 ? AX->getSizeExpr()
14478 : nullptr;
14479 return Ctx.getConstantArrayType(
14480 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14482 }
14483 case Type::ArrayParameter: {
14484 const auto *AX = cast<ArrayParameterType>(X),
14485 *AY = cast<ArrayParameterType>(Y);
14486 assert(AX->getSize() == AY->getSize());
14487 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14488 ? AX->getSizeExpr()
14489 : nullptr;
14490 auto ArrayTy = Ctx.getConstantArrayType(
14491 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14493 return Ctx.getArrayParameterType(ArrayTy);
14494 }
14495 case Type::Atomic: {
14496 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14497 return Ctx.getAtomicType(
14498 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14499 }
14500 case Type::Complex: {
14501 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14502 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14503 }
14504 case Type::Pointer: {
14505 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14506 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14507 }
14508 case Type::BlockPointer: {
14509 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14510 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14511 }
14512 case Type::ObjCObjectPointer: {
14513 const auto *PX = cast<ObjCObjectPointerType>(X),
14515 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14516 }
14517 case Type::MemberPointer: {
14518 const auto *PX = cast<MemberPointerType>(X),
14519 *PY = cast<MemberPointerType>(Y);
14520 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14521 PY->getMostRecentCXXRecordDecl()));
14522 return Ctx.getMemberPointerType(
14523 getCommonPointeeType(Ctx, PX, PY),
14524 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14525 PX->getMostRecentCXXRecordDecl());
14526 }
14527 case Type::LValueReference: {
14528 const auto *PX = cast<LValueReferenceType>(X),
14530 // FIXME: Preserve PointeeTypeAsWritten.
14531 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14532 PX->isSpelledAsLValue() ||
14533 PY->isSpelledAsLValue());
14534 }
14535 case Type::RValueReference: {
14536 const auto *PX = cast<RValueReferenceType>(X),
14538 // FIXME: Preserve PointeeTypeAsWritten.
14539 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14540 }
14541 case Type::DependentAddressSpace: {
14542 const auto *PX = cast<DependentAddressSpaceType>(X),
14544 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14545 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14546 PX->getAddrSpaceExpr(),
14547 getCommonAttrLoc(PX, PY));
14548 }
14549 case Type::FunctionNoProto: {
14550 const auto *FX = cast<FunctionNoProtoType>(X),
14552 assert(FX->getExtInfo() == FY->getExtInfo());
14553 return Ctx.getFunctionNoProtoType(
14554 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14555 FX->getExtInfo());
14556 }
14557 case Type::FunctionProto: {
14558 const auto *FX = cast<FunctionProtoType>(X),
14559 *FY = cast<FunctionProtoType>(Y);
14560 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14561 EPIY = FY->getExtProtoInfo();
14562 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14563 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14564 assert(!EPIX.ExtParameterInfos ||
14565 llvm::equal(
14566 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14567 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14568 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14569 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14570 assert(EPIX.Variadic == EPIY.Variadic);
14571
14572 // FIXME: Can we handle an empty EllipsisLoc?
14573 // Use emtpy EllipsisLoc if X and Y differ.
14574
14575 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14576
14577 QualType R =
14578 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14579 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14580 /*Unqualified=*/true);
14581
14582 SmallVector<QualType, 8> Exceptions;
14584 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14585 return Ctx.getFunctionType(R, P, EPIX);
14586 }
14587 case Type::ObjCObject: {
14588 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14589 assert(
14590 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14591 OY->getProtocols().begin(), OY->getProtocols().end(),
14592 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14593 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14594 }) &&
14595 "protocol lists must be the same");
14596 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14597 OY->getTypeArgsAsWritten());
14598 return Ctx.getObjCObjectType(
14599 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14600 OX->getProtocols(),
14601 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14602 }
14603 case Type::ConstantMatrix: {
14604 const auto *MX = cast<ConstantMatrixType>(X),
14605 *MY = cast<ConstantMatrixType>(Y);
14606 assert(MX->getNumRows() == MY->getNumRows());
14607 assert(MX->getNumColumns() == MY->getNumColumns());
14608 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14609 MX->getNumRows(), MX->getNumColumns());
14610 }
14611 case Type::DependentSizedMatrix: {
14612 const auto *MX = cast<DependentSizedMatrixType>(X),
14614 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14615 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14616 return Ctx.getDependentSizedMatrixType(
14617 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14618 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14619 }
14620 case Type::Vector: {
14621 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14622 assert(VX->getNumElements() == VY->getNumElements());
14623 assert(VX->getVectorKind() == VY->getVectorKind());
14624 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14625 VX->getNumElements(), VX->getVectorKind());
14626 }
14627 case Type::ExtVector: {
14628 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14629 assert(VX->getNumElements() == VY->getNumElements());
14630 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14631 VX->getNumElements());
14632 }
14633 case Type::DependentSizedExtVector: {
14634 const auto *VX = cast<DependentSizedExtVectorType>(X),
14637 getCommonSizeExpr(Ctx, VX, VY),
14638 getCommonAttrLoc(VX, VY));
14639 }
14640 case Type::DependentVector: {
14641 const auto *VX = cast<DependentVectorType>(X),
14643 assert(VX->getVectorKind() == VY->getVectorKind());
14644 return Ctx.getDependentVectorType(
14645 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14646 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14647 }
14648 case Type::Enum:
14649 case Type::Record:
14650 case Type::InjectedClassName: {
14651 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14652 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14653 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14654 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14655 /*OwnedTag=*/false);
14656 }
14657 case Type::TemplateSpecialization: {
14658 const auto *TX = cast<TemplateSpecializationType>(X),
14660 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14661 TY->template_arguments());
14663 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14664 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14665 TY->getTemplateName(),
14666 /*IgnoreDeduced=*/true),
14667 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14668 }
14669 case Type::Decltype: {
14670 const auto *DX = cast<DecltypeType>(X);
14671 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14672 assert(DX->isDependentType());
14673 assert(DY->isDependentType());
14674 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14675 // As Decltype is not uniqued, building a common type would be wasteful.
14676 return QualType(DX, 0);
14677 }
14678 case Type::PackIndexing: {
14679 const auto *DX = cast<PackIndexingType>(X);
14680 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14681 assert(DX->isDependentType());
14682 assert(DY->isDependentType());
14683 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14684 return QualType(DX, 0);
14685 }
14686 case Type::DependentName: {
14687 const auto *NX = cast<DependentNameType>(X),
14688 *NY = cast<DependentNameType>(Y);
14689 assert(NX->getIdentifier() == NY->getIdentifier());
14690 return Ctx.getDependentNameType(
14691 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14692 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14693 }
14694 case Type::OverflowBehavior: {
14695 const auto *NX = cast<OverflowBehaviorType>(X),
14697 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14698 return Ctx.getOverflowBehaviorType(
14699 NX->getBehaviorKind(),
14700 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14701 NY->getUnderlyingType(), QX, QY));
14702 }
14703 case Type::UnaryTransform: {
14704 const auto *TX = cast<UnaryTransformType>(X),
14705 *TY = cast<UnaryTransformType>(Y);
14706 assert(TX->getUTTKind() == TY->getUTTKind());
14707 return Ctx.getUnaryTransformType(
14708 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14709 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14710 TY->getUnderlyingType()),
14711 TX->getUTTKind());
14712 }
14713 case Type::PackExpansion: {
14714 const auto *PX = cast<PackExpansionType>(X),
14715 *PY = cast<PackExpansionType>(Y);
14716 assert(PX->getNumExpansions() == PY->getNumExpansions());
14717 return Ctx.getPackExpansionType(
14718 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14719 PX->getNumExpansions(), false);
14720 }
14721 case Type::Pipe: {
14722 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14723 assert(PX->isReadOnly() == PY->isReadOnly());
14724 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14726 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14727 }
14728 case Type::TemplateTypeParm: {
14729 const auto *TX = cast<TemplateTypeParmType>(X),
14731 assert(TX->getDepth() == TY->getDepth());
14732 assert(TX->getIndex() == TY->getIndex());
14733 assert(TX->isParameterPack() == TY->isParameterPack());
14734 return Ctx.getTemplateTypeParmType(
14735 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14736 getCommonDecl(TX->getDecl(), TY->getDecl()));
14737 }
14738 }
14739 llvm_unreachable("Unknown Type Class");
14740}
14741
14743 const Type *Y,
14744 SplitQualType Underlying) {
14745 Type::TypeClass TC = X->getTypeClass();
14746 if (TC != Y->getTypeClass())
14747 return QualType();
14748 switch (TC) {
14749#define UNEXPECTED_TYPE(Class, Kind) \
14750 case Type::Class: \
14751 llvm_unreachable("Unexpected " Kind ": " #Class);
14752#define TYPE(Class, Base)
14753#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14754#include "clang/AST/TypeNodes.inc"
14755
14756#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14759 CANONICAL_TYPE(BlockPointer)
14762 CANONICAL_TYPE(ConstantArray)
14763 CANONICAL_TYPE(ArrayParameter)
14764 CANONICAL_TYPE(ConstantMatrix)
14766 CANONICAL_TYPE(ExtVector)
14767 CANONICAL_TYPE(FunctionNoProto)
14768 CANONICAL_TYPE(FunctionProto)
14769 CANONICAL_TYPE(IncompleteArray)
14770 CANONICAL_TYPE(HLSLAttributedResource)
14771 CANONICAL_TYPE(HLSLInlineSpirv)
14772 CANONICAL_TYPE(LValueReference)
14773 CANONICAL_TYPE(ObjCInterface)
14774 CANONICAL_TYPE(ObjCObject)
14775 CANONICAL_TYPE(ObjCObjectPointer)
14776 CANONICAL_TYPE(OverflowBehavior)
14780 CANONICAL_TYPE(RValueReference)
14781 CANONICAL_TYPE(VariableArray)
14783#undef CANONICAL_TYPE
14784
14785#undef UNEXPECTED_TYPE
14786
14787 case Type::Adjusted: {
14788 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14789 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14790 if (!Ctx.hasSameType(OX, OY))
14791 return QualType();
14792 // FIXME: It's inefficient to have to unify the original types.
14793 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14794 Ctx.getQualifiedType(Underlying));
14795 }
14796 case Type::Decayed: {
14797 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14798 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14799 if (!Ctx.hasSameType(OX, OY))
14800 return QualType();
14801 // FIXME: It's inefficient to have to unify the original types.
14802 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14803 Ctx.getQualifiedType(Underlying));
14804 }
14805 case Type::Attributed: {
14806 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14807 AttributedType::Kind Kind = AX->getAttrKind();
14808 if (Kind != AY->getAttrKind())
14809 return QualType();
14810 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14811 if (!Ctx.hasSameType(MX, MY))
14812 return QualType();
14813 // FIXME: It's inefficient to have to unify the modified types.
14814 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14815 Ctx.getQualifiedType(Underlying),
14816 AX->getAttr());
14817 }
14818 case Type::BTFTagAttributed: {
14819 const auto *BX = cast<BTFTagAttributedType>(X);
14820 const BTFTypeTagAttr *AX = BX->getAttr();
14821 // The attribute is not uniqued, so just compare the tag.
14822 if (AX->getBTFTypeTag() !=
14823 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14824 return QualType();
14825 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14826 }
14827 case Type::Auto: {
14828 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14829 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14830 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14831
14832 AutoTypeKeyword KW = AX->getKeyword();
14833 if (KW != AY->getKeyword())
14834 return QualType();
14835
14836 TemplateDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
14837 AY->getTypeConstraintConcept());
14839 if (CD &&
14840 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14841 AY->getTypeConstraintArguments())) {
14842 CD = nullptr; // The arguments differ, so make it unconstrained.
14843 As.clear();
14844 }
14845
14846 // Both auto types can't be dependent, otherwise they wouldn't have been
14847 // sugar. This implies they can't contain unexpanded packs either.
14849 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14850 CD, As);
14851 }
14852 case Type::PackIndexing:
14853 case Type::Decltype:
14854 return QualType();
14855 case Type::DeducedTemplateSpecialization:
14856 // FIXME: Try to merge these.
14857 return QualType();
14858 case Type::MacroQualified: {
14859 const auto *MX = cast<MacroQualifiedType>(X),
14860 *MY = cast<MacroQualifiedType>(Y);
14861 const IdentifierInfo *IX = MX->getMacroIdentifier();
14862 if (IX != MY->getMacroIdentifier())
14863 return QualType();
14864 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14865 }
14866 case Type::SubstTemplateTypeParm: {
14867 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14869 Decl *CD =
14870 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14871 if (!CD)
14872 return QualType();
14873 unsigned Index = SX->getIndex();
14874 if (Index != SY->getIndex())
14875 return QualType();
14876 auto PackIndex = SX->getPackIndex();
14877 if (PackIndex != SY->getPackIndex())
14878 return QualType();
14879 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14880 CD, Index, PackIndex,
14881 SX->getFinal() && SY->getFinal());
14882 }
14883 case Type::ObjCTypeParam:
14884 // FIXME: Try to merge these.
14885 return QualType();
14886 case Type::Paren:
14887 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14888
14889 case Type::TemplateSpecialization: {
14890 const auto *TX = cast<TemplateSpecializationType>(X),
14892 TemplateName CTN =
14893 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14894 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14895 if (!CTN.getAsVoidPointer())
14896 return QualType();
14898 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14899 TY->template_arguments()))
14900 return QualType();
14902 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14903 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14904 }
14905 case Type::Typedef: {
14906 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14907 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14908 if (!CD)
14909 return QualType();
14910 return Ctx.getTypedefType(
14911 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14912 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14913 Ctx.getQualifiedType(Underlying));
14914 }
14915 case Type::TypeOf: {
14916 // The common sugar between two typeof expressions, where one is
14917 // potentially a typeof_unqual and the other is not, we unify to the
14918 // qualified type as that retains the most information along with the type.
14919 // We only return a typeof_unqual type when both types are unqual types.
14924 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
14925 }
14926 case Type::TypeOfExpr:
14927 return QualType();
14928
14929 case Type::UnaryTransform: {
14930 const auto *UX = cast<UnaryTransformType>(X),
14931 *UY = cast<UnaryTransformType>(Y);
14932 UnaryTransformType::UTTKind KX = UX->getUTTKind();
14933 if (KX != UY->getUTTKind())
14934 return QualType();
14935 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
14936 if (!Ctx.hasSameType(BX, BY))
14937 return QualType();
14938 // FIXME: It's inefficient to have to unify the base types.
14939 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
14940 Ctx.getQualifiedType(Underlying), KX);
14941 }
14942 case Type::Using: {
14943 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
14944 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
14945 if (!CD)
14946 return QualType();
14947 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
14948 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
14949 CD, Ctx.getQualifiedType(Underlying));
14950 }
14951 case Type::MemberPointer: {
14952 const auto *PX = cast<MemberPointerType>(X),
14953 *PY = cast<MemberPointerType>(Y);
14954 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
14955 assert(Cls == PY->getMostRecentCXXRecordDecl());
14956 return Ctx.getMemberPointerType(
14957 ::getCommonPointeeType(Ctx, PX, PY),
14958 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
14959 }
14960 case Type::CountAttributed: {
14961 const auto *DX = cast<CountAttributedType>(X),
14963 if (DX->isCountInBytes() != DY->isCountInBytes())
14964 return QualType();
14965 if (DX->isOrNull() != DY->isOrNull())
14966 return QualType();
14967 Expr *CEX = DX->getCountExpr();
14968 Expr *CEY = DY->getCountExpr();
14969 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
14970 if (Ctx.hasSameExpr(CEX, CEY))
14971 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14972 DX->isCountInBytes(), DX->isOrNull(),
14973 CDX);
14974 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
14975 return QualType();
14976 // Two declarations with the same integer constant may still differ in their
14977 // expression pointers, so we need to evaluate them.
14978 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
14979 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
14980 if (VX != VY)
14981 return QualType();
14982 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
14983 DX->isCountInBytes(), DX->isOrNull(),
14984 CDX);
14985 }
14986
14987 case Type::LateParsedAttr:
14988 return QualType();
14989
14990 case Type::PredefinedSugar:
14991 assert(cast<PredefinedSugarType>(X)->getKind() !=
14993 return QualType();
14994 }
14995 llvm_unreachable("Unhandled Type Class");
14996}
14997
14998static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15000 while (true) {
15001 QTotal.addConsistentQualifiers(T.Quals);
15002 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15003 if (NT == QualType(T.Ty, 0))
15004 break;
15005 R.push_back(T);
15006 T = NT.split();
15007 }
15008 return R;
15009}
15010
15012 bool Unqualified) const {
15013 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15014 if (X == Y)
15015 return X;
15016 if (!Unqualified) {
15017 if (X.isCanonical())
15018 return X;
15019 if (Y.isCanonical())
15020 return Y;
15021 }
15022
15023 SplitQualType SX = X.split(), SY = Y.split();
15024 Qualifiers QX, QY;
15025 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15026 // until we reach their underlying "canonical nodes". Note these are not
15027 // necessarily canonical types, as they may still have sugared properties.
15028 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15029 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15030
15031 // If this is an ArrayType, the element qualifiers are interchangeable with
15032 // the top level qualifiers.
15033 // * In case the canonical nodes are the same, the elements types are already
15034 // the same.
15035 // * Otherwise, the element types will be made the same, and any different
15036 // element qualifiers will be moved up to the top level qualifiers, per
15037 // 'getCommonArrayElementType'.
15038 // In both cases, this means there may be top level qualifiers which differ
15039 // between X and Y. If so, these differing qualifiers are redundant with the
15040 // element qualifiers, and can be removed without changing the canonical type.
15041 // The desired behaviour is the same as for the 'Unqualified' case here:
15042 // treat the redundant qualifiers as sugar, remove the ones which are not
15043 // common to both sides.
15044 bool KeepCommonQualifiers =
15046
15047 if (SX.Ty != SY.Ty) {
15048 // The canonical nodes differ. Build a common canonical node out of the two,
15049 // unifying their sugar. This may recurse back here.
15050 SX.Ty =
15051 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15052 } else {
15053 // The canonical nodes were identical: We may have desugared too much.
15054 // Add any common sugar back in.
15055 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15056 QX -= SX.Quals;
15057 QY -= SY.Quals;
15058 SX = Xs.pop_back_val();
15059 SY = Ys.pop_back_val();
15060 }
15061 }
15062 if (KeepCommonQualifiers)
15064 else
15065 assert(QX == QY);
15066
15067 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15068 // related. Walk up these nodes, unifying them and adding the result.
15069 while (!Xs.empty() && !Ys.empty()) {
15070 auto Underlying = SplitQualType(
15071 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15072 SX = Xs.pop_back_val();
15073 SY = Ys.pop_back_val();
15074 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15076 // Stop at the first pair which is unrelated.
15077 if (!SX.Ty) {
15078 SX.Ty = Underlying.Ty;
15079 break;
15080 }
15081 QX -= Underlying.Quals;
15082 };
15083
15084 // Add back the missing accumulated qualifiers, which were stripped off
15085 // with the sugar nodes we could not unify.
15086 QualType R = getQualifiedType(SX.Ty, QX);
15087 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15088 return R;
15089}
15090
15092 assert(Ty->isFixedPointType());
15093
15095 return Ty;
15096
15097 switch (Ty->castAs<BuiltinType>()->getKind()) {
15098 default:
15099 llvm_unreachable("Not a saturated fixed point type!");
15100 case BuiltinType::SatShortAccum:
15101 return ShortAccumTy;
15102 case BuiltinType::SatAccum:
15103 return AccumTy;
15104 case BuiltinType::SatLongAccum:
15105 return LongAccumTy;
15106 case BuiltinType::SatUShortAccum:
15107 return UnsignedShortAccumTy;
15108 case BuiltinType::SatUAccum:
15109 return UnsignedAccumTy;
15110 case BuiltinType::SatULongAccum:
15111 return UnsignedLongAccumTy;
15112 case BuiltinType::SatShortFract:
15113 return ShortFractTy;
15114 case BuiltinType::SatFract:
15115 return FractTy;
15116 case BuiltinType::SatLongFract:
15117 return LongFractTy;
15118 case BuiltinType::SatUShortFract:
15119 return UnsignedShortFractTy;
15120 case BuiltinType::SatUFract:
15121 return UnsignedFractTy;
15122 case BuiltinType::SatULongFract:
15123 return UnsignedLongFractTy;
15124 }
15125}
15126
15128 assert(Ty->isFixedPointType());
15129
15130 if (Ty->isSaturatedFixedPointType()) return Ty;
15131
15132 switch (Ty->castAs<BuiltinType>()->getKind()) {
15133 default:
15134 llvm_unreachable("Not a fixed point type!");
15135 case BuiltinType::ShortAccum:
15136 return SatShortAccumTy;
15137 case BuiltinType::Accum:
15138 return SatAccumTy;
15139 case BuiltinType::LongAccum:
15140 return SatLongAccumTy;
15141 case BuiltinType::UShortAccum:
15143 case BuiltinType::UAccum:
15144 return SatUnsignedAccumTy;
15145 case BuiltinType::ULongAccum:
15147 case BuiltinType::ShortFract:
15148 return SatShortFractTy;
15149 case BuiltinType::Fract:
15150 return SatFractTy;
15151 case BuiltinType::LongFract:
15152 return SatLongFractTy;
15153 case BuiltinType::UShortFract:
15155 case BuiltinType::UFract:
15156 return SatUnsignedFractTy;
15157 case BuiltinType::ULongFract:
15159 }
15160}
15161
15163 if (LangOpts.OpenCL)
15165
15166 if (LangOpts.CUDA)
15168
15169 return getLangASFromTargetAS(AS);
15170}
15171
15172// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
15173// doesn't include ASTContext.h
15174template
15176 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
15178 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
15179 const clang::ASTContext &Ctx, Decl *Value);
15180
15182 assert(Ty->isFixedPointType());
15183
15184 const TargetInfo &Target = getTargetInfo();
15185 switch (Ty->castAs<BuiltinType>()->getKind()) {
15186 default:
15187 llvm_unreachable("Not a fixed point type!");
15188 case BuiltinType::ShortAccum:
15189 case BuiltinType::SatShortAccum:
15190 return Target.getShortAccumScale();
15191 case BuiltinType::Accum:
15192 case BuiltinType::SatAccum:
15193 return Target.getAccumScale();
15194 case BuiltinType::LongAccum:
15195 case BuiltinType::SatLongAccum:
15196 return Target.getLongAccumScale();
15197 case BuiltinType::UShortAccum:
15198 case BuiltinType::SatUShortAccum:
15199 return Target.getUnsignedShortAccumScale();
15200 case BuiltinType::UAccum:
15201 case BuiltinType::SatUAccum:
15202 return Target.getUnsignedAccumScale();
15203 case BuiltinType::ULongAccum:
15204 case BuiltinType::SatULongAccum:
15205 return Target.getUnsignedLongAccumScale();
15206 case BuiltinType::ShortFract:
15207 case BuiltinType::SatShortFract:
15208 return Target.getShortFractScale();
15209 case BuiltinType::Fract:
15210 case BuiltinType::SatFract:
15211 return Target.getFractScale();
15212 case BuiltinType::LongFract:
15213 case BuiltinType::SatLongFract:
15214 return Target.getLongFractScale();
15215 case BuiltinType::UShortFract:
15216 case BuiltinType::SatUShortFract:
15217 return Target.getUnsignedShortFractScale();
15218 case BuiltinType::UFract:
15219 case BuiltinType::SatUFract:
15220 return Target.getUnsignedFractScale();
15221 case BuiltinType::ULongFract:
15222 case BuiltinType::SatULongFract:
15223 return Target.getUnsignedLongFractScale();
15224 }
15225}
15226
15228 assert(Ty->isFixedPointType());
15229
15230 const TargetInfo &Target = getTargetInfo();
15231 switch (Ty->castAs<BuiltinType>()->getKind()) {
15232 default:
15233 llvm_unreachable("Not a fixed point type!");
15234 case BuiltinType::ShortAccum:
15235 case BuiltinType::SatShortAccum:
15236 return Target.getShortAccumIBits();
15237 case BuiltinType::Accum:
15238 case BuiltinType::SatAccum:
15239 return Target.getAccumIBits();
15240 case BuiltinType::LongAccum:
15241 case BuiltinType::SatLongAccum:
15242 return Target.getLongAccumIBits();
15243 case BuiltinType::UShortAccum:
15244 case BuiltinType::SatUShortAccum:
15245 return Target.getUnsignedShortAccumIBits();
15246 case BuiltinType::UAccum:
15247 case BuiltinType::SatUAccum:
15248 return Target.getUnsignedAccumIBits();
15249 case BuiltinType::ULongAccum:
15250 case BuiltinType::SatULongAccum:
15251 return Target.getUnsignedLongAccumIBits();
15252 case BuiltinType::ShortFract:
15253 case BuiltinType::SatShortFract:
15254 case BuiltinType::Fract:
15255 case BuiltinType::SatFract:
15256 case BuiltinType::LongFract:
15257 case BuiltinType::SatLongFract:
15258 case BuiltinType::UShortFract:
15259 case BuiltinType::SatUShortFract:
15260 case BuiltinType::UFract:
15261 case BuiltinType::SatUFract:
15262 case BuiltinType::ULongFract:
15263 case BuiltinType::SatULongFract:
15264 return 0;
15265 }
15266}
15267
15268llvm::FixedPointSemantics
15270 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15271 "Can only get the fixed point semantics for a "
15272 "fixed point or integer type.");
15273 if (Ty->isIntegerType())
15274 return llvm::FixedPointSemantics::GetIntegerSemantics(
15275 getIntWidth(Ty), Ty->isSignedIntegerType());
15276
15277 bool isSigned = Ty->isSignedFixedPointType();
15278 return llvm::FixedPointSemantics(
15279 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15281 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15282}
15283
15284llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15285 assert(Ty->isFixedPointType());
15286 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15287}
15288
15289llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15290 assert(Ty->isFixedPointType());
15291 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15292}
15293
15295 assert(Ty->isUnsignedFixedPointType() &&
15296 "Expected unsigned fixed point type");
15297
15298 switch (Ty->castAs<BuiltinType>()->getKind()) {
15299 case BuiltinType::UShortAccum:
15300 return ShortAccumTy;
15301 case BuiltinType::UAccum:
15302 return AccumTy;
15303 case BuiltinType::ULongAccum:
15304 return LongAccumTy;
15305 case BuiltinType::SatUShortAccum:
15306 return SatShortAccumTy;
15307 case BuiltinType::SatUAccum:
15308 return SatAccumTy;
15309 case BuiltinType::SatULongAccum:
15310 return SatLongAccumTy;
15311 case BuiltinType::UShortFract:
15312 return ShortFractTy;
15313 case BuiltinType::UFract:
15314 return FractTy;
15315 case BuiltinType::ULongFract:
15316 return LongFractTy;
15317 case BuiltinType::SatUShortFract:
15318 return SatShortFractTy;
15319 case BuiltinType::SatUFract:
15320 return SatFractTy;
15321 case BuiltinType::SatULongFract:
15322 return SatLongFractTy;
15323 default:
15324 llvm_unreachable("Unexpected unsigned fixed point type");
15325 }
15326}
15327
15328// Given a list of FMV features, return a concatenated list of the
15329// corresponding backend features (which may contain duplicates).
15330static std::vector<std::string> getFMVBackendFeaturesFor(
15331 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15332 std::vector<std::string> BackendFeats;
15333 llvm::AArch64::ExtensionSet FeatureBits;
15334 for (StringRef F : FMVFeatStrings)
15335 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15336 if (FMVExt->ID)
15337 FeatureBits.enable(*FMVExt->ID);
15338 FeatureBits.toLLVMFeatureList(BackendFeats);
15339 return BackendFeats;
15340}
15341
15342ParsedTargetAttr
15343ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15344 assert(TD != nullptr);
15345 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15346
15347 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15348 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15349 });
15350 return ParsedAttr;
15351}
15352
15353void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15354 const FunctionDecl *FD) const {
15355 if (FD)
15356 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15357 else
15358 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15359 Target->getTargetOpts().CPU,
15360 Target->getTargetOpts().Features);
15361}
15362
15363// Fills in the supplied string map with the set of target features for the
15364// passed in function.
15365void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15366 GlobalDecl GD) const {
15367 StringRef TargetCPU = Target->getTargetOpts().CPU;
15368 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15369 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15371
15372 // Make a copy of the features as passed on the command line into the
15373 // beginning of the additional features from the function to override.
15374 // AArch64 handles command line option features in parseTargetAttr().
15375 if (!Target->getTriple().isAArch64())
15376 ParsedAttr.Features.insert(
15377 ParsedAttr.Features.begin(),
15378 Target->getTargetOpts().FeaturesAsWritten.begin(),
15379 Target->getTargetOpts().FeaturesAsWritten.end());
15380
15381 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15382 TargetCPU = ParsedAttr.CPU;
15383
15384 // Now populate the feature map, first with the TargetCPU which is either
15385 // the default or a new one from the target attribute string. Then we'll use
15386 // the passed in features (FeaturesAsWritten) along with the new ones from
15387 // the attribute.
15388 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15389 ParsedAttr.Features);
15390 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15392 Target->getCPUSpecificCPUDispatchFeatures(
15393 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15394 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15395 Features.insert(Features.begin(),
15396 Target->getTargetOpts().FeaturesAsWritten.begin(),
15397 Target->getTargetOpts().FeaturesAsWritten.end());
15398 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15399 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15400 if (Target->getTriple().isAArch64()) {
15402 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15403 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15404 Features.insert(Features.begin(),
15405 Target->getTargetOpts().FeaturesAsWritten.begin(),
15406 Target->getTargetOpts().FeaturesAsWritten.end());
15407 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15408 } else if (Target->getTriple().isRISCV()) {
15409 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15410 std::vector<std::string> Features;
15411 if (VersionStr != "default") {
15412 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15413 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15414 ParsedAttr.Features.end());
15415 }
15416 Features.insert(Features.begin(),
15417 Target->getTargetOpts().FeaturesAsWritten.begin(),
15418 Target->getTargetOpts().FeaturesAsWritten.end());
15419 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15420 } else if (Target->getTriple().isOSAIX()) {
15421 std::vector<std::string> Features;
15422 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15423 if (VersionStr.starts_with("cpu="))
15424 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15425 else
15426 assert(VersionStr == "default");
15427 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15428 } else {
15429 std::vector<std::string> Features;
15430 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15431 if (VersionStr.starts_with("arch="))
15432 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15433 else if (VersionStr != "default")
15434 Features.push_back((StringRef{"+"} + VersionStr).str());
15435 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15436 }
15437 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15438 std::vector<std::string> Features;
15439 if (Target->getTriple().isRISCV()) {
15440 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15441 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15442 ParsedAttr.Features.end());
15443 } else {
15444 assert(Target->getTriple().isAArch64());
15446 TV->getFeatures(Feats);
15447 Features = getFMVBackendFeaturesFor(Feats);
15448 }
15449 Features.insert(Features.begin(),
15450 Target->getTargetOpts().FeaturesAsWritten.begin(),
15451 Target->getTargetOpts().FeaturesAsWritten.end());
15452 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15453 } else {
15454 FeatureMap = Target->getTargetOpts().FeatureMap;
15455 }
15456}
15457
15459 CanQualType KernelNameType,
15460 const FunctionDecl *FD) {
15461 // Host and device compilation may use different ABIs and different ABIs
15462 // may allocate name mangling discriminators differently. A discriminator
15463 // override is used to ensure consistent discriminator allocation across
15464 // host and device compilation.
15465 auto DeviceDiscriminatorOverrider =
15466 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15467 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15468 if (RD->isLambda())
15469 return RD->getDeviceLambdaManglingNumber();
15470 return std::nullopt;
15471 };
15472 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15473 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15474
15475 // Construct a mangled name for the SYCL kernel caller offload entry point.
15476 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15477 // name the SYCL kernel caller offload entry point function. This mangling
15478 // does not suffice to clearly identify symbols that correspond to SYCL
15479 // kernel caller functions, nor is this mangling natural for targets that
15480 // use a non-Itanium ABI.
15481 std::string Buffer;
15482 Buffer.reserve(128);
15483 llvm::raw_string_ostream Out(Buffer);
15484 MC->mangleCanonicalTypeName(KernelNameType, Out);
15485 std::string KernelName = Out.str();
15486
15487 return {KernelNameType, FD, KernelName};
15488}
15489
15491 // If the function declaration to register is invalid or dependent, the
15492 // registration attempt is ignored.
15493 if (FD->isInvalidDecl() || FD->isTemplated())
15494 return;
15495
15496 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15497 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15498
15499 // Be tolerant of multiple registration attempts so long as each attempt
15500 // is for the same entity. Callers are obligated to detect and diagnose
15501 // conflicting kernel names prior to calling this function.
15502 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15503 auto IT = SYCLKernels.find(KernelNameType);
15504 assert((IT == SYCLKernels.end() ||
15505 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15506 "SYCL kernel name conflict");
15507 (void)IT;
15508 SYCLKernels.insert(std::make_pair(
15509 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15510}
15511
15513 CanQualType KernelNameType = getCanonicalType(T);
15514 return SYCLKernels.at(KernelNameType);
15515}
15516
15518 CanQualType KernelNameType = getCanonicalType(T);
15519 auto IT = SYCLKernels.find(KernelNameType);
15520 if (IT != SYCLKernels.end())
15521 return &IT->second;
15522 return nullptr;
15523}
15524
15526 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15527 return *OMPTraitInfoVector.back();
15528}
15529
15532 const ASTContext::SectionInfo &Section) {
15533 if (Section.Decl)
15534 return DB << Section.Decl;
15535 return DB << "a prior #pragma section";
15536}
15537
15538bool ASTContext::mayExternalize(const Decl *D) const {
15539 bool IsInternalVar =
15540 isa<VarDecl>(D) &&
15542 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15543 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15544 (D->hasAttr<CUDAConstantAttr>() &&
15545 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15546 // CUDA/HIP: managed variables need to be externalized since it is
15547 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15548 // anonymous name space needs to be externalized to avoid duplicate symbols.
15549 return (IsInternalVar &&
15550 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15551 (D->hasAttr<CUDAGlobalAttr>() &&
15553 GVA_Internal);
15554}
15555
15557 return mayExternalize(D) &&
15558 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15560}
15561
15562StringRef ASTContext::getCUIDHash() const {
15563 if (!CUIDHash.empty())
15564 return CUIDHash;
15565 if (LangOpts.CUID.empty())
15566 return StringRef();
15567 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15568 return CUIDHash;
15569}
15570
15571const CXXRecordDecl *
15573 assert(ThisClass);
15574 assert(ThisClass->isPolymorphic());
15575 const CXXRecordDecl *PrimaryBase = ThisClass;
15576 while (1) {
15577 assert(PrimaryBase);
15578 assert(PrimaryBase->isPolymorphic());
15579 auto &Layout = getASTRecordLayout(PrimaryBase);
15580 auto Base = Layout.getPrimaryBase();
15581 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15582 break;
15583 PrimaryBase = Base;
15584 }
15585 return PrimaryBase;
15586}
15587
15589 StringRef MangledName) {
15590 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15591 assert(Method->isVirtual());
15592 bool DefaultIncludesPointerAuth =
15593 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15594
15595 if (!DefaultIncludesPointerAuth)
15596 return true;
15597
15598 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15599 if (Existing != ThunksToBeAbbreviated.end())
15600 return Existing->second.contains(MangledName.str());
15601
15602 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15603 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15604 auto VtableContext = getVTableContext();
15605 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15606 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15607 for (const auto &Thunk : *ThunkInfos) {
15608 SmallString<256> ElidedName;
15609 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15610 if (Destructor)
15611 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15612 Thunk, /* elideOverrideInfo */ true,
15613 ElidedNameStream);
15614 else
15615 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15616 ElidedNameStream);
15617 SmallString<256> MangledName;
15618 llvm::raw_svector_ostream mangledNameStream(MangledName);
15619 if (Destructor)
15620 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15621 Thunk, /* elideOverrideInfo */ false,
15622 mangledNameStream);
15623 else
15624 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15625 mangledNameStream);
15626
15627 Thunks[ElidedName].push_back(std::string(MangledName));
15628 }
15629 }
15630 llvm::StringSet<> SimplifiedThunkNames;
15631 for (auto &ThunkList : Thunks) {
15632 llvm::sort(ThunkList.second);
15633 SimplifiedThunkNames.insert(ThunkList.second[0]);
15634 }
15635 bool Result = SimplifiedThunkNames.contains(MangledName);
15636 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15637 return Result;
15638}
15639
15641 // Check for trivially-destructible here because non-trivially-destructible
15642 // types will always cause the type and any types derived from it to be
15643 // considered non-trivially-copyable. The same cannot be said for
15644 // trivially-copyable because deleting special members of a type derived from
15645 // a non-trivially-copyable type can cause the derived type to be considered
15646 // trivially copyable.
15647 if (getLangOpts().PointerFieldProtectionTagged)
15648 return !isa<CXXRecordDecl>(RD) ||
15649 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15650 return true;
15651}
15652
15653static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15654 std::vector<PFPField> &Fields, bool IncludeVBases) {
15655 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15656 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15657 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15658 for (unsigned i = 0; i != AT->getSize(); ++i)
15659 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15660 Fields, true);
15661 }
15662 }
15663 auto *Decl = Ty->getAsCXXRecordDecl();
15664 // isPFPType() is inherited from bases and members (including via arrays), so
15665 // we can early exit if it is false. Unions are excluded per the API
15666 // documentation.
15667 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15668 return;
15669 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15670 for (FieldDecl *Field : Decl->fields()) {
15671 CharUnits FieldOffset =
15672 Offset +
15673 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15674 if (Ctx.isPFPField(Field))
15675 Fields.push_back({FieldOffset, Field});
15676 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15677 /*IncludeVBases=*/true);
15678 }
15679 // Pass false for IncludeVBases below because vbases are only included in
15680 // layout for top-level types, i.e. not bases or vbases.
15681 for (CXXBaseSpecifier &Base : Decl->bases()) {
15682 if (Base.isVirtual())
15683 continue;
15684 CharUnits BaseOffset =
15685 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15686 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15687 /*IncludeVBases=*/false);
15688 }
15689 if (IncludeVBases) {
15690 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15691 CharUnits BaseOffset =
15692 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15693 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15694 /*IncludeVBases=*/false);
15695 }
15696 }
15697}
15698
15699std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15700 std::vector<PFPField> PFPFields;
15701 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15702 return PFPFields;
15703}
15704
15706 return !findPFPFields(Ty).empty();
15707}
15708
15709bool ASTContext::isPFPField(const FieldDecl *FD) const {
15710 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15711 return RD->isPFPType() && FD->getType()->isPointerType() &&
15712 !FD->hasAttr<NoFieldProtectionAttr>();
15713 return false;
15714}
15715
15717 auto *FD = dyn_cast<FieldDecl>(VD);
15718 if (!FD)
15719 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15720 if (isPFPField(FD))
15722}
15723
15725 if (E->getNumComponents() == 0)
15726 return;
15727 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15728 if (Comp.getKind() != OffsetOfNode::Field)
15729 return;
15730 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15732}
15733
15734namespace {
15735// PaddingCalculator is a utility class that calculates the padding bits in a
15736// c/c++ type. It traverses the type recursively, collecting occupied
15737// bit intervals, and then computes the padding intervals.
15738// If a byte only contains some padding bits, it gets intervals for only those
15739// bits. This is the case for bit-fields.
15740struct PaddingCalculator {
15741 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15742
15743 void run(QualType Ty) {
15744 OccuppiedIntervals.clear();
15745 Stack.clear();
15746
15747 TySizeInBits = Ctx.getTypeSize(Ty);
15748
15749 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15750 while (!Stack.empty()) {
15751 Data Current = Stack.back();
15752 Stack.pop_back();
15753 Visit(Current);
15754 }
15755 MergeOccuppiedIntervals();
15756 }
15757
15758 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15759 llvm::SmallVector<ASTContext::BitInterval> Results;
15760 if (OccuppiedIntervals.size() == 1 &&
15761 OccuppiedIntervals.front().First == 0 &&
15762 OccuppiedIntervals.front().Last == TySizeInBits) {
15763 return Results;
15764 }
15765 Results.reserve(OccuppiedIntervals.size() + 1);
15766 uint64_t CurrentPos = 0;
15767 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15768 if (OccupiedInterval.First > CurrentPos) {
15769 Results.push_back(
15770 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15771 }
15772 CurrentPos = OccupiedInterval.Last;
15773 }
15774 if (TySizeInBits > CurrentPos) {
15775 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15776 }
15777 return Results;
15778 }
15779
15780private:
15781 struct Data {
15782 uint64_t StartBitOffset;
15783 QualType Ty;
15784 bool VisitVirtualBase;
15785 };
15786
15787 // Return the number of non padding bits of a scalar type.
15788 //
15789 // The property that we specifically care about here is whether the scalar
15790 // type has padding bits, i.e. are there bits in the type which are not
15791 // specified by the ABI.
15792 //
15793 // We currently don't care about this anywhere else in clang: layout cares
15794 // about the ABI size, calling convention code cares about specific types,
15795 // but nothing cares about padding specifically. And it's not something we can
15796 // easily query from LLVM due to the type system mismatches.
15797 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15798 // DataLayout methods aren't really designed for this usage.
15799 //
15800 // Therefore, it is better to explicitly list all the scalar types
15801 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15802 // double.
15803 //
15804 // FIXME: There are likely other scalar types we need to think about here, as
15805 // brought up in review for #215823:
15806 // - bool
15807 // - enums(both with/without fixed underlying type)
15808 // - nullptr_t
15809 // - more?
15810 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15811 if (const auto *BIT = Ty->getAs<BitIntType>())
15812 return BIT->getNumBits();
15813
15814 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15815 if (BT->getKind() == BuiltinType::LongDouble &&
15817 &llvm::APFloat::x87DoubleExtended())
15818 return llvm::APFloat::getSizeInBits(
15820 }
15821
15822 return Ctx.getTypeSize(Ty);
15823 }
15824
15825 void Visit(const Data &D) {
15826 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15827 VisitArray(AT, D.StartBitOffset);
15828 return;
15829 }
15830
15831 if (auto *Record = D.Ty->getAsRecordDecl()) {
15832 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15833 return;
15834 }
15835
15836 if (D.Ty->isAtomicType()) {
15837 auto Unwrapped = D;
15838 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15839 Stack.push_back(Unwrapped);
15840 return;
15841 }
15842
15843 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15844 VisitComplex(Complex, D.StartBitOffset);
15845 return;
15846 }
15847
15848 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15849 VisitVector(VT, D.StartBitOffset);
15850 return;
15851 }
15852
15853 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15854 OccuppiedIntervals.push_back(
15855 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15856 }
15857
15858 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15859 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15860 ++ArrIndex) {
15861
15862 QualType ElementQualType = AT->getElementType();
15863 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15864 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15865 auto Offset = ElementSize.alignTo(ElementAlign);
15866
15867 Stack.push_back(Data{
15868 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15869 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15870 }
15871 }
15872
15873 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15874 bool VisitVirtualBase) {
15875 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15876 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15877
15878 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15879
15880 if (CXXRecord) {
15881 if (ASTLayout.hasOwnVFPtr()) {
15882 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15883 StartBitOffset, StartBitOffset + PointerSizeInBits});
15884 }
15885
15886 if (ASTLayout.hasOwnVBPtr()) {
15887 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15888 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15889 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15890 StartVBPtr, StartVBPtr + PointerSizeInBits});
15891 }
15892
15893 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15894 const CXXBaseSpecifier &Base, auto GetOffset) {
15895 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15896 if (!BaseRecord) {
15897 return;
15898 }
15899 auto BaseOffset =
15900 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15901
15902 Stack.push_back(
15903 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15904 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15905 false});
15906 };
15907
15908 for (auto Base : CXXRecord->bases()) {
15909 if (!Base.isVirtual()) {
15910 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15911 }
15912 }
15913
15914 if (VisitVirtualBase) {
15915 for (auto VBase : CXXRecord->vbases()) {
15916 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15917 }
15918 }
15919 }
15920
15921 for (auto *Field : R->fields()) {
15922 // Treat unnamed bitfields as padding.
15923 if (Field->isUnnamedBitField())
15924 continue;
15925
15926 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
15927 if (Field->isBitField()) {
15928 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15929 StartBitOffset + FieldOffset,
15930 StartBitOffset + FieldOffset + Field->getBitWidthValue()});
15931 } else {
15932 Stack.push_back(Data{StartBitOffset + FieldOffset,
15933 Field->getType().getCanonicalType(),
15934 /*VisitVirtualBase*/ true});
15935 }
15936 }
15937 }
15938
15939 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
15940 QualType ElementQualType = CT->getElementType().getCanonicalType();
15941 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15942 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15943 auto ImgOffset = ElementSize.alignTo(ElementAlign);
15944
15945 Stack.push_back(
15946 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
15947 Stack.push_back(
15948 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
15949 ElementQualType, /*VisitVirtualBase*/ true});
15950 }
15951
15952 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
15953 uint64_t SizeBit = [&]() -> uint64_t {
15954 if (VT->isPackedVectorBoolType(Ctx))
15955 return VT->getNumElements();
15956 return getScalarOccupiedSizeInBits(VT->getElementType()) *
15957 VT->getNumElements();
15958 }();
15959 OccuppiedIntervals.push_back(
15960 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
15961 }
15962
15963 void MergeOccuppiedIntervals() {
15964 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
15965 [](const ASTContext::BitInterval &lhs,
15966 const ASTContext::BitInterval &rhs) {
15967 return std::tie(lhs.First, lhs.Last) <
15968 std::tie(rhs.First, rhs.Last);
15969 });
15970
15971 llvm::SmallVector<ASTContext::BitInterval> Merged;
15972 Merged.reserve(OccuppiedIntervals.size());
15973
15974 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
15975 if (Merged.empty()) {
15976 Merged.push_back(NextInterval);
15977 continue;
15978 }
15979 auto &LastInterval = Merged.back();
15980
15981 if (NextInterval.First > LastInterval.Last) {
15982 Merged.push_back(NextInterval);
15983 } else {
15984 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
15985 }
15986 }
15987
15988 OccuppiedIntervals = Merged;
15989 }
15990
15991 const ASTContext &Ctx;
15992 // unsigned PointerSizeInBits;
15993 uint64_t TySizeInBits = 0;
15994 llvm::SmallVector<Data> Stack;
15995 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
15996};
15997} // namespace
15998
15999llvm::ArrayRef<ASTContext::BitInterval>
16001 Ty = Ty.getCanonicalType();
16002 auto cached = PaddingIntervalCache.find(Ty);
16003 if (cached != PaddingIntervalCache.end())
16004 return cached->second;
16005
16006 PaddingCalculator pc{*this};
16007 pc.run(Ty);
16008
16009 auto [itr, res] =
16010 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
16011 assert(res && "Failed to insert?");
16012
16013 return itr->second;
16014}
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:475
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:223
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 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:827
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.
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:828
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:823
Builtin::Context & BuiltinInfo
Definition ASTContext.h:825
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
Definition ASTContext.h:980
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:824
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 getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
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:943
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:586
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:826
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:224
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:829
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:876
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:578
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:897
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.
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:942
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.
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.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const
Return number of constant array elements.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const
Return number of elements initialized in an ArrayInitLoopExpr.
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:3603
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3624
Represents a loop initializing the elements of an array.
Definition Expr.h:5985
llvm::APInt getArraySize() const
Definition Expr.h:6007
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6005
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:4006
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3850
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3854
QualType getElementType() const
Definition TypeBase.h:3848
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3858
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:6945
Expr * getPtr() const
Definition Expr.h:6976
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8308
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8356
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:8373
unsigned getNumBits() const
Definition TypeBase.h:8368
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4806
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6689
Pointer to a block type.
Definition TypeBase.h:3656
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3673
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:2637
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2258
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:1219
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:1191
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
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3370
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:3874
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3970
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3989
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3950
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4520
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4566
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4517
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3516
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3552
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3639
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:1281
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:780
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
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:4175
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4197
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8401
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4125
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4154
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4215
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4240
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4587
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4607
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:6366
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6371
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4341
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4366
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:4145
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4363
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4377
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4261
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4318
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4243
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:842
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
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:3081
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:4082
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
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:4381
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:247
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5611
Abstract interface for external sources of AST nodes.
virtual void CompleteRedeclChain(const Decl *D)
Gives the external AST source an opportunity to complete the redeclaration chain for a declaration.
Represents a member of a struct/union/class.
Definition Decl.h:3294
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3397
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4815
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3379
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3530
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:4763
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:2058
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2819
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3805
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3051
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3934
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3790
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2395
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4460
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2536
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:4121
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5389
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:5913
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:5951
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5221
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5255
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4999
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5015
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5925
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5728
unsigned getNumParams() const
Definition TypeBase.h:5699
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4114
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5734
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5894
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5890
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4728
CallingConv getCC() const
Definition TypeBase.h:4787
unsigned getRegParm() const
Definition TypeBase.h:4780
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4776
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4799
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4643
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4683
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
ExtInfo getExtInfo() const
Definition TypeBase.h:4973
QualType getReturnType() const
Definition TypeBase.h:4957
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:125
CXXDtorType getDtorType() const
Definition GlobalDecl.h:113
const Decl * getDecl() const
Definition GlobalDecl.h:106
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5187
Represents a C array with an unspecified size.
Definition TypeBase.h:4023
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4040
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
@ 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:3575
A global _GUID constant.
Definition DeclCXX.h:4428
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4465
MSGuidDeclParts Parts
Definition DeclCXX.h:4430
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6300
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:4472
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4465
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3810
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:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:317
bool isExternallyVisible() const
Definition Decl.h:433
Represent a C++ namespace.
Definition Decl.h:592
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:8066
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:8122
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8203
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:8197
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8279
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8159
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8180
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8134
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8174
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:8241
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8186
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:2538
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2585
unsigned getNumComponents() const
Definition Expr.h:2593
Helper class for OffsetOfExpr.
Definition Expr.h:2432
@ Field
A field.
Definition Expr.h:2439
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:4403
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3382
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3396
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:1819
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1883
QualType getOriginalType() const
Definition Decl.cpp:2953
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:8339
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:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3423
PredefinedSugarKind Kind
Definition TypeBase.h:8415
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:8588
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2996
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8635
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
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:8504
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8630
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8525
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8577
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:8561
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8508
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:3139
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8536
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:8444
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8451
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
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:3749
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:4459
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5309
bool hasFlexibleArrayMember() const
Definition Decl.h:4492
field_range fields() const
Definition Decl.h:4662
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5295
RecordDecl * getMostRecentDecl()
Definition Decl.h:4485
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5354
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4643
bool field_empty() const
Definition Decl.h:4670
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:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3713
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:1810
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:3851
TagTypeKind TagKind
Definition Decl.h:3856
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4088
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4969
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4962
bool isUnion() const
Definition Decl.h:4062
TagKind getTagKind() const
Definition Decl.h:4051
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:227
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:865
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:758
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:340
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:349
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:354
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:363
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:342
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:345
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:358
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:512
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:414
IntType getSizeType() const
Definition TargetInfo.h:395
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:985
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:766
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:396
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:816
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.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
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)
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
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3647
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:6332
A container of type source information.
Definition TypeBase.h:8475
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:8761
bool isVoidType() const
Definition TypeBase.h:9113
bool isObjCBuiltinType() const
Definition TypeBase.h:8971
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:2801
bool isIncompleteArrayType() const
Definition TypeBase.h:8848
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:9122
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:8844
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:2547
bool isArrayType() const
Definition TypeBase.h:8840
bool isCharType() const
Definition Type.cpp:2223
bool isPointerType() const
Definition TypeBase.h:8741
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8856
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
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:9201
bool isEnumeralType() const
Definition TypeBase.h:8872
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8941
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:9235
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:9016
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8864
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:9173
bool isHalfType() const
Definition TypeBase.h:9117
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9189
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:8953
bool isOverflowBehaviorType() const
Definition TypeBase.h:8912
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9197
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9393
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:2557
bool isFunctionType() const
Definition TypeBase.h:8737
bool isObjCObjectPointerType() const
Definition TypeBase.h:8920
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:9215
bool isVectorType() const
Definition TypeBase.h:8880
bool isObjCClassType() const
Definition TypeBase.h:8959
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2783
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2718
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:2362
bool isAnyPointerType() const
Definition TypeBase.h:8749
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:9340
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:9150
bool isRecordType() const
Definition TypeBase.h:8868
bool isObjCRetainableType() const
Definition Type.cpp:5465
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5184
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3801
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5829
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
QualType getUnderlyingType() const
Definition Decl.h:3751
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6276
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2255
Opcode getOpcode() const
Definition Expr.h:2291
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4485
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4513
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6137
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6174
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4062
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4127
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3817
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3424
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3488
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:6214
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5644
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:932
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2781
bool hasInit() const
Definition Decl.cpp:2379
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:2442
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
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:1214
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1575
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1318
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2356
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:2750
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4080
Expr * getSizeExpr() const
Definition TypeBase.h:4094
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4313
VectorKind getVectorKind() const
Definition TypeBase.h:4309
QualType getElementType() const
Definition TypeBase.h:4303
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:213
@ OCLTK_ReserveID
Definition TargetInfo.h:220
@ OCLTK_Sampler
Definition TargetInfo.h:221
@ OCLTK_Pipe
Definition TargetInfo.h:218
@ OCLTK_ClkEvent
Definition TargetInfo.h:215
@ OCLTK_Event
Definition TargetInfo.h:216
@ OCLTK_Default
Definition TargetInfo.h:214
@ OCLTK_Queue
Definition TargetInfo.h:219
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8639
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:3833
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:6050
@ Struct
The "struct" keyword.
Definition TypeBase.h:6047
@ Class
The "class" keyword.
Definition TypeBase.h:6056
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:557
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:75
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:4259
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4268
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4256
@ Generic
not a target-specific vector type
Definition TypeBase.h:4250
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4274
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4277
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4271
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:846
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6020
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6041
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6022
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6031
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6034
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6038
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:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6735
Expr * getCopyExpr() const
Definition Expr.h:6742
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:5478
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5480
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5483
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5486
Extra information about a function prototype.
Definition TypeBase.h:5506
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5552
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5511
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5556
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5545
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:3415
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:233
A lazy value (of type T) that is within an AST node of type Owner, where the value might change in la...
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:60
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h: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:147
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