clang 24.0.0git
ASTContext.cpp
Go to the documentation of this file.
1//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the ASTContext interface.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ByteCode/Context.h"
15#include "CXXABI.h"
16#include "clang/AST/APValue.h"
18#include "clang/AST/ASTLambda.h"
22#include "clang/AST/Attr.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Comment.h"
26#include "clang/AST/Decl.h"
27#include "clang/AST/DeclBase.h"
28#include "clang/AST/DeclCXX.h"
30#include "clang/AST/DeclObjC.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
38#include "clang/AST/Mangle.h"
44#include "clang/AST/Stmt.h"
47#include "clang/AST/Type.h"
48#include "clang/AST/TypeLoc.h"
57#include "clang/Basic/LLVM.h"
59#include "clang/Basic/Linkage.h"
60#include "clang/Basic/Module.h"
70#include "clang/Lex/MacroInfo.h"
71#include "llvm/ADT/APFixedPoint.h"
72#include "llvm/ADT/APInt.h"
73#include "llvm/ADT/APSInt.h"
74#include "llvm/ADT/ArrayRef.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/DenseSet.h"
77#include "llvm/ADT/FoldingSet.h"
78#include "llvm/ADT/PointerUnion.h"
79#include "llvm/ADT/STLExtras.h"
80#include "llvm/ADT/SmallPtrSet.h"
81#include "llvm/ADT/SmallVector.h"
82#include "llvm/ADT/StringExtras.h"
83#include "llvm/ADT/StringRef.h"
84#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
85#include "llvm/Support/Capacity.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/MD5.h"
90#include "llvm/Support/MathExtras.h"
91#include "llvm/Support/SipHash.h"
92#include "llvm/Support/raw_ostream.h"
93#include "llvm/TargetParser/AArch64TargetParser.h"
94#include "llvm/TargetParser/Triple.h"
95#include <algorithm>
96#include <cassert>
97#include <cstddef>
98#include <cstdint>
99#include <cstdlib>
100#include <map>
101#include <memory>
102#include <optional>
103#include <string>
104#include <tuple>
105#include <utility>
106
107using namespace clang;
108
119
120/// \returns The locations that are relevant when searching for Doc comments
121/// related to \p Key.
124 SourceManager &SourceMgr) {
125 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
126 SourceLocation DefLoc = MI->getDefinitionLoc();
127 if (DefLoc.isInvalid() || !DefLoc.isFileID())
128 return {};
129
130 // The macro's definition location points at its name (e.g. FOO in
131 // `#define FOO 1`). The text between a preceding documentation comment
132 // and the name contains the `#define` directive itself, which would be
133 // rejected by the preprocessor-directive guard in
134 // getRawCommentNoCacheImpl. Walk back to the leading `#` so that
135 // the guard only fires when something *else* sits between the comment
136 // and our directive.
137 FileIDAndOffset Decomposed = SourceMgr.getDecomposedLoc(DefLoc);
138 bool Invalid = false;
139 StringRef Buffer = SourceMgr.getBufferData(Decomposed.first, &Invalid);
140 if (Invalid)
141 return {};
142 unsigned Offset = Decomposed.second;
143 if (size_t Found = Buffer.find_last_of("#\n", Offset);
144 Found != StringRef::npos)
145 Offset = Found;
146 return {SourceMgr.getLocForStartOfFile(Decomposed.first)
147 .getLocWithOffset(Offset)};
148 }
149
150 const auto *D = cast<const Decl *>(Key);
151 assert(D);
152
153 // User can not attach documentation to implicit declarations.
154 if (D->isImplicit())
155 return {};
156
157 // User can not attach documentation to implicit instantiations.
158 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
159 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
160 return {};
161 }
162
163 if (const auto *VD = dyn_cast<VarDecl>(D)) {
164 if (VD->isStaticDataMember() &&
165 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
166 return {};
167 }
168
169 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
170 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
171 return {};
172 }
173
174 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
175 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
176 if (TSK == TSK_ImplicitInstantiation ||
177 TSK == TSK_Undeclared)
178 return {};
179 }
180
181 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
182 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
183 return {};
184 }
185 if (const auto *TD = dyn_cast<TagDecl>(D)) {
186 // When tag declaration (but not definition!) is part of the
187 // decl-specifier-seq of some other declaration, it doesn't get comment
188 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
189 return {};
190 }
191 // TODO: handle comments for function parameters properly.
192 if (isa<ParmVarDecl>(D))
193 return {};
194
195 // TODO: we could look up template parameter documentation in the template
196 // documentation.
200 return {};
201
203 // Find declaration location.
204 // For Objective-C declarations we generally don't expect to have multiple
205 // declarators, thus use declaration starting location as the "declaration
206 // location".
207 // For all other declarations multiple declarators are used quite frequently,
208 // so we use the location of the identifier as the "declaration location".
209 SourceLocation BaseLocation;
213 // Allow association with Y across {} in `typedef struct X {} Y`.
215 BaseLocation = D->getBeginLoc();
216 else
217 BaseLocation = D->getLocation();
218
219 if (!D->getLocation().isMacroID()) {
220 Locations.emplace_back(BaseLocation);
221 } else {
222 const auto *DeclCtx = D->getDeclContext();
223
224 // When encountering definitions generated from a macro (that are not
225 // contained by another declaration in the macro) we need to try and find
226 // the comment at the location of the expansion but if there is no comment
227 // there we should retry to see if there is a comment inside the macro as
228 // well. To this end we return first BaseLocation to first look at the
229 // expansion site, the second value is the spelling location of the
230 // beginning of the declaration defined inside the macro.
231 if (!(DeclCtx &&
232 Decl::castFromDeclContext(DeclCtx)->getLocation().isMacroID())) {
233 Locations.emplace_back(SourceMgr.getExpansionLoc(BaseLocation));
234 }
235
236 // We use Decl::getBeginLoc() and not just BaseLocation here to ensure that
237 // we don't refer to the macro argument location at the expansion site (this
238 // can happen if the name's spelling is provided via macro argument), and
239 // always to the declaration itself.
240 Locations.emplace_back(SourceMgr.getSpellingLoc(D->getBeginLoc()));
241 }
242
243 return Locations;
244}
245
247 RawCommentLookupKey Key, const SourceLocation RepresentativeLoc,
248 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
249 // If the declaration doesn't map directly to a location in a file, we
250 // can't find the comment.
251 if (RepresentativeLoc.isInvalid() || !RepresentativeLoc.isFileID())
252 return nullptr;
253
254 // If there are no comments anywhere, we won't find anything.
255 if (CommentsInTheFile.empty())
256 return nullptr;
257
258 const auto *D = dyn_cast<const Decl *>(Key);
259 const bool IsMacro = isa<const MacroInfo *>(Key);
260
261 // Decompose the location for the declaration and find the beginning of the
262 // file buffer.
263 const FileIDAndOffset LocDecomp =
264 SourceMgr.getDecomposedLoc(RepresentativeLoc);
265
266 // Slow path.
267 auto OffsetCommentBehindDecl =
268 CommentsInTheFile.lower_bound(LocDecomp.second);
269
270 // First check whether we have a trailing comment.
271 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
272 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
273 if ((CommentBehindDecl->isDocumentation() ||
274 LangOpts.CommentOpts.ParseAllComments) &&
275 CommentBehindDecl->isTrailingComment() &&
276 (IsMacro || (D && (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) ||
278 isa<ObjCPropertyDecl>(D))))) {
279
280 // Check that Doxygen trailing comment comes after the declaration, starts
281 // on the same line and in the same file as the declaration.
282 if (SourceMgr.getLineNumber(LocDecomp.first, LocDecomp.second) ==
283 Comments.getCommentBeginLine(CommentBehindDecl, LocDecomp.first,
284 OffsetCommentBehindDecl->first)) {
285 return CommentBehindDecl;
286 }
287 }
288 }
289
290 // The comment just after the declaration was not a trailing comment.
291 // Let's look at the previous comment.
292 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
293 return nullptr;
294
295 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
296 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
297
298 // Check that we actually have a non-member Doxygen comment.
299 if (!(CommentBeforeDecl->isDocumentation() ||
300 LangOpts.CommentOpts.ParseAllComments) ||
301 CommentBeforeDecl->isTrailingComment())
302 return nullptr;
303
304 // Decompose the end of the comment.
305 const unsigned CommentEndOffset =
306 Comments.getCommentEndOffset(CommentBeforeDecl);
307
308 // Get the corresponding buffer.
309 bool Invalid = false;
310 const char *Buffer =
311 SourceMgr.getBufferData(LocDecomp.first, &Invalid).data();
312 if (Invalid)
313 return nullptr;
314
315 // Extract text between the comment and declaration.
316 StringRef Text(Buffer + CommentEndOffset,
317 LocDecomp.second - CommentEndOffset);
318
319 // There should be no other declarations or preprocessor directives between
320 // comment and declaration.
321 if (Text.find_last_of(";{}#@") != StringRef::npos)
322 return nullptr;
323
324 return CommentBeforeDecl;
325}
326
328 const auto Locs = getLocsForCommentSearch(Key, SourceMgr);
329
330 for (const auto Loc : Locs) {
331 // If the declaration or macro doesn't map directly to a location in a file,
332 // we can't find the comment.
333 if (Loc.isInvalid() || !Loc.isFileID())
334 continue;
335
337 ExternalSource->ReadComments();
338 CommentsLoaded = true;
339 }
340
341 if (Comments.empty())
342 continue;
343
344 const FileID File = SourceMgr.getDecomposedLoc(Loc).first;
345 if (!File.isValid())
346 continue;
347
348 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
349 if (!CommentsInThisFile || CommentsInThisFile->empty())
350 continue;
351
352 if (RawComment *Comment =
353 getRawCommentNoCacheImpl(Key, Loc, *CommentsInThisFile))
354 return Comment;
355 }
356
357 return nullptr;
358}
359
361 assert(LangOpts.CommentOpts.RetainCommentsFromSystemHeaders ||
362 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
363 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
364}
365
366const RawComment *
368 const Decl **OriginalDecl) const {
369 if (Key.isNull()) {
370 if (OriginalDecl)
371 *OriginalDecl = nullptr;
372 return nullptr;
373 }
374
375 // Macros have no redeclaration chain: look up directly, populate the cache,
376 // and return.
377 if (const auto *MI = dyn_cast<const MacroInfo *>(Key)) {
378 if (OriginalDecl)
379 *OriginalDecl = nullptr;
380 auto Existing = RawComments.find(Key);
381 if (Existing != RawComments.end())
382 return Existing->second;
383 if (const RawComment *RC = getRawCommentNoCache(Key)) {
384 cacheRawComment(MI, *RC);
385 return RC;
386 }
387 return nullptr;
388 }
389
390 const Decl *D = cast<const Decl *>(Key);
391 D = &adjustDeclToTemplate(*D);
392
393 // Any comment directly attached to D?
394 {
395 auto DeclComment = RawComments.find(D);
396 if (DeclComment != RawComments.end()) {
397 if (OriginalDecl)
398 *OriginalDecl = D;
399 return DeclComment->second;
400 }
401 }
402
403 // Any comment attached to any redeclaration of D?
404 const Decl *CanonicalD = D->getCanonicalDecl();
405 if (!CanonicalD)
406 return nullptr;
407
408 {
409 auto RedeclComment = RedeclChainComments.find(CanonicalD);
410 if (RedeclComment != RedeclChainComments.end()) {
411 if (OriginalDecl)
412 *OriginalDecl = RedeclComment->second;
413 auto CommentAtRedecl = RawComments.find(RedeclComment->second);
414 assert(CommentAtRedecl != RawComments.end() &&
415 "This decl is supposed to have comment attached.");
416 return CommentAtRedecl->second;
417 }
418 }
419
420 // Any redeclarations of D that we haven't checked for comments yet?
421 const Decl *LastCheckedRedecl = [&]() {
422 const Decl *LastChecked = CommentlessRedeclChains.lookup(CanonicalD);
423 bool CanUseCommentlessCache = false;
424 if (LastChecked) {
425 for (auto *Redecl : CanonicalD->redecls()) {
426 if (Redecl == D) {
427 CanUseCommentlessCache = true;
428 break;
429 }
430 if (Redecl == LastChecked)
431 break;
432 }
433 }
434 // FIXME: This could be improved so that even if CanUseCommentlessCache
435 // is false, once we've traversed past CanonicalD we still skip ahead
436 // LastChecked.
437 return CanUseCommentlessCache ? LastChecked : nullptr;
438 }();
439
440 for (const Decl *Redecl : D->redecls()) {
441 assert(Redecl);
442 // Skip all redeclarations that have been checked previously.
443 if (LastCheckedRedecl) {
444 if (LastCheckedRedecl == Redecl) {
445 LastCheckedRedecl = nullptr;
446 }
447 continue;
448 }
449 const RawComment *RedeclComment = getRawCommentNoCache(Redecl);
450 if (RedeclComment) {
451 cacheRawComment(Redecl, *RedeclComment);
452 if (OriginalDecl)
453 *OriginalDecl = Redecl;
454 return RedeclComment;
455 }
456 CommentlessRedeclChains[CanonicalD] = Redecl;
457 }
458
459 if (OriginalDecl)
460 *OriginalDecl = nullptr;
461 return nullptr;
462}
463
465 const RawComment &Comment) const {
466 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
467 RawComments.try_emplace(Original, &Comment);
468 if (const auto *D = dyn_cast<const Decl *>(Original)) {
469 const Decl *const CanonicalDecl = D->getCanonicalDecl();
470 RedeclChainComments.try_emplace(CanonicalDecl, D);
471 CommentlessRedeclChains.erase(CanonicalDecl);
472 }
473}
474
475static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
477 const DeclContext *DC = ObjCMethod->getDeclContext();
478 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
479 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
480 if (!ID)
481 return;
482 // Add redeclared method here.
483 for (const auto *Ext : ID->known_extensions()) {
484 if (ObjCMethodDecl *RedeclaredMethod =
485 Ext->getMethod(ObjCMethod->getSelector(),
486 ObjCMethod->isInstanceMethod()))
487 Redeclared.push_back(RedeclaredMethod);
488 }
489 }
490}
491
493 const Preprocessor *PP) {
494 if (Comments.empty() || Decls.empty())
495 return;
496
497 FileID File;
498 for (const Decl *D : Decls) {
499 if (D->isInvalidDecl())
500 continue;
501
502 D = &adjustDeclToTemplate(*D);
503 SourceLocation Loc = D->getLocation();
504 if (Loc.isValid()) {
505 // See if there are any new comments that are not attached to a decl.
506 // The location doesn't have to be precise - we care only about the file.
507 File = SourceMgr.getDecomposedLoc(Loc).first;
508 break;
509 }
510 }
511
512 if (File.isInvalid())
513 return;
514
515 auto CommentsInThisFile = Comments.getCommentsInFile(File);
516 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
517 CommentsInThisFile->rbegin()->second->isAttached())
518 return;
519
520 // There is at least one comment not attached to a decl.
521 // Maybe it should be attached to one of Decls?
522 //
523 // Note that this way we pick up not only comments that precede the
524 // declaration, but also comments that *follow* the declaration -- thanks to
525 // the lookahead in the lexer: we've consumed the semicolon and looked
526 // ahead through comments.
527 for (const Decl *D : Decls) {
528 assert(D);
529 if (D->isInvalidDecl())
530 continue;
531
532 D = &adjustDeclToTemplate(*D);
533
534 if (RawComments.count(D) > 0)
535 continue;
536
537 const auto DeclLocs = getLocsForCommentSearch(D, SourceMgr);
538
539 for (const auto DeclLoc : DeclLocs) {
540 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
541 continue;
542
543 if (RawComment *const DocComment =
544 getRawCommentNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
545 cacheRawComment(D, *DocComment);
546 comments::FullComment *FC = DocComment->parse(*this, PP, D);
547 ParsedComments[D->getCanonicalDecl()] = FC;
548 break;
549 }
550 }
551 }
552}
553
555 const Decl *D) const {
556 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
557 ThisDeclInfo->CommentDecl = D;
558 ThisDeclInfo->IsFilled = false;
559 ThisDeclInfo->fill();
560 ThisDeclInfo->CommentDecl = FC->getDecl();
561 if (!ThisDeclInfo->TemplateParameters)
562 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
564 new (*this) comments::FullComment(FC->getBlocks(),
565 ThisDeclInfo);
566 return CFC;
567}
568
570 const RawComment *RC = getRawCommentNoCache(D);
571 return RC ? RC->parse(*this, nullptr, D) : nullptr;
572}
573
575 const Decl *D,
576 const Preprocessor *PP) const {
577 if (!D || D->isInvalidDecl())
578 return nullptr;
579 D = &adjustDeclToTemplate(*D);
580
581 const Decl *Canonical = D->getCanonicalDecl();
582 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
583 ParsedComments.find(Canonical);
584
585 if (Pos != ParsedComments.end()) {
586 if (Canonical != D) {
587 comments::FullComment *FC = Pos->second;
589 return CFC;
590 }
591 return Pos->second;
592 }
593
594 const Decl *OriginalDecl = nullptr;
595
596 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
597 if (!RC) {
600 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
601 if (OMD && OMD->isPropertyAccessor())
602 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
603 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
604 return cloneFullComment(FC, D);
605 if (OMD)
606 addRedeclaredMethods(OMD, Overridden);
607 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
608 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
609 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
610 return cloneFullComment(FC, D);
611 }
612 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
613 // Attach any tag type's documentation to its typedef if latter
614 // does not have one of its own.
615 QualType QT = TD->getUnderlyingType();
616 if (const auto *TT = QT->getAs<TagType>())
617 if (comments::FullComment *FC = getCommentForDecl(TT->getDecl(), PP))
618 return cloneFullComment(FC, D);
619 }
620 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
621 while (IC->getSuperClass()) {
622 IC = IC->getSuperClass();
624 return cloneFullComment(FC, D);
625 }
626 }
627 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
628 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
630 return cloneFullComment(FC, D);
631 }
632 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
633 if (!(RD = RD->getDefinition()))
634 return nullptr;
635 // Check non-virtual bases.
636 for (const auto &I : RD->bases()) {
637 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
638 continue;
639 QualType Ty = I.getType();
640 if (Ty.isNull())
641 continue;
643 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
644 continue;
645
647 return cloneFullComment(FC, D);
648 }
649 }
650 // Check virtual bases.
651 for (const auto &I : RD->vbases()) {
652 if (I.getAccessSpecifier() != AS_public)
653 continue;
654 QualType Ty = I.getType();
655 if (Ty.isNull())
656 continue;
657 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
658 if (!(VirtualBase= VirtualBase->getDefinition()))
659 continue;
661 return cloneFullComment(FC, D);
662 }
663 }
664 }
665 return nullptr;
666 }
667
668 // If the RawComment was attached to other redeclaration of this Decl, we
669 // should parse the comment in context of that other Decl. This is important
670 // because comments can contain references to parameter names which can be
671 // different across redeclarations.
672 if (D != OriginalDecl && OriginalDecl)
673 return getCommentForDecl(OriginalDecl, PP);
674
675 comments::FullComment *FC = RC->parse(*this, PP, D);
676 ParsedComments[Canonical] = FC;
677 return FC;
678}
679
680void ASTContext::CanonicalTemplateTemplateParm::Profile(
681 llvm::FoldingSetNodeID &ID, const ASTContext &C,
683 ID.AddInteger(Parm->getDepth());
684 ID.AddInteger(Parm->getPosition());
685 ID.AddBoolean(Parm->isParameterPack());
686 ID.AddInteger(Parm->templateParameterKind());
687
689 ID.AddInteger(Params->size());
691 PEnd = Params->end();
692 P != PEnd; ++P) {
693 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
694 ID.AddInteger(0);
695 ID.AddBoolean(TTP->isParameterPack());
696 ID.AddInteger(
697 TTP->getNumExpansionParameters().toInternalRepresentation());
698 continue;
699 }
700
701 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
702 ID.AddInteger(1);
703 ID.AddBoolean(NTTP->isParameterPack());
704 ID.AddPointer(C.getUnconstrainedType(C.getCanonicalType(NTTP->getType()))
705 .getAsOpaquePtr());
706 if (NTTP->isExpandedParameterPack()) {
707 ID.AddBoolean(true);
708 ID.AddInteger(NTTP->getNumExpansionTypes());
709 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
710 QualType T = NTTP->getExpansionType(I);
711 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
712 }
713 } else
714 ID.AddBoolean(false);
715 continue;
716 }
717
718 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
719 ID.AddInteger(2);
720 Profile(ID, C, TTP);
721 }
722}
723
724TemplateTemplateParmDecl *
726 TemplateTemplateParmDecl *TTP) const {
727 // Check if we already have a canonical template template parameter.
728 llvm::FoldingSetNodeID ID;
729 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
730 llvm::FoldingSetInsertToken Token;
731 CanonicalTemplateTemplateParm *Canonical =
732 CanonTemplateTemplateParms.lookup(ID, Token);
733 if (Canonical)
734 return Canonical->getParam();
735
736 // Build a canonical template parameter list.
738 SmallVector<NamedDecl *, 4> CanonParams;
739 CanonParams.reserve(Params->size());
741 PEnd = Params->end();
742 P != PEnd; ++P) {
743 // Note that, per C++20 [temp.over.link]/6, when determining whether
744 // template-parameters are equivalent, constraints are ignored.
745 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
748 TTP->getDepth(), TTP->getIndex(), nullptr, false,
749 TTP->isParameterPack(), /*HasTypeConstraint=*/false,
750 TTP->getNumExpansionParameters());
751 CanonParams.push_back(NewTTP);
752 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
756 if (NTTP->isExpandedParameterPack()) {
757 SmallVector<QualType, 2> ExpandedTypes;
759 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
760 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
761 ExpandedTInfos.push_back(
762 getTrivialTypeSourceInfo(ExpandedTypes.back()));
763 }
764
768 NTTP->getDepth(),
769 NTTP->getPosition(), nullptr,
770 T,
771 TInfo,
772 ExpandedTypes,
773 ExpandedTInfos);
774 } else {
778 NTTP->getDepth(),
779 NTTP->getPosition(), nullptr,
780 T,
781 NTTP->isParameterPack(),
782 TInfo);
783 }
784 CanonParams.push_back(Param);
785 } else
786 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
788 }
789
792 TTP->getPosition(), TTP->isParameterPack(), nullptr,
794 /*Typename=*/false,
796 CanonParams, SourceLocation(),
797 /*RequiresClause=*/nullptr));
798
799 // Get the new insert position for the node we care about.
800 Canonical = CanonTemplateTemplateParms.lookup(ID, Token);
801 assert(!Canonical && "Shouldn't be in the map!");
802 (void)Canonical;
803
804 // Create the canonical template template parameter entry.
805 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
806 CanonTemplateTemplateParms.insert(Canonical, Token);
807 return CanonTTP;
808}
809
812 TemplateTemplateParmDecl *TTP) const {
813 llvm::FoldingSetNodeID ID;
814 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
815 llvm::FoldingSetInsertToken Token;
816 CanonicalTemplateTemplateParm *Canonical =
817 CanonTemplateTemplateParms.lookup(ID, Token);
818 return Canonical ? Canonical->getParam() : nullptr;
819}
820
823 TemplateTemplateParmDecl *CanonTTP) const {
824 llvm::FoldingSetNodeID ID;
825 CanonicalTemplateTemplateParm::Profile(ID, *this, CanonTTP);
826 llvm::FoldingSetInsertToken Token;
827 if (auto *Existing = CanonTemplateTemplateParms.lookup(ID, Token))
828 return Existing->getParam();
829 CanonTemplateTemplateParms.insert(
830 new (*this) CanonicalTemplateTemplateParm(CanonTTP), Token);
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 const LangOptions &LangOpts) {
913 switch (LangOpts.getAddressSpaceMapMangling()) {
915 return TI.useAddressSpaceMapMangling();
917 return true;
919 return false;
920 }
921 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
922}
923
925 IdentifierTable &idents, SelectorTable &sels,
927 : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
928 DependentSizedArrayTypes(this_()), DependentSizedExtVectorTypes(this_()),
929 DependentAddressSpaceTypes(this_()), DependentVectorTypes(this_()),
930 DependentSizedMatrixTypes(this_()),
931 FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
932 DependentTypeOfExprTypes(this_()), DependentDecltypeTypes(this_()),
933 DependentPackIndexingTypes(this_()), TemplateSpecializationTypes(this_()),
934 AttributedTypes(this_()), DependentBitIntTypes(this_()),
935 HLSLAttributedResourceTypes(this_()),
936 SubstTemplateTemplateParmPacks(this_()), DeducedTemplates(this_()),
937 PackIndexingTemplates(this_()), ArrayParameterTypes(this_()),
938 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
939 NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
940 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
941 LangOpts.XRayNeverInstrumentFiles,
942 LangOpts.XRayAttrListFiles, SM)),
943 ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
944 PrintingPolicy(LOpts), ParentMapCtx(new ParentMapContext(*this)),
945 Idents(idents), Selectors(sels), BuiltinInfo(builtins), TUKind(TUKind),
946 DeclarationNames(*this), Comments(SM),
947 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
948 CompCategories(this_()), LastSDM(nullptr, 0) {
950}
951
953 // Release the DenseMaps associated with DeclContext objects.
954 // FIXME: Is this the ideal solution?
955 ReleaseDeclContextMaps();
956
957 // Call all of the deallocation functions on all of their targets.
958 for (auto &Pair : Deallocations)
959 (Pair.first)(Pair.second);
960 Deallocations.clear();
961
962 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
963 // because they can contain DenseMaps.
964 for (llvm::DenseMap<const ObjCInterfaceDecl *,
966 I = ObjCLayouts.begin(),
967 E = ObjCLayouts.end();
968 I != E;)
969 // Increment in loop to prevent using deallocated memory.
970 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
971 R->Destroy(*this);
972 ObjCLayouts.clear();
973
974 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
975 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
976 // Increment in loop to prevent using deallocated memory.
977 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
978 R->Destroy(*this);
979 }
980 ASTRecordLayouts.clear();
981
982 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
983 AEnd = DeclAttrs.end();
984 A != AEnd; ++A)
985 A->second->~AttrVec();
986 DeclAttrs.clear();
987 LastDeclAttrsDecl = nullptr;
988
989 CtorClosureDefaultArgs.clear();
990
991 for (const auto &Value : ModuleInitializers)
992 Value.second->~PerModuleInitializers();
993 ModuleInitializers.clear();
994
995 TUDecl = nullptr;
996 XRayFilter.reset();
997 NoSanitizeL.reset();
998}
999
1001
1002void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1003 TraversalScope = TopLevelDecls;
1005}
1006
1007void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1008 Deallocations.push_back({Callback, Data});
1009}
1010
1011void
1015
1017 llvm::errs() << "\n*** AST Context Stats:\n";
1018 llvm::errs() << " " << Types.size() << " types total.\n";
1019
1020 unsigned counts[] = {
1021#define TYPE(Name, Parent) 0,
1022#define ABSTRACT_TYPE(Name, Parent)
1023#include "clang/AST/TypeNodes.inc"
1024 0 // Extra
1025 };
1026
1027 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1028 Type *T = Types[i];
1029 counts[(unsigned)T->getTypeClass()]++;
1030 }
1031
1032 unsigned Idx = 0;
1033 unsigned TotalBytes = 0;
1034#define TYPE(Name, Parent) \
1035 if (counts[Idx]) \
1036 llvm::errs() << " " << counts[Idx] << " " << #Name \
1037 << " types, " << sizeof(Name##Type) << " each " \
1038 << "(" << counts[Idx] * sizeof(Name##Type) \
1039 << " bytes)\n"; \
1040 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1041 ++Idx;
1042#define ABSTRACT_TYPE(Name, Parent)
1043#include "clang/AST/TypeNodes.inc"
1044
1045 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1046
1047 // Implicit special member functions.
1048 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1050 << " implicit default constructors created\n";
1051 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1053 << " implicit copy constructors created\n";
1054 if (getLangOpts().CPlusPlus)
1055 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1057 << " implicit move constructors created\n";
1058 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1060 << " implicit copy assignment operators created\n";
1061 if (getLangOpts().CPlusPlus)
1062 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1064 << " implicit move assignment operators created\n";
1065 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1067 << " implicit destructors created\n";
1068
1069 if (ExternalSource) {
1070 llvm::errs() << "\n";
1071 ExternalSource->PrintStats();
1072 }
1073
1074 BumpAlloc.PrintStats();
1075}
1076
1078 bool NotifyListeners) {
1079 if (NotifyListeners)
1080 if (auto *Listener = getASTMutationListener();
1082 Listener->RedefinedHiddenDefinition(ND, M);
1083
1084 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1085}
1086
1088 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1089 if (It == MergedDefModules.end())
1090 return;
1091
1092 auto &Merged = It->second;
1093 llvm::DenseSet<Module*> Found;
1094 for (Module *&M : Merged)
1095 if (!Found.insert(M).second)
1096 M = nullptr;
1097 llvm::erase(Merged, nullptr);
1098}
1099
1102 auto MergedIt =
1103 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1104 if (MergedIt == MergedDefModules.end())
1105 return {};
1106 return MergedIt->second;
1107}
1108
1109void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1110 if (LazyInitializers.empty())
1111 return;
1112
1113 auto *Source = Ctx.getExternalSource();
1114 assert(Source && "lazy initializers but no external source");
1115
1116 auto LazyInits = std::move(LazyInitializers);
1117 LazyInitializers.clear();
1118
1119 for (auto ID : LazyInits)
1120 Initializers.push_back(Source->GetExternalDecl(ID));
1121
1122 assert(LazyInitializers.empty() &&
1123 "GetExternalDecl for lazy module initializer added more inits");
1124}
1125
1127 // One special case: if we add a module initializer that imports another
1128 // module, and that module's only initializer is an ImportDecl, simplify.
1129 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1130 auto It = ModuleInitializers.find(ID->getImportedModule());
1131
1132 // Maybe the ImportDecl does nothing at all. (Common case.)
1133 if (It == ModuleInitializers.end())
1134 return;
1135
1136 // Maybe the ImportDecl only imports another ImportDecl.
1137 auto &Imported = *It->second;
1138 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1139 Imported.resolve(*this);
1140 auto *OnlyDecl = Imported.Initializers.front();
1141 if (isa<ImportDecl>(OnlyDecl))
1142 D = OnlyDecl;
1143 }
1144 }
1145
1146 auto *&Inits = ModuleInitializers[M];
1147 if (!Inits)
1148 Inits = new (*this) PerModuleInitializers;
1149 Inits->Initializers.push_back(D);
1150}
1151
1154 auto *&Inits = ModuleInitializers[M];
1155 if (!Inits)
1156 Inits = new (*this) PerModuleInitializers;
1157 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1158 IDs.begin(), IDs.end());
1159}
1160
1162 auto It = ModuleInitializers.find(M);
1163 if (It == ModuleInitializers.end())
1164 return {};
1165
1166 auto *Inits = It->second;
1167 Inits->resolve(*this);
1168 return Inits->Initializers;
1169}
1170
1172 assert(M->isNamedModule());
1173 assert(!CurrentCXXNamedModule &&
1174 "We should set named module for ASTContext for only once");
1175 CurrentCXXNamedModule = M;
1176}
1177
1178bool ASTContext::isInSameModule(const Module *M1, const Module *M2) const {
1179 if (!M1 != !M2)
1180 return false;
1181
1182 /// Get the representative module for M. The representative module is the
1183 /// first module unit for a specific primary module name. So that the module
1184 /// units have the same representative module belongs to the same module.
1185 ///
1186 /// The process is helpful to reduce the expensive string operations.
1187 auto GetRepresentativeModule = [this](const Module *M) {
1188 auto Iter = SameModuleLookupSet.find(M);
1189 if (Iter != SameModuleLookupSet.end())
1190 return Iter->second;
1191
1192 const Module *RepresentativeModule =
1193 PrimaryModuleNameMap.try_emplace(M->getPrimaryModuleInterfaceName(), M)
1194 .first->second;
1195 SameModuleLookupSet[M] = RepresentativeModule;
1196 return RepresentativeModule;
1197 };
1198
1199 assert(M1 && "Shouldn't call `isInSameModule` if both M1 and M2 are none.");
1200 return GetRepresentativeModule(M1) == GetRepresentativeModule(M2);
1201}
1202
1204 if (!ExternCContext)
1205 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1206
1207 return ExternCContext;
1208}
1209
1220
1221#define BuiltinTemplate(BTName) \
1222 BuiltinTemplateDecl *ASTContext::get##BTName##Decl() const { \
1223 if (!Decl##BTName) \
1224 Decl##BTName = \
1225 buildBuiltinTemplateDecl(BTK##BTName, get##BTName##Name()); \
1226 return Decl##BTName; \
1227 }
1228#include "clang/Basic/BuiltinTemplates.inc"
1229
1231 RecordDecl::TagKind TK) const {
1232 SourceLocation Loc;
1233 RecordDecl *NewDecl;
1234 if (getLangOpts().CPlusPlus)
1235 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1236 Loc, &Idents.get(Name));
1237 else
1238 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1239 &Idents.get(Name));
1240 NewDecl->setImplicit();
1241 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1242 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1243 return NewDecl;
1244}
1245
1247 StringRef Name) const {
1250 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1251 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1252 NewDecl->setImplicit();
1253 return NewDecl;
1254}
1255
1257 if (!Int128Decl)
1258 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1259 return Int128Decl;
1260}
1261
1263 if (!UInt128Decl)
1264 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1265 return UInt128Decl;
1266}
1267
1268void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1269 auto *Ty = new (*this, alignof(BuiltinType)) BuiltinType(K);
1271 Types.push_back(Ty);
1272}
1273
1275 const TargetInfo *AuxTarget) {
1276 assert((!this->Target || this->Target == &Target) &&
1277 "Incorrect target reinitialization");
1278 assert(VoidTy.isNull() && "Context reinitialized?");
1279
1280 this->Target = &Target;
1281 this->AuxTarget = AuxTarget;
1282
1283 ABI.reset(createCXXABI(Target));
1284 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1285
1286 // C99 6.2.5p19.
1287 InitBuiltinType(VoidTy, BuiltinType::Void);
1288
1289 // C99 6.2.5p2.
1290 InitBuiltinType(BoolTy, BuiltinType::Bool);
1291 // C99 6.2.5p3.
1292 if (LangOpts.CharIsSigned)
1293 InitBuiltinType(CharTy, BuiltinType::Char_S);
1294 else
1295 InitBuiltinType(CharTy, BuiltinType::Char_U);
1296 // C99 6.2.5p4.
1297 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1298 InitBuiltinType(ShortTy, BuiltinType::Short);
1299 InitBuiltinType(IntTy, BuiltinType::Int);
1300 InitBuiltinType(LongTy, BuiltinType::Long);
1301 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1302
1303 // C99 6.2.5p6.
1304 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1305 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1306 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1307 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1308 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1309
1310 // C99 6.2.5p10.
1311 InitBuiltinType(FloatTy, BuiltinType::Float);
1312 InitBuiltinType(DoubleTy, BuiltinType::Double);
1313 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1314
1315 // GNU extension, __float128 for IEEE quadruple precision
1316 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1317
1318 // __ibm128 for IBM extended precision
1319 InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
1320
1321 // C11 extension ISO/IEC TS 18661-3
1322 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1323
1324 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1325 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1326 InitBuiltinType(AccumTy, BuiltinType::Accum);
1327 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1328 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1329 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1330 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1331 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1332 InitBuiltinType(FractTy, BuiltinType::Fract);
1333 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1334 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1335 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1336 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1337 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1338 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1339 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1340 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1341 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1342 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1343 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1344 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1345 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1346 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1347 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1348 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1349
1350 // GNU extension, 128-bit integers.
1351 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1352 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1353
1354 // C++ 3.9.1p5
1355 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1356 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1357 else // -fshort-wchar makes wchar_t be unsigned.
1358 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1359 if (LangOpts.CPlusPlus && LangOpts.WChar)
1361 else {
1362 // C99 (or C++ using -fno-wchar).
1363 WideCharTy = getFromTargetType(Target.getWCharType());
1364 }
1365
1366 WIntTy = getFromTargetType(Target.getWIntType());
1367
1368 // C++20 (proposed)
1369 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1370
1371 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1372 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1373 else // C99
1374 Char16Ty = getFromTargetType(Target.getChar16Type());
1375
1376 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1377 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1378 else // C99
1379 Char32Ty = getFromTargetType(Target.getChar32Type());
1380
1381 // Placeholder type for type-dependent expressions whose type is
1382 // completely unknown. No code should ever check a type against
1383 // DependentTy and users should never see it; however, it is here to
1384 // help diagnose failures to properly check for type-dependent
1385 // expressions.
1386 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1387
1388 // Placeholder type for functions.
1389 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1390
1391 // Placeholder type for bound members.
1392 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1393
1394 // Placeholder type for unresolved templates.
1395 InitBuiltinType(UnresolvedTemplateTy, BuiltinType::UnresolvedTemplate);
1396
1397 // Placeholder type for pseudo-objects.
1398 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1399
1400 // "any" type; useful for debugger-like clients.
1401 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1402
1403 // Placeholder type for unbridged ARC casts.
1404 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1405
1406 // Placeholder type for builtin functions.
1407 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1408
1409 // Placeholder type for OMP array sections.
1410 if (LangOpts.OpenMP) {
1411 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1412 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1413 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1414 }
1415 // Placeholder type for OpenACC array sections, if we are ALSO in OMP mode,
1416 // don't bother, as we're just using the same type as OMP.
1417 if (LangOpts.OpenACC && !LangOpts.OpenMP) {
1418 InitBuiltinType(ArraySectionTy, BuiltinType::ArraySection);
1419 }
1420 if (LangOpts.MatrixTypes)
1421 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1422
1423 // Builtin types for 'id', 'Class', and 'SEL'.
1424 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1425 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1426 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1427
1428 if (LangOpts.OpenCL) {
1429#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1430 InitBuiltinType(SingletonId, BuiltinType::Id);
1431#include "clang/Basic/OpenCLImageTypes.def"
1432
1433 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1434 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1435 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1436 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1437 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1438
1439#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1440 InitBuiltinType(Id##Ty, BuiltinType::Id);
1441#include "clang/Basic/OpenCLExtensionTypes.def"
1442 }
1443
1444 if (LangOpts.HLSL) {
1445#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1446 InitBuiltinType(SingletonId, BuiltinType::Id);
1447#include "clang/Basic/HLSLIntangibleTypes.def"
1448
1449#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1450 InitBuiltinType(SingletonId, BuiltinType::Id);
1451#include "clang/Basic/HLSLPackedTypes.def"
1452 }
1453
1454 if (Target.hasAArch64ACLETypes() ||
1455 (AuxTarget && AuxTarget->hasAArch64ACLETypes())) {
1456#define SVE_TYPE(Name, Id, SingletonId) \
1457 InitBuiltinType(SingletonId, BuiltinType::Id);
1458#include "clang/Basic/AArch64ACLETypes.def"
1459 }
1460
1461 if (Target.getTriple().isPPC64()) {
1462#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
1463 InitBuiltinType(Id##Ty, BuiltinType::Id);
1464#include "clang/Basic/PPCTypes.def"
1465#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
1466 InitBuiltinType(Id##Ty, BuiltinType::Id);
1467#include "clang/Basic/PPCTypes.def"
1468 }
1469
1470 if (Target.hasRISCVVTypes()) {
1471#define RVV_TYPE(Name, Id, SingletonId) \
1472 InitBuiltinType(SingletonId, BuiltinType::Id);
1473#include "clang/Basic/RISCVVTypes.def"
1474 }
1475
1476 if (Target.getTriple().isWasm() && Target.hasFeature("reference-types")) {
1477#define WASM_TYPE(Name, Id, SingletonId) \
1478 InitBuiltinType(SingletonId, BuiltinType::Id);
1479#include "clang/Basic/WebAssemblyReferenceTypes.def"
1480 }
1481
1482 if (Target.hasAMDGPUTypes() || (AuxTarget && (AuxTarget->hasAMDGPUTypes()))) {
1483#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
1484 InitBuiltinType(SingletonId, BuiltinType::Id);
1485#include "clang/Basic/AMDGPUTypes.def"
1486 }
1487
1488 if (Target.getTriple().isSPIRV() ||
1489 (AuxTarget && AuxTarget->getTriple().isSPIRV())) {
1490#define SPIRV_TYPE(Name, Id, SingletonId) \
1491 InitBuiltinType(SingletonId, BuiltinType::Id);
1492#include "clang/Basic/SPIRVTypes.def"
1493 }
1494
1495 // Builtin type for __objc_yes and __objc_no
1496 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1498
1499 ObjCConstantStringType = QualType();
1500
1501 ObjCSuperType = QualType();
1502
1503 // void * type
1504 if (LangOpts.OpenCLGenericAddressSpace) {
1505 auto Q = VoidTy.getQualifiers();
1506 Q.setAddressSpace(LangAS::opencl_generic);
1508 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1509 } else {
1511 }
1512
1513 // nullptr type (C++0x 2.14.7)
1514 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1515
1516 // std::meta::info type (C++26 21.4.1)
1517 InitBuiltinType(MetaInfoTy, BuiltinType::MetaInfo);
1518
1519 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1520 InitBuiltinType(HalfTy, BuiltinType::Half);
1521
1522 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1523
1524 // Builtin type used to help define __builtin_va_list.
1525 VaListTagDecl = nullptr;
1526
1527 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1528 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1531 }
1532}
1533
1535 return SourceMgr.getDiagnostics();
1536}
1537
1539 // 85% of lookups use the most recent D, so use a one-entry cache.
1540 if (LastDeclAttrsDecl == D) {
1541 assert(LastDeclAttrs != nullptr && LastDeclAttrs == DeclAttrs[D]);
1542 return *LastDeclAttrs;
1543 }
1544
1545 AttrVec *&Result = DeclAttrs[D];
1546 if (!Result) {
1547 void *Mem = Allocate(sizeof(AttrVec));
1548 Result = new (Mem) AttrVec;
1549 }
1550
1551 LastDeclAttrsDecl = D;
1552 LastDeclAttrs = Result;
1553 return *Result;
1554}
1555
1556/// Erase the attributes corresponding to the given declaration.
1558 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1559 if (Pos != DeclAttrs.end()) {
1560 Pos->second->~AttrVec();
1561 DeclAttrs.erase(Pos);
1562 }
1563 if (LastDeclAttrsDecl == D)
1564 LastDeclAttrsDecl = nullptr;
1565}
1566
1569 return CtorClosureDefaultArgs.lookup(CD);
1570}
1571
1574 assert(!CtorClosureDefaultArgs.contains(CD));
1575 CtorClosureDefaultArgs[CD] = Args;
1576}
1577
1580 auto It =
1581 ExplicitInstantiations.find(cast<NamedDecl>(Spec->getCanonicalDecl()));
1582 if (It != ExplicitInstantiations.end())
1583 return It->second;
1584 return {};
1585}
1586
1589 ExplicitInstantiations[cast<NamedDecl>(Spec->getCanonicalDecl())].push_back(
1590 EID);
1591}
1592
1595 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1596 TemplateOrInstantiation.find(Var);
1597 if (Pos == TemplateOrInstantiation.end())
1598 return {};
1599
1600 return Pos->second;
1601}
1602
1603void
1606 SourceLocation PointOfInstantiation) {
1607 assert(Inst->isStaticDataMember() && "Not a static data member");
1608 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1610 Tmpl, TSK, PointOfInstantiation));
1611}
1612
1613void
1616 assert(!TemplateOrInstantiation[Inst] &&
1617 "Already noted what the variable was instantiated from");
1618 TemplateOrInstantiation[Inst] = TSI;
1619}
1620
1621NamedDecl *
1623 return InstantiatedFromUsingDecl.lookup(UUD);
1624}
1625
1626void
1628 assert((isa<UsingDecl>(Pattern) ||
1631 "pattern decl is not a using decl");
1632 assert((isa<UsingDecl>(Inst) ||
1635 "instantiation did not produce a using decl");
1636 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1637 InstantiatedFromUsingDecl[Inst] = Pattern;
1638}
1639
1642 return InstantiatedFromUsingEnumDecl.lookup(UUD);
1643}
1644
1646 UsingEnumDecl *Pattern) {
1647 assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
1648 InstantiatedFromUsingEnumDecl[Inst] = Pattern;
1649}
1650
1653 return InstantiatedFromUsingShadowDecl.lookup(Inst);
1654}
1655
1656void
1658 UsingShadowDecl *Pattern) {
1659 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1660 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1661}
1662
1663FieldDecl *
1665 return InstantiatedFromUnnamedFieldDecl.lookup(Field);
1666}
1667
1669 FieldDecl *Tmpl) {
1670 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1671 "Instantiated field decl is not unnamed");
1672 assert((!Inst->getDeclName() || Inst->isPlaceholderVar(getLangOpts())) &&
1673 "Template field decl is not unnamed");
1674 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1675 "Already noted what unnamed field was instantiated from");
1676
1677 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1678}
1679
1684
1689
1690unsigned
1692 auto Range = overridden_methods(Method);
1693 return Range.end() - Range.begin();
1694}
1695
1698 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1699 OverriddenMethods.find(Method->getCanonicalDecl());
1700 if (Pos == OverriddenMethods.end())
1701 return overridden_method_range(nullptr, nullptr);
1702 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1703}
1704
1706 const CXXMethodDecl *Overridden) {
1707 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1708 OverriddenMethods[Method].push_back(Overridden);
1709}
1710
1712 const NamedDecl *D,
1713 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1714 assert(D);
1715
1716 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1717 Overridden.append(overridden_methods_begin(CXXMethod),
1718 overridden_methods_end(CXXMethod));
1719 return;
1720 }
1721
1722 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1723 if (!Method)
1724 return;
1725
1727 Method->getOverriddenMethods(OverDecls);
1728 Overridden.append(OverDecls.begin(), OverDecls.end());
1729}
1730
1731std::optional<ASTContext::CXXRecordDeclRelocationInfo>
1733 assert(RD);
1734 CXXRecordDecl *D = RD->getDefinition();
1735 auto it = RelocatableClasses.find(D);
1736 if (it != RelocatableClasses.end())
1737 return it->getSecond();
1738 return std::nullopt;
1739}
1740
1743 assert(RD);
1744 CXXRecordDecl *D = RD->getDefinition();
1745 assert(RelocatableClasses.find(D) == RelocatableClasses.end());
1746 RelocatableClasses.insert({D, Info});
1747}
1748
1750 const ASTContext &Context, const CXXRecordDecl *Class) {
1751 if (!Class->isPolymorphic())
1752 return false;
1753 const CXXRecordDecl *BaseType = Context.baseForVTableAuthentication(Class);
1754 using AuthAttr = VTablePointerAuthenticationAttr;
1755 const AuthAttr *ExplicitAuth = BaseType->getAttr<AuthAttr>();
1756 if (!ExplicitAuth)
1757 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1758 AuthAttr::AddressDiscriminationMode AddressDiscrimination =
1759 ExplicitAuth->getAddressDiscrimination();
1760 if (AddressDiscrimination == AuthAttr::DefaultAddressDiscrimination)
1761 return Context.getLangOpts().PointerAuthVTPtrAddressDiscrimination;
1762 return AddressDiscrimination == AuthAttr::AddressDiscrimination;
1763}
1764
1765ASTContext::PointerAuthContent
1766ASTContext::findPointerAuthContent(QualType T) const {
1767 assert(isPointerAuthenticationAvailable());
1768
1769 T = T.getCanonicalType();
1770 if (T->isDependentType())
1771 return PointerAuthContent::None;
1772
1773 if (T.hasAddressDiscriminatedPointerAuth())
1774 return PointerAuthContent::AddressDiscriminatedData;
1775 const RecordDecl *RD = T->getAsRecordDecl();
1776 if (!RD)
1777 return PointerAuthContent::None;
1778
1779 if (RD->isInvalidDecl())
1780 return PointerAuthContent::None;
1781
1782 if (auto Existing = RecordContainsAddressDiscriminatedPointerAuth.find(RD);
1783 Existing != RecordContainsAddressDiscriminatedPointerAuth.end())
1784 return Existing->second;
1785
1786 PointerAuthContent Result = PointerAuthContent::None;
1787
1788 auto SaveResultAndReturn = [&]() -> PointerAuthContent {
1789 auto [ResultIter, DidAdd] =
1790 RecordContainsAddressDiscriminatedPointerAuth.try_emplace(RD, Result);
1791 (void)ResultIter;
1792 (void)DidAdd;
1793 assert(DidAdd);
1794 return Result;
1795 };
1796 auto ShouldContinueAfterUpdate = [&](PointerAuthContent NewResult) {
1797 static_assert(PointerAuthContent::None <
1798 PointerAuthContent::AddressDiscriminatedVTable);
1799 static_assert(PointerAuthContent::AddressDiscriminatedVTable <
1800 PointerAuthContent::AddressDiscriminatedData);
1801 if (NewResult > Result)
1802 Result = NewResult;
1803 return Result != PointerAuthContent::AddressDiscriminatedData;
1804 };
1805 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1807 !ShouldContinueAfterUpdate(
1808 PointerAuthContent::AddressDiscriminatedVTable))
1809 return SaveResultAndReturn();
1810 for (auto Base : CXXRD->bases()) {
1811 if (!ShouldContinueAfterUpdate(findPointerAuthContent(Base.getType())))
1812 return SaveResultAndReturn();
1813 }
1814 }
1815 for (auto *FieldDecl : RD->fields()) {
1816 if (!ShouldContinueAfterUpdate(
1817 findPointerAuthContent(FieldDecl->getType())))
1818 return SaveResultAndReturn();
1819 }
1820 return SaveResultAndReturn();
1821}
1822
1824 assert(!Import->getNextLocalImport() &&
1825 "Import declaration already in the chain");
1826 assert(!Import->isFromASTFile() && "Non-local import declaration");
1827 if (!FirstLocalImport) {
1828 FirstLocalImport = Import;
1829 LastLocalImport = Import;
1830 return;
1831 }
1832
1833 LastLocalImport->setNextLocalImport(Import);
1834 LastLocalImport = Import;
1835}
1836
1837//===----------------------------------------------------------------------===//
1838// Type Sizing and Analysis
1839//===----------------------------------------------------------------------===//
1840
1841/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1842/// scalar floating point type.
1843const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1844 switch (T->castAs<BuiltinType>()->getKind()) {
1845 default:
1846 llvm_unreachable("Not a floating point type!");
1847 case BuiltinType::BFloat16:
1848 return Target->getBFloat16Format();
1849 case BuiltinType::Float16:
1850 return Target->getHalfFormat();
1851 case BuiltinType::Half:
1852 return Target->getHalfFormat();
1853 case BuiltinType::Float: return Target->getFloatFormat();
1854 case BuiltinType::Double: return Target->getDoubleFormat();
1855 case BuiltinType::Ibm128:
1856 return Target->getIbm128Format();
1857 case BuiltinType::LongDouble:
1858 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1859 return AuxTarget->getLongDoubleFormat();
1860 return Target->getLongDoubleFormat();
1861 case BuiltinType::Float128:
1862 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice)
1863 return AuxTarget->getFloat128Format();
1864 return Target->getFloat128Format();
1865 }
1866}
1867
1868CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1869 unsigned Align = Target->getCharWidth();
1870
1871 const unsigned AlignFromAttr = D->getMaxAlignment();
1872 if (AlignFromAttr)
1873 Align = AlignFromAttr;
1874
1875 // __attribute__((aligned)) can increase or decrease alignment
1876 // *except* on a struct or struct member, where it only increases
1877 // alignment unless 'packed' is also specified.
1878 //
1879 // It is an error for alignas to decrease alignment, so we can
1880 // ignore that possibility; Sema should diagnose it.
1881 bool UseAlignAttrOnly;
1882 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D))
1883 UseAlignAttrOnly =
1884 FD->hasAttr<PackedAttr>() || FD->getParent()->hasAttr<PackedAttr>();
1885 else
1886 UseAlignAttrOnly = AlignFromAttr != 0;
1887 // If we're using the align attribute only, just ignore everything
1888 // else about the declaration and its type.
1889 if (UseAlignAttrOnly) {
1890 // do nothing
1891 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1892 QualType T = VD->getType();
1893 if (const auto *RT = T->getAs<ReferenceType>()) {
1894 if (ForAlignof)
1895 T = RT->getPointeeType();
1896 else
1897 T = getPointerType(RT->getPointeeType());
1898 }
1899 QualType BaseT = getBaseElementType(T);
1900 if (T->isFunctionType())
1901 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1902 else if (!BaseT->isIncompleteType()) {
1903 // Adjust alignments of declarations with array type by the
1904 // large-array alignment on the target.
1905 if (const ArrayType *arrayType = getAsArrayType(T)) {
1906 unsigned MinWidth = Target->getLargeArrayMinWidth();
1907 if (!ForAlignof && MinWidth) {
1909 Align = std::max(Align, Target->getLargeArrayAlign());
1912 Align = std::max(Align, Target->getLargeArrayAlign());
1913 }
1914 }
1915 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1916 if (BaseT.getQualifiers().hasUnaligned())
1917 Align = Target->getCharWidth();
1918 }
1919
1920 // Ensure minimum alignment for global variables.
1921 if (const auto *VD = dyn_cast<VarDecl>(D))
1922 if (VD->hasGlobalStorage() && !ForAlignof) {
1923 uint64_t TypeSize =
1924 !BaseT->isIncompleteType() ? getTypeSize(T.getTypePtr()) : 0;
1925 Align = std::max(Align, getMinGlobalAlignOfVar(TypeSize, VD));
1926 }
1927
1928 // Fields can be subject to extra alignment constraints, like if
1929 // the field is packed, the struct is packed, or the struct has a
1930 // a max-field-alignment constraint (#pragma pack). So calculate
1931 // the actual alignment of the field within the struct, and then
1932 // (as we're expected to) constrain that by the alignment of the type.
1933 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1934 const RecordDecl *Parent = Field->getParent();
1935 // We can only produce a sensible answer if the record is valid.
1936 if (!Parent->isInvalidDecl()) {
1937 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1938
1939 // Start with the record's overall alignment.
1940 unsigned FieldAlign = toBits(Layout.getAlignment());
1941
1942 // Use the GCD of that and the offset within the record.
1943 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1944 if (Offset > 0) {
1945 // Alignment is always a power of 2, so the GCD will be a power of 2,
1946 // which means we get to do this crazy thing instead of Euclid's.
1947 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1948 if (LowBitOfOffset < FieldAlign)
1949 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1950 }
1951
1952 Align = std::min(Align, FieldAlign);
1953 }
1954 }
1955 }
1956
1957 // Some targets have hard limitation on the maximum requestable alignment in
1958 // aligned attribute for static variables.
1959 const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
1960 const auto *VD = dyn_cast<VarDecl>(D);
1961 if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
1962 Align = std::min(Align, MaxAlignedAttr);
1963
1964 return toCharUnitsFromBits(Align);
1965}
1966
1968 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1969}
1970
1971// getTypeInfoDataSizeInChars - Return the size of a type, in
1972// chars. If the type is a record, its data size is returned. This is
1973// the size of the memcpy that's performed when assigning this type
1974// using a trivial copy/move assignment operator.
1977
1978 // In C++, objects can sometimes be allocated into the tail padding
1979 // of a base-class subobject. We decide whether that's possible
1980 // during class layout, so here we can just trust the layout results.
1981 if (getLangOpts().CPlusPlus) {
1982 if (const auto *RD = T->getAsCXXRecordDecl(); RD && !RD->isInvalidDecl()) {
1983 const ASTRecordLayout &layout = getASTRecordLayout(RD);
1984 Info.Width = layout.getDataSize();
1985 }
1986 }
1987
1988 return Info;
1989}
1990
1991/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1992/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1995 const ConstantArrayType *CAT) {
1996 TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
1997 uint64_t Size = CAT->getZExtSize();
1998 assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
1999 (uint64_t)(-1)/Size) &&
2000 "Overflow in array type char size evaluation");
2001 uint64_t Width = EltInfo.Width.getQuantity() * Size;
2002 unsigned Align = EltInfo.Align.getQuantity();
2003 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2004 Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2005 Width = llvm::alignTo(Width, Align);
2008 EltInfo.AlignRequirement);
2009}
2010
2012 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2013 return getConstantArrayInfoInChars(*this, CAT);
2014 TypeInfo Info = getTypeInfo(T);
2017}
2018
2022
2024 // HLSL doesn't promote all small integer types to int, it
2025 // just uses the rank-based promotion rules for all types.
2026 if (getLangOpts().HLSL)
2027 return false;
2028
2029 if (const auto *BT = T->getAs<BuiltinType>())
2030 switch (BT->getKind()) {
2031 case BuiltinType::Bool:
2032 case BuiltinType::Char_S:
2033 case BuiltinType::Char_U:
2034 case BuiltinType::SChar:
2035 case BuiltinType::UChar:
2036 case BuiltinType::Short:
2037 case BuiltinType::UShort:
2038 case BuiltinType::WChar_S:
2039 case BuiltinType::WChar_U:
2040 case BuiltinType::Char8:
2041 case BuiltinType::Char16:
2042 case BuiltinType::Char32:
2043 return true;
2044 default:
2045 return false;
2046 }
2047
2048 // Enumerated types are promotable to their compatible integer types
2049 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2050 if (const auto *ED = T->getAsEnumDecl()) {
2051 if (T->isDependentType() || ED->getPromotionType().isNull() ||
2052 ED->isScoped())
2053 return false;
2054
2055 return true;
2056 }
2057
2058 // OverflowBehaviorTypes are promotable if their underlying type is promotable
2059 if (const auto *OBT = T->getAs<OverflowBehaviorType>()) {
2060 return isPromotableIntegerType(OBT->getUnderlyingType());
2061 }
2062
2063 return false;
2064}
2065
2067 return getTypeInfo(T).isAlignRequired();
2068}
2069
2071 return isAlignmentRequired(T.getTypePtr());
2072}
2073
2075 bool NeedsPreferredAlignment) const {
2076 // An alignment on a typedef overrides anything else.
2077 if (const auto *TT = T->getAs<TypedefType>())
2078 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2079 return Align;
2080
2081 // If we have an (array of) complete type, we're done.
2083 if (!T->isIncompleteType())
2084 return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
2085
2086 // If we had an array type, its element type might be a typedef
2087 // type with an alignment attribute.
2088 if (const auto *TT = T->getAs<TypedefType>())
2089 if (unsigned Align = TT->getDecl()->getMaxAlignment())
2090 return Align;
2091
2092 // Otherwise, see if the declaration of the type had an attribute.
2093 if (const auto *TD = T->getAsTagDecl())
2094 return TD->getMaxAlignment();
2095
2096 return 0;
2097}
2098
2100 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
2101 if (I != MemoizedTypeInfo.end())
2102 return I->second;
2103
2104 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
2105 TypeInfo TI = getTypeInfoImpl(T);
2106 MemoizedTypeInfo[T] = TI;
2107 return TI;
2108}
2109
2110/// getTypeInfoImpl - Return the size of the specified type, in bits. This
2111/// method does not work on incomplete types.
2112///
2113/// FIXME: Pointers into different addr spaces could have different sizes and
2114/// alignment requirements: getPointerInfo should take an AddrSpace, this
2115/// should take a QualType, &c.
2116TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
2117 uint64_t Width = 0;
2118 unsigned Align = 8;
2121 switch (T->getTypeClass()) {
2122#define TYPE(Class, Base)
2123#define ABSTRACT_TYPE(Class, Base)
2124#define NON_CANONICAL_TYPE(Class, Base)
2125#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2126#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
2127 case Type::Class: \
2128 assert(!T->isDependentType() && "should not see dependent types here"); \
2129 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
2130#include "clang/AST/TypeNodes.inc"
2131 llvm_unreachable("Should not see dependent types");
2132
2133 case Type::FunctionNoProto:
2134 case Type::FunctionProto:
2135 // GCC extension: alignof(function) = 32 bits
2136 Width = 0;
2137 Align = 32;
2138 break;
2139
2140 case Type::IncompleteArray:
2141 case Type::VariableArray:
2142 case Type::ConstantArray:
2143 case Type::ArrayParameter: {
2144 // Model non-constant sized arrays as size zero, but track the alignment.
2145 uint64_t Size = 0;
2146 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
2147 Size = CAT->getZExtSize();
2148
2149 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
2150 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
2151 "Overflow in array type bit size evaluation");
2152 Width = EltInfo.Width * Size;
2153 Align = EltInfo.Align;
2154 AlignRequirement = EltInfo.AlignRequirement;
2155 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
2156 getTargetInfo().getPointerWidth(LangAS::Default) == 64)
2157 Width = llvm::alignTo(Width, Align);
2158 break;
2159 }
2160
2161 case Type::ExtVector:
2162 case Type::Vector: {
2163 const auto *VT = cast<VectorType>(T);
2164 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
2165 Width = VT->isPackedVectorBoolType(*this)
2166 ? VT->getNumElements()
2167 : EltInfo.Width * VT->getNumElements();
2168 // Enforce at least byte size and alignment.
2169 Width = std::max<unsigned>(8, Width);
2170 Align = std::max<unsigned>(
2171 8, Target->vectorsAreElementAligned() ? EltInfo.Width : Width);
2172
2173 // If the alignment is not a power of 2, round up to the next power of 2.
2174 // This happens for non-power-of-2 length vectors.
2175 if (Align & (Align-1)) {
2176 Align = llvm::bit_ceil(Align);
2177 Width = llvm::alignTo(Width, Align);
2178 }
2179 // Adjust the alignment based on the target max.
2180 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
2181 if (TargetVectorAlign && TargetVectorAlign < Align)
2182 Align = TargetVectorAlign;
2183 if (VT->getVectorKind() == VectorKind::SveFixedLengthData)
2184 // Adjust the alignment for fixed-length SVE vectors. This is important
2185 // for non-power-of-2 vector lengths.
2186 Align = 128;
2187 else if (VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
2188 // Adjust the alignment for fixed-length SVE predicates.
2189 Align = 16;
2190 else if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
2191 VT->getVectorKind() == VectorKind::RVVFixedLengthMask ||
2192 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||
2193 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||
2194 VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4)
2195 // Adjust the alignment for fixed-length RVV vectors.
2196 Align = std::min<unsigned>(64, Width);
2197 // Vector types have their natural alignment resist reduction by
2198 // #pragma pack in MSVC record layout.
2199 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2200 break;
2201 }
2202
2203 case Type::ConstantMatrix: {
2204 const auto *MT = cast<ConstantMatrixType>(T);
2205 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
2206 // The internal layout of a matrix value is implementation defined.
2207 // Initially be ABI compatible with arrays with respect to alignment and
2208 // size.
2209 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
2210 Align = ElementInfo.Align;
2211 break;
2212 }
2213
2214 case Type::Builtin:
2215 switch (cast<BuiltinType>(T)->getKind()) {
2216 default: llvm_unreachable("Unknown builtin type!");
2217 case BuiltinType::Void:
2218 // GCC extension: alignof(void) = 8 bits.
2219 Width = 0;
2220 Align = 8;
2221 break;
2222 case BuiltinType::Bool:
2223 Width = Target->getBoolWidth();
2224 Align = Target->getBoolAlign();
2225 break;
2226 case BuiltinType::Char_S:
2227 case BuiltinType::Char_U:
2228 case BuiltinType::UChar:
2229 case BuiltinType::SChar:
2230 case BuiltinType::Char8:
2231 Width = Target->getCharWidth();
2232 Align = Target->getCharAlign();
2233 break;
2234 case BuiltinType::WChar_S:
2235 case BuiltinType::WChar_U:
2236 Width = Target->getWCharWidth();
2237 Align = Target->getWCharAlign();
2238 break;
2239 case BuiltinType::Char16:
2240 Width = Target->getChar16Width();
2241 Align = Target->getChar16Align();
2242 break;
2243 case BuiltinType::Char32:
2244 Width = Target->getChar32Width();
2245 Align = Target->getChar32Align();
2246 break;
2247 case BuiltinType::UShort:
2248 case BuiltinType::Short:
2249 Width = Target->getShortWidth();
2250 Align = Target->getShortAlign();
2251 break;
2252 case BuiltinType::UInt:
2253 case BuiltinType::Int:
2254 Width = Target->getIntWidth();
2255 Align = Target->getIntAlign();
2256 break;
2257 case BuiltinType::ULong:
2258 case BuiltinType::Long:
2259 Width = Target->getLongWidth();
2260 Align = Target->getLongAlign();
2261 break;
2262 case BuiltinType::ULongLong:
2263 case BuiltinType::LongLong:
2264 Width = Target->getLongLongWidth();
2265 Align = Target->getLongLongAlign();
2266 break;
2267 case BuiltinType::Int128:
2268 case BuiltinType::UInt128:
2269 Width = 128;
2270 Align = Target->getInt128Align();
2271 break;
2272 case BuiltinType::ShortAccum:
2273 case BuiltinType::UShortAccum:
2274 case BuiltinType::SatShortAccum:
2275 case BuiltinType::SatUShortAccum:
2276 Width = Target->getShortAccumWidth();
2277 Align = Target->getShortAccumAlign();
2278 break;
2279 case BuiltinType::Accum:
2280 case BuiltinType::UAccum:
2281 case BuiltinType::SatAccum:
2282 case BuiltinType::SatUAccum:
2283 Width = Target->getAccumWidth();
2284 Align = Target->getAccumAlign();
2285 break;
2286 case BuiltinType::LongAccum:
2287 case BuiltinType::ULongAccum:
2288 case BuiltinType::SatLongAccum:
2289 case BuiltinType::SatULongAccum:
2290 Width = Target->getLongAccumWidth();
2291 Align = Target->getLongAccumAlign();
2292 break;
2293 case BuiltinType::ShortFract:
2294 case BuiltinType::UShortFract:
2295 case BuiltinType::SatShortFract:
2296 case BuiltinType::SatUShortFract:
2297 Width = Target->getShortFractWidth();
2298 Align = Target->getShortFractAlign();
2299 break;
2300 case BuiltinType::Fract:
2301 case BuiltinType::UFract:
2302 case BuiltinType::SatFract:
2303 case BuiltinType::SatUFract:
2304 Width = Target->getFractWidth();
2305 Align = Target->getFractAlign();
2306 break;
2307 case BuiltinType::LongFract:
2308 case BuiltinType::ULongFract:
2309 case BuiltinType::SatLongFract:
2310 case BuiltinType::SatULongFract:
2311 Width = Target->getLongFractWidth();
2312 Align = Target->getLongFractAlign();
2313 break;
2314 case BuiltinType::BFloat16:
2315 if (Target->hasBFloat16Type()) {
2316 Width = Target->getBFloat16Width();
2317 Align = Target->getBFloat16Align();
2318 } else if ((getLangOpts().SYCLIsDevice ||
2319 (getLangOpts().OpenMP &&
2320 getLangOpts().OpenMPIsTargetDevice)) &&
2321 AuxTarget->hasBFloat16Type()) {
2322 Width = AuxTarget->getBFloat16Width();
2323 Align = AuxTarget->getBFloat16Align();
2324 }
2325 break;
2326 case BuiltinType::Float16:
2327 case BuiltinType::Half:
2328 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2329 !getLangOpts().OpenMPIsTargetDevice) {
2330 Width = Target->getHalfWidth();
2331 Align = Target->getHalfAlign();
2332 } else {
2333 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2334 "Expected OpenMP device compilation.");
2335 Width = AuxTarget->getHalfWidth();
2336 Align = AuxTarget->getHalfAlign();
2337 }
2338 break;
2339 case BuiltinType::Float:
2340 Width = Target->getFloatWidth();
2341 Align = Target->getFloatAlign();
2342 break;
2343 case BuiltinType::Double:
2344 Width = Target->getDoubleWidth();
2345 Align = Target->getDoubleAlign();
2346 break;
2347 case BuiltinType::Ibm128:
2348 Width = Target->getIbm128Width();
2349 Align = Target->getIbm128Align();
2350 break;
2351 case BuiltinType::LongDouble:
2352 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2353 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2354 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2355 Width = AuxTarget->getLongDoubleWidth();
2356 Align = AuxTarget->getLongDoubleAlign();
2357 } else {
2358 Width = Target->getLongDoubleWidth();
2359 Align = Target->getLongDoubleAlign();
2360 }
2361 // x87 extended precision (fp80) has its natural alignment resist
2362 // reduction by #pragma pack in MSVC record layout.
2363 if (&Target->getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
2364 AlignRequirement = AlignRequirementKind::ResistPragmaPack;
2365 break;
2366 case BuiltinType::Float128:
2367 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2368 !getLangOpts().OpenMPIsTargetDevice) {
2369 Width = Target->getFloat128Width();
2370 Align = Target->getFloat128Align();
2371 } else {
2372 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2373 "Expected OpenMP device compilation.");
2374 Width = AuxTarget->getFloat128Width();
2375 Align = AuxTarget->getFloat128Align();
2376 }
2377 break;
2378 case BuiltinType::NullPtr:
2379 // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
2380 Width = Target->getPointerWidth(LangAS::Default);
2381 Align = Target->getPointerAlign(LangAS::Default);
2382 break;
2383 case BuiltinType::MetaInfo:
2384 // sizeof(std::meta::info) == sizeof(void*)
2385 Width = Target->getPointerWidth(LangAS::Default);
2386 // alignof(std::meta::info) == alignof(void*)
2387 Align = Target->getPointerAlign(LangAS::Default);
2388 break;
2389 case BuiltinType::ObjCId:
2390 case BuiltinType::ObjCClass:
2391 case BuiltinType::ObjCSel:
2392 Width = Target->getPointerWidth(LangAS::Default);
2393 Align = Target->getPointerAlign(LangAS::Default);
2394 break;
2395 case BuiltinType::OCLSampler:
2396 case BuiltinType::OCLEvent:
2397 case BuiltinType::OCLClkEvent:
2398 case BuiltinType::OCLQueue:
2399 case BuiltinType::OCLReserveID:
2400#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2401 case BuiltinType::Id:
2402#include "clang/Basic/OpenCLImageTypes.def"
2403#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2404 case BuiltinType::Id:
2405#include "clang/Basic/OpenCLExtensionTypes.def"
2406 AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
2407 Width = Target->getPointerWidth(AS);
2408 Align = Target->getPointerAlign(AS);
2409 break;
2410 // The SVE types are effectively target-specific. The length of an
2411 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2412 // of 128 bits. There is one predicate bit for each vector byte, so the
2413 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2414 //
2415 // Because the length is only known at runtime, we use a dummy value
2416 // of 0 for the static length. The alignment values are those defined
2417 // by the Procedure Call Standard for the Arm Architecture.
2418#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2419 case BuiltinType::Id: \
2420 Width = 0; \
2421 Align = 128; \
2422 break;
2423#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2424 case BuiltinType::Id: \
2425 Width = 0; \
2426 Align = 16; \
2427 break;
2428#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2429 case BuiltinType::Id: \
2430 Width = 0; \
2431 Align = 16; \
2432 break;
2433#define SVE_SCALAR_TYPE(Name, MangledName, Id, SingletonId, Bits) \
2434 case BuiltinType::Id: \
2435 Width = Bits; \
2436 Align = Bits; \
2437 break;
2438#include "clang/Basic/AArch64ACLETypes.def"
2439#define PPC_VECTOR_TYPE(Name, Id, Size) \
2440 case BuiltinType::Id: \
2441 Width = Size; \
2442 Align = Size; \
2443 break;
2444#include "clang/Basic/PPCTypes.def"
2445#define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
2446 IsFP, IsBF) \
2447 case BuiltinType::Id: \
2448 Width = 0; \
2449 Align = ElBits; \
2450 break;
2451#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
2452 case BuiltinType::Id: \
2453 Width = 0; \
2454 Align = 8; \
2455 break;
2456#include "clang/Basic/RISCVVTypes.def"
2457#define WASM_TYPE(Name, Id, SingletonId) \
2458 case BuiltinType::Id: \
2459 Width = 0; \
2460 Align = 8; \
2461 break;
2462#include "clang/Basic/WebAssemblyReferenceTypes.def"
2463#define AMDGPU_TYPE(NAME, ID, SINGLETONID, WIDTH, ALIGN) \
2464 case BuiltinType::ID: \
2465 Width = WIDTH; \
2466 Align = ALIGN; \
2467 break;
2468#include "clang/Basic/AMDGPUTypes.def"
2469#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2470#include "clang/Basic/HLSLIntangibleTypes.def"
2471 Width = Target->getPointerWidth(LangAS::Default);
2472 Align = Target->getPointerAlign(LangAS::Default);
2473 break;
2474#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2475#include "clang/Basic/HLSLPackedTypes.def"
2476 Width = 32;
2477 Align = 32;
2478 break;
2479#define SPIRV_TYPE(Name, Id, SingletonId) \
2480 case BuiltinType::Id: \
2481 Width = Target->getPointerWidth(LangAS::Default); \
2482 Align = Target->getPointerAlign(LangAS::Default); \
2483 break;
2484#include "clang/Basic/SPIRVTypes.def"
2485 }
2486 break;
2487 case Type::ObjCObjectPointer:
2488 Width = Target->getPointerWidth(LangAS::Default);
2489 Align = Target->getPointerAlign(LangAS::Default);
2490 break;
2491 case Type::BlockPointer:
2492 AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
2493 Width = Target->getPointerWidth(AS);
2494 Align = Target->getPointerAlign(AS);
2495 break;
2496 case Type::LValueReference:
2497 case Type::RValueReference:
2498 // alignof and sizeof should never enter this code path here, so we go
2499 // the pointer route.
2500 AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
2501 Width = Target->getPointerWidth(AS);
2502 Align = Target->getPointerAlign(AS);
2503 break;
2504 case Type::Pointer:
2505 AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
2506 Width = Target->getPointerWidth(AS);
2507 Align = Target->getPointerAlign(AS);
2508 break;
2509 case Type::MemberPointer: {
2510 const auto *MPT = cast<MemberPointerType>(T);
2511 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2512 Width = MPI.Width;
2513 Align = MPI.Align;
2514 break;
2515 }
2516 case Type::Complex: {
2517 // Complex types have the same alignment as their elements, but twice the
2518 // size.
2519 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2520 Width = EltInfo.Width * 2;
2521 Align = EltInfo.Align;
2522 break;
2523 }
2524 case Type::ObjCObject:
2525 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2526 case Type::Adjusted:
2527 case Type::Decayed:
2528 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2529 case Type::ObjCInterface: {
2530 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2531 if (ObjCI->getDecl()->isInvalidDecl()) {
2532 Width = 8;
2533 Align = 8;
2534 break;
2535 }
2536 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2537 Width = toBits(Layout.getSize());
2538 Align = toBits(Layout.getAlignment());
2539 break;
2540 }
2541 case Type::BitInt: {
2542 const auto *EIT = cast<BitIntType>(T);
2543 Align = Target->getBitIntAlign(EIT->getNumBits());
2544 Width = Target->getBitIntWidth(EIT->getNumBits());
2545 break;
2546 }
2547 case Type::Record:
2548 case Type::Enum: {
2549 const auto *TT = cast<TagType>(T);
2550 const TagDecl *TD = TT->getDecl()->getDefinitionOrSelf();
2551
2552 if (TD->isInvalidDecl()) {
2553 Width = 8;
2554 Align = 8;
2555 break;
2556 }
2557
2558 if (isa<EnumType>(TT)) {
2559 const EnumDecl *ED = cast<EnumDecl>(TD);
2560 TypeInfo Info =
2562 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2563 Info.Align = AttrAlign;
2565 }
2566 return Info;
2567 }
2568
2569 const auto *RD = cast<RecordDecl>(TD);
2570 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2571 Width = toBits(Layout.getSize());
2572 Align = toBits(Layout.getAlignment());
2573 AlignRequirement = RD->hasAttr<AlignedAttr>()
2575 : AlignRequirementKind::None;
2576 break;
2577 }
2578
2579 case Type::SubstTemplateTypeParm:
2581 getReplacementType().getTypePtr());
2582
2583 case Type::Auto:
2584 case Type::DeducedTemplateSpecialization: {
2585 const auto *A = cast<DeducedType>(T);
2586 assert(!A->getDeducedType().isNull() &&
2587 "cannot request the size of an undeduced or dependent auto type");
2588 return getTypeInfo(A->getDeducedType().getTypePtr());
2589 }
2590
2591 case Type::Paren:
2592 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2593
2594 case Type::MacroQualified:
2595 return getTypeInfo(
2597
2598 case Type::ObjCTypeParam:
2599 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2600
2601 case Type::Using:
2602 return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
2603
2604 case Type::Typedef: {
2605 const auto *TT = cast<TypedefType>(T);
2606 TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
2607 // If the typedef has an aligned attribute on it, it overrides any computed
2608 // alignment we have. This violates the GCC documentation (which says that
2609 // attribute(aligned) can only round up) but matches its implementation.
2610 if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
2611 Align = AttrAlign;
2612 AlignRequirement = AlignRequirementKind::RequiredByTypedef;
2613 } else {
2614 Align = Info.Align;
2615 AlignRequirement = Info.AlignRequirement;
2616 }
2617 Width = Info.Width;
2618 break;
2619 }
2620
2621 case Type::Attributed:
2622 return getTypeInfo(
2623 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2624
2625 case Type::CountAttributed:
2626 return getTypeInfo(cast<CountAttributedType>(T)->desugar().getTypePtr());
2627
2628 case Type::LateParsedAttr:
2629 return getTypeInfo(cast<LateParsedAttrType>(T)->desugar().getTypePtr());
2630
2631 case Type::BTFTagAttributed:
2632 return getTypeInfo(
2633 cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
2634
2635 case Type::OverflowBehavior:
2636 return getTypeInfo(
2638
2639 case Type::HLSLAttributedResource:
2640 return getTypeInfo(
2641 cast<HLSLAttributedResourceType>(T)->getWrappedType().getTypePtr());
2642
2643 case Type::HLSLInlineSpirv: {
2644 const auto *ST = cast<HLSLInlineSpirvType>(T);
2645 // Size is specified in bytes, convert to bits
2646 Width = ST->getSize() * 8;
2647 Align = ST->getAlignment();
2648 if (Width == 0 && Align == 0) {
2649 // We are defaulting to laying out opaque SPIR-V types as 32-bit ints.
2650 Width = 32;
2651 Align = 32;
2652 }
2653 break;
2654 }
2655
2656 case Type::Atomic: {
2657 // Start with the base type information.
2658 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2659 Width = Info.Width;
2660 Align = Info.Align;
2661
2662 if (!Width) {
2663 // An otherwise zero-sized type should still generate an
2664 // atomic operation.
2665 Width = Target->getCharWidth();
2666 assert(Align);
2667 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2668 // If the size of the type doesn't exceed the platform's max
2669 // atomic promotion width, make the size and alignment more
2670 // favorable to atomic operations:
2671
2672 // Round the size up to a power of 2.
2673 Width = llvm::bit_ceil(Width);
2674
2675 // Set the alignment equal to the size.
2676 Align = static_cast<unsigned>(Width);
2677 }
2678 }
2679 break;
2680
2681 case Type::PredefinedSugar:
2682 return getTypeInfo(cast<PredefinedSugarType>(T)->desugar().getTypePtr());
2683
2684 case Type::Pipe:
2685 Width = Target->getPointerWidth(LangAS::opencl_global);
2686 Align = Target->getPointerAlign(LangAS::opencl_global);
2687 break;
2688 }
2689
2690 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2691 return TypeInfo(Width, Align, AlignRequirement);
2692}
2693
2695 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2696 if (I != MemoizedUnadjustedAlign.end())
2697 return I->second;
2698
2699 unsigned UnadjustedAlign;
2700 if (const auto *RT = T->getAsCanonical<RecordType>()) {
2701 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
2702 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2703 } else if (const auto *ObjCI = T->getAsCanonical<ObjCInterfaceType>()) {
2704 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2705 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2706 } else {
2707 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2708 }
2709
2710 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2711 return UnadjustedAlign;
2712}
2713
2715 unsigned SimdAlign = llvm::OpenMPIRBuilder::getOpenMPDefaultSimdAlign(
2716 getTargetInfo().getTriple(), Target->getTargetOpts().FeatureMap);
2717 return SimdAlign;
2718}
2719
2720/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2722 return CharUnits::fromQuantity(BitSize / getCharWidth());
2723}
2724
2725/// toBits - Convert a size in characters to a size in characters.
2726int64_t ASTContext::toBits(CharUnits CharSize) const {
2727 return CharSize.getQuantity() * getCharWidth();
2728}
2729
2730/// getTypeSizeInChars - Return the size of the specified type, in characters.
2731/// This method does not work on incomplete types.
2738
2739/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2740/// characters. This method does not work on incomplete types.
2747
2748/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2749/// type, in characters, before alignment adjustments. This method does
2750/// not work on incomplete types.
2757
2758/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2759/// type for the current target in bits. This can be different than the ABI
2760/// alignment in cases where it is beneficial for performance or backwards
2761/// compatibility preserving to overalign a data type. (Note: despite the name,
2762/// the preferred alignment is ABI-impacting, and not an optimization.)
2764 TypeInfo TI = getTypeInfo(T);
2765 unsigned ABIAlign = TI.Align;
2766
2767 T = T->getBaseElementTypeUnsafe();
2768
2769 // The preferred alignment of member pointers is that of a pointer.
2770 if (T->isMemberPointerType())
2771 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2772
2773 if (!Target->allowsLargerPreferedTypeAlignment())
2774 return ABIAlign;
2775
2776 if (const auto *RD = T->getAsRecordDecl()) {
2777 // When used as part of a typedef, or together with a 'packed' attribute,
2778 // the 'aligned' attribute can be used to decrease alignment. Note that the
2779 // 'packed' case is already taken into consideration when computing the
2780 // alignment, we only need to handle the typedef case here.
2782 RD->isInvalidDecl())
2783 return ABIAlign;
2784
2785 unsigned PreferredAlign = static_cast<unsigned>(
2786 toBits(getASTRecordLayout(RD).PreferredAlignment));
2787 assert(PreferredAlign >= ABIAlign &&
2788 "PreferredAlign should be at least as large as ABIAlign.");
2789 return PreferredAlign;
2790 }
2791
2792 // Double (and, for targets supporting AIX `power` alignment, long double) and
2793 // long long should be naturally aligned (despite requiring less alignment) if
2794 // possible.
2795 if (const auto *CT = T->getAs<ComplexType>())
2796 T = CT->getElementType().getTypePtr();
2797 if (const auto *ED = T->getAsEnumDecl())
2798 T = ED->getIntegerType().getTypePtr();
2799 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2800 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2801 T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2802 (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
2803 Target->defaultsToAIXPowerAlignment()))
2804 // Don't increase the alignment if an alignment attribute was specified on a
2805 // typedef declaration.
2806 if (!TI.isAlignRequired())
2807 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2808
2809 return ABIAlign;
2810}
2811
2812/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2813/// for __attribute__((aligned)) on this target, to be used if no alignment
2814/// value is specified.
2818
2819/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2820/// to a global variable of the specified type.
2822 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2823 return std::max(getPreferredTypeAlign(T),
2824 getMinGlobalAlignOfVar(TypeSize, VD));
2825}
2826
2827/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2828/// should be given to a global variable of the specified type.
2833
2835 const VarDecl *VD) const {
2836 // Make the default handling as that of a non-weak definition in the
2837 // current translation unit.
2838 bool HasNonWeakDef = !VD || (VD->hasDefinition() && !VD->isWeak());
2839 return getTargetInfo().getMinGlobalAlign(Size, HasNonWeakDef);
2840}
2841
2843 CharUnits Offset = CharUnits::Zero();
2844 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2845 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2846 Offset += Layout->getBaseClassOffset(Base);
2847 Layout = &getASTRecordLayout(Base);
2848 }
2849 return Offset;
2850}
2851
2853 const ValueDecl *MPD = MP.getMemberPointerDecl();
2856 bool DerivedMember = MP.isMemberPointerToDerivedMember();
2858 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
2859 const CXXRecordDecl *Base = RD;
2860 const CXXRecordDecl *Derived = Path[I];
2861 if (DerivedMember)
2862 std::swap(Base, Derived);
2864 RD = Path[I];
2865 }
2866 if (DerivedMember)
2868 return ThisAdjustment;
2869}
2870
2871/// DeepCollectObjCIvars -
2872/// This routine first collects all declared, but not synthesized, ivars in
2873/// super class and then collects all ivars, including those synthesized for
2874/// current class. This routine is used for implementation of current class
2875/// when all ivars, declared and synthesized are known.
2877 bool leafClass,
2879 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2880 DeepCollectObjCIvars(SuperClass, false, Ivars);
2881 if (!leafClass) {
2882 llvm::append_range(Ivars, OI->ivars());
2883 } else {
2884 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2885 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2886 Iv= Iv->getNextIvar())
2887 Ivars.push_back(Iv);
2888 }
2889}
2890
2891/// CollectInheritedProtocols - Collect all protocols in current class and
2892/// those inherited by it.
2895 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2896 // We can use protocol_iterator here instead of
2897 // all_referenced_protocol_iterator since we are walking all categories.
2898 for (auto *Proto : OI->all_referenced_protocols()) {
2899 CollectInheritedProtocols(Proto, Protocols);
2900 }
2901
2902 // Categories of this Interface.
2903 for (const auto *Cat : OI->visible_categories())
2904 CollectInheritedProtocols(Cat, Protocols);
2905
2906 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2907 while (SD) {
2908 CollectInheritedProtocols(SD, Protocols);
2909 SD = SD->getSuperClass();
2910 }
2911 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2912 for (auto *Proto : OC->protocols()) {
2913 CollectInheritedProtocols(Proto, Protocols);
2914 }
2915 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2916 // Insert the protocol.
2917 if (!Protocols.insert(
2918 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2919 return;
2920
2921 for (auto *Proto : OP->protocols())
2922 CollectInheritedProtocols(Proto, Protocols);
2923 }
2924}
2925
2927 const RecordDecl *RD,
2928 bool CheckIfTriviallyCopyable) {
2929 assert(RD->isUnion() && "Must be union type");
2930 CharUnits UnionSize =
2931 Context.getTypeSizeInChars(Context.getCanonicalTagType(RD));
2932
2933 for (const auto *Field : RD->fields()) {
2934 if (!Context.hasUniqueObjectRepresentations(Field->getType(),
2935 CheckIfTriviallyCopyable))
2936 return false;
2937 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2938 if (FieldSize != UnionSize)
2939 return false;
2940 }
2941 return !RD->field_empty();
2942}
2943
2944static int64_t getSubobjectOffset(const FieldDecl *Field,
2945 const ASTContext &Context,
2946 const clang::ASTRecordLayout & /*Layout*/) {
2947 return Context.getFieldOffset(Field);
2948}
2949
2950static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
2951 const ASTContext &Context,
2952 const clang::ASTRecordLayout &Layout) {
2953 return Context.toBits(Layout.getBaseClassOffset(RD));
2954}
2955
2956static std::optional<int64_t>
2958 const RecordDecl *RD,
2959 bool CheckIfTriviallyCopyable);
2960
2961static std::optional<int64_t>
2962getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context,
2963 bool CheckIfTriviallyCopyable) {
2964 if (const auto *RD = Field->getType()->getAsRecordDecl();
2965 RD && !RD->isUnion())
2966 return structHasUniqueObjectRepresentations(Context, RD,
2967 CheckIfTriviallyCopyable);
2968
2969 // A _BitInt type may not be unique if it has padding bits
2970 // but if it is a bitfield the padding bits are not used.
2971 bool IsBitIntType = Field->getType()->isBitIntType();
2972 if (!Field->getType()->isReferenceType() && !IsBitIntType &&
2973 !Context.hasUniqueObjectRepresentations(Field->getType(),
2974 CheckIfTriviallyCopyable))
2975 return std::nullopt;
2976
2977 int64_t FieldSizeInBits =
2978 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2979 if (Field->isBitField()) {
2980 // If we have explicit padding bits, they don't contribute bits
2981 // to the actual object representation, so return 0.
2982 if (Field->isUnnamedBitField())
2983 return 0;
2984
2985 int64_t BitfieldSize = Field->getBitWidthValue();
2986 if (IsBitIntType) {
2987 if ((unsigned)BitfieldSize >
2988 cast<BitIntType>(Field->getType())->getNumBits())
2989 return std::nullopt;
2990 } else if (BitfieldSize > FieldSizeInBits) {
2991 return std::nullopt;
2992 }
2993 FieldSizeInBits = BitfieldSize;
2994 } else if (IsBitIntType && !Context.hasUniqueObjectRepresentations(
2995 Field->getType(), CheckIfTriviallyCopyable)) {
2996 return std::nullopt;
2997 }
2998 return FieldSizeInBits;
2999}
3000
3001static std::optional<int64_t>
3003 bool CheckIfTriviallyCopyable) {
3004 return structHasUniqueObjectRepresentations(Context, RD,
3005 CheckIfTriviallyCopyable);
3006}
3007
3008template <typename RangeT>
3010 const RangeT &Subobjects, int64_t CurOffsetInBits,
3011 const ASTContext &Context, const clang::ASTRecordLayout &Layout,
3012 bool CheckIfTriviallyCopyable) {
3013 for (const auto *Subobject : Subobjects) {
3014 std::optional<int64_t> SizeInBits =
3015 getSubobjectSizeInBits(Subobject, Context, CheckIfTriviallyCopyable);
3016 if (!SizeInBits)
3017 return std::nullopt;
3018 if (*SizeInBits != 0) {
3019 int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
3020 if (Offset != CurOffsetInBits)
3021 return std::nullopt;
3022 CurOffsetInBits += *SizeInBits;
3023 }
3024 }
3025 return CurOffsetInBits;
3026}
3027
3028static std::optional<int64_t>
3030 const RecordDecl *RD,
3031 bool CheckIfTriviallyCopyable) {
3032 assert(!RD->isUnion() && "Must be struct/class type");
3033 const auto &Layout = Context.getASTRecordLayout(RD);
3034
3035 int64_t CurOffsetInBits = 0;
3036 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
3037 if (ClassDecl->isDynamicClass())
3038 return std::nullopt;
3039
3041 for (const auto &Base : ClassDecl->bases()) {
3042 // Empty types can be inherited from, and non-empty types can potentially
3043 // have tail padding, so just make sure there isn't an error.
3044 Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
3045 }
3046
3047 llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3048 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3049 });
3050
3051 std::optional<int64_t> OffsetAfterBases =
3053 Bases, CurOffsetInBits, Context, Layout, CheckIfTriviallyCopyable);
3054 if (!OffsetAfterBases)
3055 return std::nullopt;
3056 CurOffsetInBits = *OffsetAfterBases;
3057 }
3058
3059 std::optional<int64_t> OffsetAfterFields =
3061 RD->fields(), CurOffsetInBits, Context, Layout,
3062 CheckIfTriviallyCopyable);
3063 if (!OffsetAfterFields)
3064 return std::nullopt;
3065 CurOffsetInBits = *OffsetAfterFields;
3066
3067 return CurOffsetInBits;
3068}
3069
3071 QualType Ty, bool CheckIfTriviallyCopyable) const {
3072 // C++17 [meta.unary.prop]:
3073 // The predicate condition for a template specialization
3074 // has_unique_object_representations<T> shall be satisfied if and only if:
3075 // (9.1) - T is trivially copyable, and
3076 // (9.2) - any two objects of type T with the same value have the same
3077 // object representation, where:
3078 // - two objects of array or non-union class type are considered to have
3079 // the same value if their respective sequences of direct subobjects
3080 // have the same values, and
3081 // - two objects of union type are considered to have the same value if
3082 // they have the same active member and the corresponding members have
3083 // the same value.
3084 // The set of scalar types for which this condition holds is
3085 // implementation-defined. [ Note: If a type has padding bits, the condition
3086 // does not hold; otherwise, the condition holds true for unsigned integral
3087 // types. -- end note ]
3088 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
3089
3090 // Arrays are unique only if their element type is unique.
3091 if (Ty->isArrayType())
3093 CheckIfTriviallyCopyable);
3094
3095 assert((Ty->isVoidType() || !Ty->isIncompleteType()) &&
3096 "hasUniqueObjectRepresentations should not be called with an "
3097 "incomplete type");
3098
3099 // _Atomic(T) shares T's object representation unless its size was rounded
3100 // up to a power of two, in which case the extra bytes are padding. Atomic
3101 // types are never trivially copyable, so (9.1) is judged on the value type.
3102 if (const auto *AT = Ty->getAs<AtomicType>())
3103 return getTypeSize(AT) == getTypeSize(AT->getValueType()) &&
3104 hasUniqueObjectRepresentations(AT->getValueType(),
3105 CheckIfTriviallyCopyable);
3106
3107 // (9.1) - T is trivially copyable...
3108 if (CheckIfTriviallyCopyable && !Ty.isTriviallyCopyableType(*this))
3109 return false;
3110
3111 // All integrals and enums are unique.
3112 if (Ty->isIntegralOrEnumerationType()) {
3113 // Address discriminated integer types are not unique.
3115 return false;
3116 // Except _BitInt types that have padding bits.
3117 if (const auto *BIT = Ty->getAs<BitIntType>())
3118 return getTypeSize(BIT) == BIT->getNumBits();
3119
3120 return true;
3121 }
3122
3123 // All other pointers are unique.
3124 if (Ty->isPointerType())
3126
3127 if (const auto *MPT = Ty->getAs<MemberPointerType>())
3128 return !ABI->getMemberPointerInfo(MPT).HasPadding;
3129
3130 if (const auto *Record = Ty->getAsRecordDecl()) {
3131 if (Record->isInvalidDecl())
3132 return false;
3133
3134 if (Record->isUnion())
3136 CheckIfTriviallyCopyable);
3137
3138 std::optional<int64_t> StructSize = structHasUniqueObjectRepresentations(
3139 *this, Record, CheckIfTriviallyCopyable);
3140
3141 return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
3142 }
3143
3144 // FIXME: More cases to handle here (list by rsmith):
3145 // vectors (careful about, eg, vector of 3 foo)
3146 // _Complex int and friends
3147 // Obj-C block pointers
3148 // Obj-C object pointers
3149 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
3150 // clk_event_t, queue_t, reserve_id_t)
3151 // There're also Obj-C class types and the Obj-C selector type, but I think it
3152 // makes sense for those to return false here.
3153
3154 return false;
3155}
3156
3158 unsigned count = 0;
3159 // Count ivars declared in class extension.
3160 for (const auto *Ext : OI->known_extensions())
3161 count += Ext->ivar_size();
3162
3163 // Count ivar defined in this class's implementation. This
3164 // includes synthesized ivars.
3165 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
3166 count += ImplDecl->ivar_size();
3167
3168 return count;
3169}
3170
3172 if (!E)
3173 return false;
3174
3175 // nullptr_t is always treated as null.
3176 if (E->getType()->isNullPtrType()) return true;
3177
3178 if (E->getType()->isAnyPointerType() &&
3181 return true;
3182
3183 // Unfortunately, __null has type 'int'.
3184 if (isa<GNUNullExpr>(E)) return true;
3185
3186 return false;
3187}
3188
3189/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
3190/// exists.
3192 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3193 I = ObjCImpls.find(D);
3194 if (I != ObjCImpls.end())
3195 return cast<ObjCImplementationDecl>(I->second);
3196 return nullptr;
3197}
3198
3199/// Get the implementation of ObjCCategoryDecl, or nullptr if none
3200/// exists.
3202 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
3203 I = ObjCImpls.find(D);
3204 if (I != ObjCImpls.end())
3205 return cast<ObjCCategoryImplDecl>(I->second);
3206 return nullptr;
3207}
3208
3209/// Set the implementation of ObjCInterfaceDecl.
3211 ObjCImplementationDecl *ImplD) {
3212 assert(IFaceD && ImplD && "Passed null params");
3213 ObjCImpls[IFaceD] = ImplD;
3214}
3215
3216/// Set the implementation of ObjCCategoryDecl.
3218 ObjCCategoryImplDecl *ImplD) {
3219 assert(CatD && ImplD && "Passed null params");
3220 ObjCImpls[CatD] = ImplD;
3221}
3222
3223const ObjCMethodDecl *
3225 return ObjCMethodRedecls.lookup(MD);
3226}
3227
3229 const ObjCMethodDecl *Redecl) {
3230 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
3231 ObjCMethodRedecls[MD] = Redecl;
3232}
3233
3235 const NamedDecl *ND) const {
3236 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
3237 return ID;
3238 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
3239 return CD->getClassInterface();
3240 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
3241 return IMD->getClassInterface();
3242
3243 return nullptr;
3244}
3245
3246/// Get the copy initialization expression of VarDecl, or nullptr if
3247/// none exists.
3249 assert(VD && "Passed null params");
3250 assert(VD->hasAttr<BlocksAttr>() &&
3251 "getBlockVarCopyInits - not __block var");
3252 auto I = BlockVarCopyInits.find(VD);
3253 if (I != BlockVarCopyInits.end())
3254 return I->second;
3255 return {nullptr, false};
3256}
3257
3258/// Set the copy initialization expression of a block var decl.
3260 bool CanThrow) {
3261 assert(VD && CopyExpr && "Passed null params");
3262 assert(VD->hasAttr<BlocksAttr>() &&
3263 "setBlockVarCopyInits - not __block var");
3264 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
3265}
3266
3268 unsigned DataSize) const {
3269 if (!DataSize)
3271 else
3272 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
3273 "incorrect data size provided to CreateTypeSourceInfo!");
3274
3275 auto *TInfo =
3276 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
3277 new (TInfo) TypeSourceInfo(T, DataSize);
3278 return TInfo;
3279}
3280
3282 SourceLocation L) const {
3284 TSI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
3285 return TSI;
3286}
3287
3288const ASTRecordLayout &
3290 return getObjCLayout(D);
3291}
3292
3295 bool &AnyNonCanonArgs) {
3296 SmallVector<TemplateArgument, 16> CanonArgs(Args);
3297 AnyNonCanonArgs |= C.canonicalizeTemplateArguments(CanonArgs);
3298 return CanonArgs;
3299}
3300
3303 bool AnyNonCanonArgs = false;
3304 for (auto &Arg : Args) {
3305 TemplateArgument OrigArg = Arg;
3307 AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
3308 }
3309 return AnyNonCanonArgs;
3310}
3311
3312//===----------------------------------------------------------------------===//
3313// Type creation/memoization methods
3314//===----------------------------------------------------------------------===//
3315
3317ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
3318 unsigned fastQuals = quals.getFastQualifiers();
3319 quals.removeFastQualifiers();
3320
3321 // Check if we've already instantiated this type.
3322 llvm::FoldingSetNodeID ID;
3323 ExtQuals::Profile(ID, baseType, quals);
3324 llvm::FoldingSetInsertToken Token;
3325 if (ExtQuals *eq = ExtQualNodes.lookup(ID, Token)) {
3326 assert(eq->getQualifiers() == quals);
3327 return QualType(eq, fastQuals);
3328 }
3329
3330 // If the base type is not canonical, make the appropriate canonical type.
3331 QualType canon;
3332 if (!baseType->isCanonicalUnqualified()) {
3333 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
3334 canonSplit.Quals.addConsistentQualifiers(quals);
3335 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
3336
3337 // Re-find the insert position.
3338 (void)ExtQualNodes.lookup(ID, Token);
3339 }
3340
3341 auto *eq = new (*this, alignof(ExtQuals)) ExtQuals(baseType, canon, quals);
3342 ExtQualNodes.insert(eq, Token);
3343 return QualType(eq, fastQuals);
3344}
3345
3347 LangAS AddressSpace) const {
3348 QualType CanT = getCanonicalType(T);
3349 if (CanT.getAddressSpace() == AddressSpace)
3350 return T;
3351
3352 // If we are composing extended qualifiers together, merge together
3353 // into one ExtQuals node.
3354 QualifierCollector Quals;
3355 const Type *TypeNode = Quals.strip(T);
3356
3357 // If this type already has an address space specified, it cannot get
3358 // another one.
3359 assert(!Quals.hasAddressSpace() &&
3360 "Type cannot be in multiple addr spaces!");
3361 Quals.addAddressSpace(AddressSpace);
3362
3363 return getExtQualType(TypeNode, Quals);
3364}
3365
3367 // If the type is not qualified with an address space, just return it
3368 // immediately.
3369 if (!T.hasAddressSpace())
3370 return T;
3371
3372 QualifierCollector Quals;
3373 const Type *TypeNode;
3374 // For arrays, strip the qualifier off the element type, then reconstruct the
3375 // array type
3376 if (T.getTypePtr()->isArrayType()) {
3377 T = getUnqualifiedArrayType(T, Quals);
3378 TypeNode = T.getTypePtr();
3379 } else {
3380 // If we are composing extended qualifiers together, merge together
3381 // into one ExtQuals node.
3382 while (T.hasAddressSpace()) {
3383 TypeNode = Quals.strip(T);
3384
3385 // If the type no longer has an address space after stripping qualifiers,
3386 // jump out.
3387 if (!QualType(TypeNode, 0).hasAddressSpace())
3388 break;
3389
3390 // There might be sugar in the way. Strip it and try again.
3391 T = T.getSingleStepDesugaredType(*this);
3392 }
3393 }
3394
3395 Quals.removeAddressSpace();
3396
3397 // Removal of the address space can mean there are no longer any
3398 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
3399 // or required.
3400 if (Quals.hasNonFastQualifiers())
3401 return getExtQualType(TypeNode, Quals);
3402 else
3403 return QualType(TypeNode, Quals.getFastQualifiers());
3404}
3405
3406uint16_t
3408 bool IsVTTEntry) {
3409 assert(RD->isPolymorphic() &&
3410 "Attempted to get vtable pointer discriminator on a monomorphic type");
3411
3412 std::unique_ptr<MangleContext> MC(createMangleContext());
3413 SmallString<256> Str;
3414 llvm::raw_svector_ostream Out(Str);
3415 MC->mangleCXXVTable(RD, Out);
3416 if (IsVTTEntry)
3418 return llvm::getPointerAuthStableSipHash(Str);
3419}
3420
3421/// Encode a function type for use in the discriminator of a function pointer
3422/// type. We can't use the itanium scheme for this since C has quite permissive
3423/// rules for type compatibility that we need to be compatible with.
3424///
3425/// Formally, this function associates every function pointer type T with an
3426/// encoded string E(T). Let the equivalence relation T1 ~ T2 be defined as
3427/// E(T1) == E(T2). E(T) is part of the ABI of values of type T. C type
3428/// compatibility requires equivalent treatment under the ABI, so
3429/// CCompatible(T1, T2) must imply E(T1) == E(T2), that is, CCompatible must be
3430/// a subset of ~. Crucially, however, it must be a proper subset because
3431/// CCompatible is not an equivalence relation: for example, int[] is compatible
3432/// with both int[1] and int[2], but the latter are not compatible with each
3433/// other. Therefore this encoding function must be careful to only distinguish
3434/// types if there is no third type with which they are both required to be
3435/// compatible.
3437 raw_ostream &OS, QualType QT) {
3438 // FIXME: Consider address space qualifiers.
3439 const Type *T = QT.getCanonicalType().getTypePtr();
3440
3441 // FIXME: Consider using the C++ type mangling when we encounter a construct
3442 // that is incompatible with C.
3443
3444 switch (T->getTypeClass()) {
3445 case Type::Atomic:
3447 Ctx, OS, cast<AtomicType>(T)->getValueType());
3448
3449 case Type::LValueReference:
3450 OS << "R";
3453 return;
3454 case Type::RValueReference:
3455 OS << "O";
3458 return;
3459
3460 case Type::Pointer:
3461 // C11 6.7.6.1p2:
3462 // For two pointer types to be compatible, both shall be identically
3463 // qualified and both shall be pointers to compatible types.
3464 // FIXME: we should also consider pointee types.
3465 OS << "P";
3466 return;
3467
3468 case Type::ObjCObjectPointer:
3469 case Type::BlockPointer:
3470 OS << "P";
3471 return;
3472
3473 case Type::Complex:
3474 OS << "C";
3476 Ctx, OS, cast<ComplexType>(T)->getElementType());
3477
3478 case Type::VariableArray:
3479 case Type::ConstantArray:
3480 case Type::IncompleteArray:
3481 case Type::ArrayParameter:
3482 // C11 6.7.6.2p6:
3483 // For two array types to be compatible, both shall have compatible
3484 // element types, and if both size specifiers are present, and are integer
3485 // constant expressions, then both size specifiers shall have the same
3486 // constant value [...]
3487 //
3488 // So since ElemType[N] has to be compatible ElemType[], we can't encode the
3489 // width of the array.
3490 OS << "A";
3492 Ctx, OS, cast<ArrayType>(T)->getElementType());
3493
3494 case Type::ObjCInterface:
3495 case Type::ObjCObject:
3496 OS << "<objc_object>";
3497 return;
3498
3499 case Type::Enum: {
3500 // C11 6.7.2.2p4:
3501 // Each enumerated type shall be compatible with char, a signed integer
3502 // type, or an unsigned integer type.
3503 //
3504 // So we have to treat enum types as integers.
3505 QualType UnderlyingType = T->castAsEnumDecl()->getIntegerType();
3507 Ctx, OS, UnderlyingType.isNull() ? Ctx.IntTy : UnderlyingType);
3508 }
3509
3510 case Type::FunctionNoProto:
3511 case Type::FunctionProto: {
3512 // C11 6.7.6.3p15:
3513 // For two function types to be compatible, both shall specify compatible
3514 // return types. Moreover, the parameter type lists, if both are present,
3515 // shall agree in the number of parameters and in the use of the ellipsis
3516 // terminator; corresponding parameters shall have compatible types.
3517 //
3518 // That paragraph goes on to describe how unprototyped functions are to be
3519 // handled, which we ignore here. Unprototyped function pointers are hashed
3520 // as though they were prototyped nullary functions since thats probably
3521 // what the user meant. This behavior is non-conforming.
3522 // FIXME: If we add a "custom discriminator" function type attribute we
3523 // should encode functions as their discriminators.
3524 OS << "F";
3525 const auto *FuncType = cast<FunctionType>(T);
3526 encodeTypeForFunctionPointerAuth(Ctx, OS, FuncType->getReturnType());
3527 if (const auto *FPT = dyn_cast<FunctionProtoType>(FuncType)) {
3528 for (QualType Param : FPT->param_types()) {
3529 Param = Ctx.getSignatureParameterType(Param);
3530 encodeTypeForFunctionPointerAuth(Ctx, OS, Param);
3531 }
3532 if (FPT->isVariadic())
3533 OS << "z";
3534 }
3535 OS << "E";
3536 return;
3537 }
3538
3539 case Type::MemberPointer: {
3540 OS << "M";
3541 const auto *MPT = T->castAs<MemberPointerType>();
3543 Ctx, OS, QualType(MPT->getQualifier().getAsType(), 0));
3544 encodeTypeForFunctionPointerAuth(Ctx, OS, MPT->getPointeeType());
3545 return;
3546 }
3547 case Type::ExtVector:
3548 case Type::Vector:
3549 OS << "Dv" << Ctx.getTypeSizeInChars(T).getQuantity();
3550 break;
3551
3552 // Don't bother discriminating based on these types.
3553 case Type::Pipe:
3554 case Type::BitInt:
3555 case Type::ConstantMatrix:
3556 OS << "?";
3557 return;
3558
3559 case Type::Builtin: {
3560 const auto *BTy = T->castAs<BuiltinType>();
3561 switch (BTy->getKind()) {
3562#define SIGNED_TYPE(Id, SingletonId) \
3563 case BuiltinType::Id: \
3564 OS << "i"; \
3565 return;
3566#define UNSIGNED_TYPE(Id, SingletonId) \
3567 case BuiltinType::Id: \
3568 OS << "i"; \
3569 return;
3570#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
3571#define BUILTIN_TYPE(Id, SingletonId)
3572#include "clang/AST/BuiltinTypes.def"
3573 llvm_unreachable("placeholder types should not appear here.");
3574
3575 case BuiltinType::Half:
3576 OS << "Dh";
3577 return;
3578 case BuiltinType::Float:
3579 OS << "f";
3580 return;
3581 case BuiltinType::Double:
3582 OS << "d";
3583 return;
3584 case BuiltinType::LongDouble:
3585 OS << "e";
3586 return;
3587 case BuiltinType::Float16:
3588 OS << "DF16_";
3589 return;
3590 case BuiltinType::Float128:
3591 OS << "g";
3592 return;
3593
3594 case BuiltinType::Void:
3595 OS << "v";
3596 return;
3597
3598 case BuiltinType::ObjCId:
3599 case BuiltinType::ObjCClass:
3600 case BuiltinType::ObjCSel:
3601 case BuiltinType::NullPtr:
3602 OS << "P";
3603 return;
3604
3605 // Don't bother discriminating based on OpenCL types.
3606 case BuiltinType::OCLSampler:
3607 case BuiltinType::OCLEvent:
3608 case BuiltinType::OCLClkEvent:
3609 case BuiltinType::OCLQueue:
3610 case BuiltinType::OCLReserveID:
3611 case BuiltinType::BFloat16:
3612 case BuiltinType::VectorQuad:
3613 case BuiltinType::VectorPair:
3614 case BuiltinType::DMR1024:
3615 case BuiltinType::DMR2048:
3616 case BuiltinType::MetaInfo:
3617 OS << "?";
3618 return;
3619
3620 // Don't bother discriminating based on these seldom-used types.
3621 case BuiltinType::Ibm128:
3622 return;
3623#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3624 case BuiltinType::Id: \
3625 return;
3626#include "clang/Basic/OpenCLImageTypes.def"
3627#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3628 case BuiltinType::Id: \
3629 return;
3630#include "clang/Basic/OpenCLExtensionTypes.def"
3631#define SVE_TYPE(Name, Id, SingletonId) \
3632 case BuiltinType::Id: \
3633 return;
3634#include "clang/Basic/AArch64ACLETypes.def"
3635#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3636 case BuiltinType::Id: \
3637 return;
3638#include "clang/Basic/HLSLIntangibleTypes.def"
3639#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
3640 case BuiltinType::Id: \
3641 return;
3642#include "clang/Basic/HLSLPackedTypes.def"
3643 case BuiltinType::Dependent:
3644 llvm_unreachable("should never get here");
3645#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
3646#include "clang/Basic/AMDGPUTypes.def"
3647 case BuiltinType::WasmExternRef:
3648#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3649#include "clang/Basic/RISCVVTypes.def"
3650#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
3651#include "clang/Basic/SPIRVTypes.def"
3652 llvm_unreachable("not yet implemented");
3653 }
3654 llvm_unreachable("should never get here");
3655 }
3656 case Type::Record: {
3657 const RecordDecl *RD = T->castAsCanonical<RecordType>()->getDecl();
3658 const IdentifierInfo *II = RD->getIdentifier();
3659
3660 // In C++, an immediate typedef of an anonymous struct or union
3661 // is considered to name it for ODR purposes, but C's specification
3662 // of type compatibility does not have a similar rule. Using the typedef
3663 // name in function type discriminators anyway, as we do here,
3664 // therefore technically violates the C standard: two function pointer
3665 // types defined in terms of two typedef'd anonymous structs with
3666 // different names are formally still compatible, but we are assigning
3667 // them different discriminators and therefore incompatible ABIs.
3668 //
3669 // This is a relatively minor violation that significantly improves
3670 // discrimination in some cases and has not caused problems in
3671 // practice. Regardless, it is now part of the ABI in places where
3672 // function type discrimination is used, and it can no longer be
3673 // changed except on new platforms.
3674
3675 if (!II)
3676 if (const TypedefNameDecl *Typedef = RD->getTypedefNameForAnonDecl())
3677 II = Typedef->getDeclName().getAsIdentifierInfo();
3678
3679 if (!II) {
3680 OS << "<anonymous_record>";
3681 return;
3682 }
3683 OS << II->getLength() << II->getName();
3684 return;
3685 }
3686 case Type::HLSLAttributedResource:
3687 case Type::HLSLInlineSpirv:
3688 llvm_unreachable("should never get here");
3689 break;
3690 case Type::OverflowBehavior:
3691 llvm_unreachable("should never get here");
3692 break;
3693 case Type::DeducedTemplateSpecialization:
3694 case Type::Auto:
3695#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3696#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3697#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3698#define ABSTRACT_TYPE(Class, Base)
3699#define TYPE(Class, Base)
3700#include "clang/AST/TypeNodes.inc"
3701 llvm_unreachable("unexpected non-canonical or dependent type!");
3702 return;
3703 }
3704}
3705
3707 assert(!T->isDependentType() &&
3708 "cannot compute type discriminator of a dependent type");
3709 SmallString<256> Str;
3710 llvm::raw_svector_ostream Out(Str);
3711
3712 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
3713 T = T->getPointeeType();
3714
3715 if (T->isFunctionType()) {
3717 } else {
3718 T = T.getUnqualifiedType();
3719 // Calls to member function pointers don't need to worry about
3720 // language interop or the laxness of the C type compatibility rules.
3721 // We just mangle the member pointer type directly, which is
3722 // implicitly much stricter about type matching. However, we do
3723 // strip any top-level exception specification before this mangling.
3724 // C++23 requires calls to work when the function type is convertible
3725 // to the pointer type by a function pointer conversion, which can
3726 // change the exception specification. This does not technically
3727 // require the exception specification to not affect representation,
3728 // because the function pointer conversion is still always a direct
3729 // value conversion and therefore an opportunity to resign the
3730 // pointer. (This is in contrast to e.g. qualification conversions,
3731 // which can be applied in nested pointer positions, effectively
3732 // requiring qualified and unqualified representations to match.)
3733 // However, it is pragmatic to ignore exception specifications
3734 // because it allows a certain amount of `noexcept` mismatching
3735 // to not become a visible ODR problem. This also leaves some
3736 // room for the committee to add laxness to function pointer
3737 // conversions in future standards.
3738 if (auto *MPT = T->getAs<MemberPointerType>())
3739 if (MPT->isMemberFunctionPointer()) {
3740 QualType PointeeType = MPT->getPointeeType();
3741 if (PointeeType->castAs<FunctionProtoType>()->getExceptionSpecType() !=
3742 EST_None) {
3744 T = getMemberPointerType(FT, MPT->getQualifier(),
3745 MPT->getMostRecentCXXRecordDecl());
3746 }
3747 }
3748 std::unique_ptr<MangleContext> MC(createMangleContext());
3749 MC->mangleCanonicalTypeName(T, Out);
3750 }
3751
3752 return llvm::getPointerAuthStableSipHash(Str);
3753}
3754
3756 Qualifiers::GC GCAttr) const {
3757 QualType CanT = getCanonicalType(T);
3758 if (CanT.getObjCGCAttr() == GCAttr)
3759 return T;
3760
3761 if (const auto *ptr = T->getAs<PointerType>()) {
3762 QualType Pointee = ptr->getPointeeType();
3763 if (Pointee->isAnyPointerType()) {
3764 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
3765 return getPointerType(ResultType);
3766 }
3767 }
3768
3769 // If we are composing extended qualifiers together, merge together
3770 // into one ExtQuals node.
3771 QualifierCollector Quals;
3772 const Type *TypeNode = Quals.strip(T);
3773
3774 // If this type already has an ObjCGC specified, it cannot get
3775 // another one.
3776 assert(!Quals.hasObjCGCAttr() &&
3777 "Type cannot have multiple ObjCGCs!");
3778 Quals.addObjCGCAttr(GCAttr);
3779
3780 return getExtQualType(TypeNode, Quals);
3781}
3782
3784 if (const PointerType *Ptr = T->getAs<PointerType>()) {
3785 QualType Pointee = Ptr->getPointeeType();
3786 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
3787 return getPointerType(removeAddrSpaceQualType(Pointee));
3788 }
3789 }
3790 return T;
3791}
3792
3794 QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull,
3795 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3796 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3797 assert(CountExpr && "use getIncompleteCountAttributedType for a null count");
3798
3799 // Complete (non-late-parsed) path: the count expression is known up front.
3800 // This deliberately preserves the pre-existing uniquing behavior -- the
3801 // FoldingSet lookup/insert below is unchanged by late-parse support. Only
3802 // getIncompleteCountAttributedType (count filled in later) opts out of
3803 // uniquing.
3804 llvm::FoldingSetNodeID ID;
3805 CountAttributedType::Profile(ID, WrappedTy, CountExpr, CountInBytes, OrNull);
3806
3807 llvm::FoldingSetInsertToken Token;
3808 CountAttributedType *CATy = CountAttributedTypes.lookup(ID, Token);
3809 if (CATy)
3810 return QualType(CATy, 0);
3811
3812 QualType CanonTy = getCanonicalType(WrappedTy);
3813 CATy = CountAttributedType::Create(*this, WrappedTy, CanonTy, CountExpr,
3814 CountInBytes, OrNull, DependentDecls);
3815 Types.push_back(CATy);
3816 CountAttributedTypes.insert(CATy, Token);
3817
3818 return QualType(CATy, 0);
3819}
3820
3822 QualType WrappedTy, bool CountInBytes, bool OrNull) const {
3823 assert(WrappedTy->isPointerType() || WrappedTy->isArrayType());
3824
3825 // Deliberately opts out of the uniquing that `getCountAttributedType` does:
3826 // `CountAttributedType::Profile` keys on the `CountExpr` pointer, which is
3827 // null here, so every incomplete node would profile identically as
3828 // `(WrappedTy, flags, nullptr)` and two fields with different counts would
3829 // collide. The node stays un-uniqued even after completion; see
3830 // `completeCountAttributedType`.
3831 //
3832 // Also deliberately not in `Types` yet. An incomplete node can be abandoned
3833 // without ever being completed (a nested counted_by, or an argument that
3834 // fails to parse), and a null-count node must not be reachable by anything
3835 // that scans `Types`. `completeCountAttributedType` registers it once the
3836 // count is in place.
3837 return CountAttributedType::Create(
3838 *this, WrappedTy, getCanonicalType(WrappedTy),
3839 /*CountExpr=*/nullptr, CountInBytes, OrNull,
3840 /*CoupledDecls=*/{});
3841}
3842
3844 CountAttributedType *CATy, Expr *CountExpr,
3845 ArrayRef<TypeCoupledDeclRefInfo> DependentDecls) const {
3846 CATy->complete(*this, CountExpr, DependentDecls);
3847 // Safe for `Types` scanners now that the count is in place; see
3848 // `getIncompleteCountAttributedType` for why it was held back.
3849 //
3850 // It stays out of the `CountAttributedTypes` FoldingSet permanently, unlike
3851 // an eagerly built node: this pointer is already embedded in the enclosing
3852 // types and handed out, so an equal node that happens to exist cannot be
3853 // merged into. The only cost is that a completed node is never
3854 // pointer-shared with an equal eager one, which does not affect semantic
3855 // type equality -- `hasSameType` compares canonical types, and this sugar's
3856 // canonical type is the wrapped type's.
3857 Types.push_back(CATy);
3858}
3859
3861 QualType WrappedTy, LateParsedTypeAttribute *LateParsedAttr) const {
3862 QualType CanonTy = getCanonicalType(WrappedTy);
3863
3864 auto *LPATy = new (*this, alignof(LateParsedAttrType))
3865 LateParsedAttrType(WrappedTy, CanonTy, LateParsedAttr);
3866
3867 Types.push_back(LPATy);
3868 return QualType(LPATy, 0);
3869}
3870
3873 llvm::function_ref<QualType(QualType)> Adjust) const {
3874 switch (Orig->getTypeClass()) {
3875 case Type::Attributed: {
3876 const auto *AT = cast<AttributedType>(Orig);
3877 return getAttributedType(AT->getAttrKind(),
3878 adjustType(AT->getModifiedType(), Adjust),
3879 adjustType(AT->getEquivalentType(), Adjust),
3880 AT->getAttr());
3881 }
3882
3883 case Type::BTFTagAttributed: {
3884 const auto *BTFT = dyn_cast<BTFTagAttributedType>(Orig);
3885 return getBTFTagAttributedType(BTFT->getAttr(),
3886 adjustType(BTFT->getWrappedType(), Adjust));
3887 }
3888
3889 case Type::OverflowBehavior: {
3890 const auto *OB = dyn_cast<OverflowBehaviorType>(Orig);
3891 return getOverflowBehaviorType(OB->getBehaviorKind(),
3892 adjustType(OB->getUnderlyingType(), Adjust));
3893 }
3894
3895 case Type::Paren:
3896 return getParenType(
3897 adjustType(cast<ParenType>(Orig)->getInnerType(), Adjust));
3898
3899 case Type::Adjusted: {
3900 const auto *AT = cast<AdjustedType>(Orig);
3901 return getAdjustedType(AT->getOriginalType(),
3902 adjustType(AT->getAdjustedType(), Adjust));
3903 }
3904
3905 case Type::MacroQualified: {
3906 const auto *MQT = cast<MacroQualifiedType>(Orig);
3907 return getMacroQualifiedType(adjustType(MQT->getUnderlyingType(), Adjust),
3908 MQT->getMacroIdentifier());
3909 }
3910
3911 default:
3912 return Adjust(Orig);
3913 }
3914}
3915
3917 FunctionType::ExtInfo Info) {
3918 if (T->getExtInfo() == Info)
3919 return T;
3920
3922 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
3923 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
3924 } else {
3925 const auto *FPT = cast<FunctionProtoType>(T);
3926 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
3927 EPI.ExtInfo = Info;
3928 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
3929 }
3930
3931 return cast<FunctionType>(Result.getTypePtr());
3932}
3933
3935 QualType ResultType) {
3936 return adjustType(FunctionType, [&](QualType Orig) {
3937 if (const auto *FNPT = Orig->getAs<FunctionNoProtoType>())
3938 return getFunctionNoProtoType(ResultType, FNPT->getExtInfo());
3939
3940 const auto *FPT = Orig->castAs<FunctionProtoType>();
3941 return getFunctionType(ResultType, FPT->getParamTypes(),
3942 FPT->getExtProtoInfo());
3943 });
3944}
3945
3947 QualType ResultType) {
3948 FD = FD->getMostRecentDecl();
3949 while (true) {
3950 FD->setType(adjustFunctionResultType(FD->getType(), ResultType));
3951 if (FunctionDecl *Next = FD->getPreviousDecl())
3952 FD = Next;
3953 else
3954 break;
3955 }
3957 L->DeducedReturnType(FD, ResultType);
3958}
3959
3960/// Get a function type and produce the equivalent function type with the
3961/// specified exception specification. Type sugar that can be present on a
3962/// declaration of a function with an exception specification is permitted
3963/// and preserved. Other type sugar (for instance, typedefs) is not.
3965 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
3966 return adjustType(Orig, [&](QualType Ty) {
3967 const auto *Proto = Ty->castAs<FunctionProtoType>();
3968 return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(),
3969 Proto->getExtProtoInfo().withExceptionSpec(ESI));
3970 });
3971}
3972
3980
3982 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3983 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3984 SmallVector<QualType, 16> Args(Proto->param_types().size());
3985 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3986 Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
3987 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3988 }
3989
3990 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3991 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3992 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3993 }
3994
3995 return T;
3996}
3997
4003
4005 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
4006 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4007 EPI.ExtParameterInfos = nullptr;
4008 return getFunctionType(Proto->getReturnType(), Proto->param_types(), EPI);
4009 }
4010 return T;
4011}
4012
4018
4021 bool AsWritten) {
4022 // Update the type.
4023 QualType Updated =
4025 FD->setType(Updated);
4026
4027 if (!AsWritten)
4028 return;
4029
4030 // Update the type in the type source information too.
4031 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
4032 // If the type and the type-as-written differ, we may need to update
4033 // the type-as-written too.
4034 if (TSInfo->getType() != FD->getType())
4035 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
4036
4037 // FIXME: When we get proper type location information for exceptions,
4038 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
4039 // up the TypeSourceInfo;
4040 assert(TypeLoc::getFullDataSizeForType(Updated) ==
4041 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
4042 "TypeLoc size mismatch from updating exception specification");
4043 TSInfo->overrideType(Updated);
4044 }
4045}
4046
4047/// getComplexType - Return the uniqued reference to the type for a complex
4048/// number with the specified element type.
4050 // Unique pointers, to guarantee there is only one pointer of a particular
4051 // structure.
4052 llvm::FoldingSetInsertToken Token;
4053 if (ComplexType *CT = ComplexTypes.lookup(T, Token))
4054 return QualType(CT, 0);
4055
4056 // If the pointee type isn't canonical, this won't be a canonical type either,
4057 // so fill in the canonical type field.
4058 QualType Canonical;
4059 if (!T.isCanonical()) {
4060 Canonical = getComplexType(getCanonicalType(T));
4061
4062 assert(!ComplexTypes.lookup(T, Token) && "Shouldn't be in the map!");
4063 }
4064 auto *New = new (*this, alignof(ComplexType)) ComplexType(T, Canonical);
4065 Types.push_back(New);
4066 ComplexTypes.insert(New, Token);
4067 return QualType(New, 0);
4068}
4069
4070/// getPointerType - Return the uniqued reference to the type for a pointer to
4071/// the specified type.
4073 // Unique pointers, to guarantee there is only one pointer of a particular
4074 // structure.
4075 llvm::FoldingSetInsertToken Token;
4076 if (PointerType *PT = PointerTypes.lookup(T, Token))
4077 return QualType(PT, 0);
4078
4079 // If the pointee type isn't canonical, this won't be a canonical type either,
4080 // so fill in the canonical type field.
4081 QualType Canonical;
4082 if (!T.isCanonical()) {
4083 Canonical = getPointerType(getCanonicalType(T));
4084
4085 assert(!PointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4086 }
4087 auto *New = new (*this, alignof(PointerType)) PointerType(T, Canonical);
4088 Types.push_back(New);
4089 PointerTypes.insert(New, Token);
4090 return QualType(New, 0);
4091}
4092
4094 llvm::FoldingSetInsertToken Token;
4095 AdjustedType *AT = AdjustedTypes.lookup({Orig, New}, Token);
4096 if (AT)
4097 return QualType(AT, 0);
4098
4099 QualType Canonical = getCanonicalType(New);
4100
4101 AT = new (*this, alignof(AdjustedType))
4102 AdjustedType(Type::Adjusted, Orig, New, Canonical);
4103 Types.push_back(AT);
4104 AdjustedTypes.insert(AT, Token);
4105 return QualType(AT, 0);
4106}
4107
4109 llvm::FoldingSetInsertToken Token;
4110 AdjustedType *AT = AdjustedTypes.lookup({Orig, Decayed}, Token);
4111 if (AT)
4112 return QualType(AT, 0);
4113
4114 QualType Canonical = getCanonicalType(Decayed);
4115
4116 AT = new (*this, alignof(DecayedType)) DecayedType(Orig, Decayed, Canonical);
4117 Types.push_back(AT);
4118 AdjustedTypes.insert(AT, Token);
4119 return QualType(AT, 0);
4120}
4121
4123 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
4124
4125 QualType Decayed;
4126
4127 // C99 6.7.5.3p7:
4128 // A declaration of a parameter as "array of type" shall be
4129 // adjusted to "qualified pointer to type", where the type
4130 // qualifiers (if any) are those specified within the [ and ] of
4131 // the array type derivation.
4132 if (T->isArrayType())
4133 Decayed = getArrayDecayedType(T);
4134
4135 // C99 6.7.5.3p8:
4136 // A declaration of a parameter as "function returning type"
4137 // shall be adjusted to "pointer to function returning type", as
4138 // in 6.3.2.1.
4139 if (T->isFunctionType())
4140 Decayed = getPointerType(T);
4141
4142 return getDecayedType(T, Decayed);
4143}
4144
4146 if (Ty->isArrayParameterType())
4147 return Ty;
4148 assert(Ty->isConstantArrayType() && "Ty must be an array type.");
4149 QualType DTy = Ty.getDesugaredType(*this);
4150 const auto *ATy = cast<ConstantArrayType>(DTy);
4151 llvm::FoldingSetNodeID ID;
4152 ATy->Profile(ID, *this, ATy->getElementType(), ATy->getZExtSize(),
4153 ATy->getSizeExpr(), ATy->getSizeModifier(),
4154 ATy->getIndexTypeQualifiers().getAsOpaqueValue());
4155 llvm::FoldingSetInsertToken Token;
4156 ArrayParameterType *AT = ArrayParameterTypes.lookup(ID, Token);
4157 if (AT)
4158 return QualType(AT, 0);
4159
4160 QualType Canonical;
4161 if (!DTy.isCanonical()) {
4162 Canonical = getArrayParameterType(getCanonicalType(Ty));
4163
4164 // Get the new insert position for the node we care about.
4165 AT = ArrayParameterTypes.lookup(ID, Token);
4166 assert(!AT && "Shouldn't be in the map!");
4167 }
4168
4169 AT = new (*this, alignof(ArrayParameterType))
4170 ArrayParameterType(ATy, Canonical);
4171 Types.push_back(AT);
4172 ArrayParameterTypes.insert(AT, Token);
4173 return QualType(AT, 0);
4174}
4175
4176/// getBlockPointerType - Return the uniqued reference to the type for
4177/// a pointer to the specified block.
4179 assert(T->isFunctionType() && "block of function types only");
4180 // Unique pointers, to guarantee there is only one block of a particular
4181 // structure.
4182 llvm::FoldingSetInsertToken Token;
4183 if (BlockPointerType *PT = BlockPointerTypes.lookup(T, Token))
4184 return QualType(PT, 0);
4185
4186 // If the block pointee type isn't canonical, this won't be a canonical
4187 // type either so fill in the canonical type field.
4188 QualType Canonical;
4189 if (!T.isCanonical()) {
4191
4192 assert(!BlockPointerTypes.lookup(T, Token) && "Shouldn't be in the map!");
4193 }
4194 auto *New =
4195 new (*this, alignof(BlockPointerType)) BlockPointerType(T, Canonical);
4196 Types.push_back(New);
4197 BlockPointerTypes.insert(New, Token);
4198 return QualType(New, 0);
4199}
4200
4201/// getLValueReferenceType - Return the uniqued reference to the type for an
4202/// lvalue reference to the specified type.
4204ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
4205 assert((!T->isPlaceholderType() ||
4206 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4207 "Unresolved placeholder type");
4208
4209 // Unique pointers, to guarantee there is only one pointer of a particular
4210 // structure.
4211 llvm::FoldingSetInsertToken Token;
4212 if (LValueReferenceType *RT =
4213 LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token))
4214 return QualType(RT, 0);
4215
4216 const auto *InnerRef = T->getAs<ReferenceType>();
4217
4218 // If the referencee type isn't canonical, this won't be a canonical type
4219 // either, so fill in the canonical type field.
4220 QualType Canonical;
4221 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
4222 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4223 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
4224
4225 assert(!LValueReferenceTypes.lookup({T, SpelledAsLValue}, Token) &&
4226 "Shouldn't be in the map!");
4227 }
4228
4229 auto *New = new (*this, alignof(LValueReferenceType))
4230 LValueReferenceType(T, Canonical, SpelledAsLValue);
4231 Types.push_back(New);
4232 LValueReferenceTypes.insert(New, Token);
4233
4234 return QualType(New, 0);
4235}
4236
4237/// getRValueReferenceType - Return the uniqued reference to the type for an
4238/// rvalue reference to the specified type.
4240 assert((!T->isPlaceholderType() ||
4241 T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
4242 "Unresolved placeholder type");
4243
4244 // Unique pointers, to guarantee there is only one pointer of a particular
4245 // structure.
4246 llvm::FoldingSetInsertToken Token;
4247 if (RValueReferenceType *RT = RValueReferenceTypes.lookup({T, false}, Token))
4248 return QualType(RT, 0);
4249
4250 const auto *InnerRef = T->getAs<ReferenceType>();
4251
4252 // If the referencee type isn't canonical, this won't be a canonical type
4253 // either, so fill in the canonical type field.
4254 QualType Canonical;
4255 if (InnerRef || !T.isCanonical()) {
4256 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
4257 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
4258
4259 assert(!RValueReferenceTypes.lookup({T, false}, Token) &&
4260 "Shouldn't be in the map!");
4261 }
4262
4263 auto *New = new (*this, alignof(RValueReferenceType))
4264 RValueReferenceType(T, Canonical);
4265 Types.push_back(New);
4266 RValueReferenceTypes.insert(New, Token);
4267 return QualType(New, 0);
4268}
4269
4271 NestedNameSpecifier Qualifier,
4272 const CXXRecordDecl *Cls) const {
4273 if (!Qualifier) {
4274 assert(Cls && "At least one of Qualifier or Cls must be provided");
4275 Qualifier = NestedNameSpecifier(getCanonicalTagType(Cls).getTypePtr());
4276 } else if (!Cls) {
4277 Cls = Qualifier.getAsRecordDecl();
4278 }
4279 // Unique pointers, to guarantee there is only one pointer of a particular
4280 // structure.
4281 llvm::FoldingSetNodeID ID;
4282 MemberPointerType::Profile(ID, T, Qualifier, Cls);
4283
4284 llvm::FoldingSetInsertToken Token;
4285 if (MemberPointerType *PT = MemberPointerTypes.lookup(ID, Token))
4286 return QualType(PT, 0);
4287
4288 NestedNameSpecifier CanonicalQualifier = [&] {
4289 if (!Cls)
4290 return Qualifier.getCanonical();
4291 NestedNameSpecifier R(getCanonicalTagType(Cls).getTypePtr());
4292 assert(R.isCanonical());
4293 return R;
4294 }();
4295 // If the pointee or class type isn't canonical, this won't be a canonical
4296 // type either, so fill in the canonical type field.
4297 QualType Canonical;
4298 if (!T.isCanonical() || Qualifier != CanonicalQualifier) {
4299 Canonical =
4300 getMemberPointerType(getCanonicalType(T), CanonicalQualifier, Cls);
4301 assert(!cast<MemberPointerType>(Canonical)->isSugared());
4302 // Get the new insert position for the node we care about.
4303 [[maybe_unused]] MemberPointerType *NewIP =
4304 MemberPointerTypes.lookup(ID, Token);
4305 assert(!NewIP && "Shouldn't be in the map!");
4306 }
4307 auto *New = new (*this, alignof(MemberPointerType))
4308 MemberPointerType(T, Qualifier, Canonical);
4309 Types.push_back(New);
4310 MemberPointerTypes.insert(New, Token);
4311 return QualType(New, 0);
4312}
4313
4314/// getConstantArrayType - Return the unique reference to the type for an
4315/// array of the specified element type.
4317 const llvm::APInt &ArySizeIn,
4318 const Expr *SizeExpr,
4320 unsigned IndexTypeQuals) const {
4321 assert((EltTy->isDependentType() ||
4322 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
4323 "Constant array of VLAs is illegal!");
4324
4325 // We only need the size as part of the type if it's instantiation-dependent.
4326 if (SizeExpr && !SizeExpr->isInstantiationDependent())
4327 SizeExpr = nullptr;
4328
4329 // Convert the array size into a canonical width matching the pointer size for
4330 // the target.
4331 llvm::APInt ArySize(ArySizeIn);
4332 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
4333
4334 llvm::FoldingSetNodeID ID;
4335 ConstantArrayType::Profile(ID, *this, EltTy, ArySize.getZExtValue(), SizeExpr,
4336 ASM, IndexTypeQuals);
4337
4338 llvm::FoldingSetInsertToken Token;
4339 if (ConstantArrayType *ATP = ConstantArrayTypes.lookup(ID, Token))
4340 return QualType(ATP, 0);
4341
4342 // If the element type isn't canonical or has qualifiers, or the array bound
4343 // is instantiation-dependent, this won't be a canonical type either, so fill
4344 // in the canonical type field.
4345 QualType Canon;
4346 // FIXME: Check below should look for qualifiers behind sugar.
4347 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
4348 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4349 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
4350 ASM, IndexTypeQuals);
4351 Canon = getQualifiedType(Canon, canonSplit.Quals);
4352
4353 // Get the new insert position for the node we care about.
4354 ConstantArrayType *NewIP = ConstantArrayTypes.lookup(ID, Token);
4355 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4356 }
4357
4358 auto *New = ConstantArrayType::Create(*this, EltTy, Canon, ArySize, SizeExpr,
4359 ASM, IndexTypeQuals);
4360 ConstantArrayTypes.insert(New, Token);
4361 Types.push_back(New);
4362 return QualType(New, 0);
4363}
4364
4365/// getVariableArrayDecayedType - Turns the given type, which may be
4366/// variably-modified, into the corresponding type with all the known
4367/// sizes replaced with [*].
4369 // Vastly most common case.
4370 if (!type->isVariablyModifiedType()) return type;
4371
4372 QualType result;
4373
4374 SplitQualType split = type.getSplitDesugaredType();
4375 const Type *ty = split.Ty;
4376 switch (ty->getTypeClass()) {
4377#define TYPE(Class, Base)
4378#define ABSTRACT_TYPE(Class, Base)
4379#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4380#include "clang/AST/TypeNodes.inc"
4381 llvm_unreachable("didn't desugar past all non-canonical types?");
4382
4383 // These types should never be variably-modified.
4384 case Type::Builtin:
4385 case Type::Complex:
4386 case Type::Vector:
4387 case Type::DependentVector:
4388 case Type::ExtVector:
4389 case Type::DependentSizedExtVector:
4390 case Type::ConstantMatrix:
4391 case Type::DependentSizedMatrix:
4392 case Type::DependentAddressSpace:
4393 case Type::ObjCObject:
4394 case Type::ObjCInterface:
4395 case Type::ObjCObjectPointer:
4396 case Type::Record:
4397 case Type::Enum:
4398 case Type::UnresolvedUsing:
4399 case Type::TypeOfExpr:
4400 case Type::TypeOf:
4401 case Type::Decltype:
4402 case Type::UnaryTransform:
4403 case Type::DependentName:
4404 case Type::InjectedClassName:
4405 case Type::TemplateSpecialization:
4406 case Type::TemplateTypeParm:
4407 case Type::SubstTemplateTypeParmPack:
4408 case Type::SubstBuiltinTemplatePack:
4409 case Type::Auto:
4410 case Type::DeducedTemplateSpecialization:
4411 case Type::PackExpansion:
4412 case Type::PackIndexing:
4413 case Type::BitInt:
4414 case Type::DependentBitInt:
4415 case Type::ArrayParameter:
4416 case Type::HLSLAttributedResource:
4417 case Type::HLSLInlineSpirv:
4418 case Type::OverflowBehavior:
4419 llvm_unreachable("type should never be variably-modified");
4420
4421 // These types can be variably-modified but should never need to
4422 // further decay.
4423 case Type::FunctionNoProto:
4424 case Type::FunctionProto:
4425 case Type::BlockPointer:
4426 case Type::MemberPointer:
4427 case Type::Pipe:
4428 return type;
4429
4430 // These types can be variably-modified. All these modifications
4431 // preserve structure except as noted by comments.
4432 // TODO: if we ever care about optimizing VLAs, there are no-op
4433 // optimizations available here.
4434 case Type::Pointer:
4437 break;
4438
4439 case Type::LValueReference: {
4440 const auto *lv = cast<LValueReferenceType>(ty);
4441 result = getLValueReferenceType(
4442 getVariableArrayDecayedType(lv->getPointeeType()),
4443 lv->isSpelledAsLValue());
4444 break;
4445 }
4446
4447 case Type::RValueReference: {
4448 const auto *lv = cast<RValueReferenceType>(ty);
4449 result = getRValueReferenceType(
4450 getVariableArrayDecayedType(lv->getPointeeType()));
4451 break;
4452 }
4453
4454 case Type::Atomic: {
4455 const auto *at = cast<AtomicType>(ty);
4456 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
4457 break;
4458 }
4459
4460 case Type::ConstantArray: {
4461 const auto *cat = cast<ConstantArrayType>(ty);
4462 result = getConstantArrayType(
4463 getVariableArrayDecayedType(cat->getElementType()),
4464 cat->getSize(),
4465 cat->getSizeExpr(),
4466 cat->getSizeModifier(),
4467 cat->getIndexTypeCVRQualifiers());
4468 break;
4469 }
4470
4471 case Type::DependentSizedArray: {
4472 const auto *dat = cast<DependentSizedArrayType>(ty);
4474 getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(),
4475 dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers());
4476 break;
4477 }
4478
4479 // Turn incomplete types into [*] types.
4480 case Type::IncompleteArray: {
4481 const auto *iat = cast<IncompleteArrayType>(ty);
4482 result =
4484 /*size*/ nullptr, ArraySizeModifier::Normal,
4485 iat->getIndexTypeCVRQualifiers());
4486 break;
4487 }
4488
4489 // Turn VLA types into [*] types.
4490 case Type::VariableArray: {
4491 const auto *vat = cast<VariableArrayType>(ty);
4492 result =
4494 /*size*/ nullptr, ArraySizeModifier::Star,
4495 vat->getIndexTypeCVRQualifiers());
4496 break;
4497 }
4498 }
4499
4500 // Apply the top-level qualifiers from the original.
4501 return getQualifiedType(result, split.Quals);
4502}
4503
4504/// getVariableArrayType - Returns a non-unique reference to the type for a
4505/// variable array of the specified element type.
4508 unsigned IndexTypeQuals) const {
4509 // Since we don't unique expressions, it isn't possible to unique VLA's
4510 // that have an expression provided for their size.
4511 QualType Canon;
4512
4513 // Be sure to pull qualifiers off the element type.
4514 // FIXME: Check below should look for qualifiers behind sugar.
4515 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
4516 SplitQualType canonSplit = getCanonicalType(EltTy).split();
4517 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
4518 IndexTypeQuals);
4519 Canon = getQualifiedType(Canon, canonSplit.Quals);
4520 }
4521
4522 auto *New = new (*this, alignof(VariableArrayType))
4523 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals);
4524
4525 VariableArrayTypes.push_back(New);
4526 Types.push_back(New);
4527 return QualType(New, 0);
4528}
4529
4530/// getDependentSizedArrayType - Returns a non-unique reference to
4531/// the type for a dependently-sized array of the specified element
4532/// type.
4536 unsigned elementTypeQuals) const {
4537 assert((!numElements || numElements->isTypeDependent() ||
4538 numElements->isValueDependent()) &&
4539 "Size must be type- or value-dependent!");
4540
4541 SplitQualType canonElementType = getCanonicalType(elementType).split();
4542
4543 llvm::FoldingSetInsertToken Token;
4544 llvm::FoldingSetNodeID ID;
4546 ID, *this, numElements ? QualType(canonElementType.Ty, 0) : elementType,
4547 ASM, elementTypeQuals, numElements);
4548
4549 // Look for an existing type with these properties.
4550 DependentSizedArrayType *canonTy = DependentSizedArrayTypes.lookup(ID, Token);
4551
4552 // Dependently-sized array types that do not have a specified number
4553 // of elements will have their sizes deduced from a dependent
4554 // initializer.
4555 if (!numElements) {
4556 if (canonTy)
4557 return QualType(canonTy, 0);
4558
4559 auto *newType = new (*this, alignof(DependentSizedArrayType))
4560 DependentSizedArrayType(elementType, QualType(), numElements, ASM,
4561 elementTypeQuals);
4562 DependentSizedArrayTypes.insert(newType, Token);
4563 Types.push_back(newType);
4564 return QualType(newType, 0);
4565 }
4566
4567 // If we don't have one, build one.
4568 if (!canonTy) {
4569 canonTy = new (*this, alignof(DependentSizedArrayType))
4570 DependentSizedArrayType(QualType(canonElementType.Ty, 0), QualType(),
4571 numElements, ASM, elementTypeQuals);
4572 DependentSizedArrayTypes.insert(canonTy, Token);
4573 Types.push_back(canonTy);
4574 }
4575
4576 // Apply qualifiers from the element type to the array.
4577 QualType canon = getQualifiedType(QualType(canonTy,0),
4578 canonElementType.Quals);
4579
4580 // If we didn't need extra canonicalization for the element type or the size
4581 // expression, then just use that as our result.
4582 if (QualType(canonElementType.Ty, 0) == elementType &&
4583 canonTy->getSizeExpr() == numElements)
4584 return canon;
4585
4586 // Otherwise, we need to build a type which follows the spelling
4587 // of the element type.
4588 auto *sugaredType = new (*this, alignof(DependentSizedArrayType))
4589 DependentSizedArrayType(elementType, canon, numElements, ASM,
4590 elementTypeQuals);
4591 Types.push_back(sugaredType);
4592 return QualType(sugaredType, 0);
4593}
4594
4597 unsigned elementTypeQuals) const {
4598 llvm::FoldingSetNodeID ID;
4599 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
4600
4601 llvm::FoldingSetInsertToken Token;
4602 if (IncompleteArrayType *iat = IncompleteArrayTypes.lookup(ID, Token))
4603 return QualType(iat, 0);
4604
4605 // If the element type isn't canonical, this won't be a canonical type
4606 // either, so fill in the canonical type field. We also have to pull
4607 // qualifiers off the element type.
4608 QualType canon;
4609
4610 // FIXME: Check below should look for qualifiers behind sugar.
4611 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
4612 SplitQualType canonSplit = getCanonicalType(elementType).split();
4613 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
4614 ASM, elementTypeQuals);
4615 canon = getQualifiedType(canon, canonSplit.Quals);
4616
4617 // Get the new insert position for the node we care about.
4618 IncompleteArrayType *existing = IncompleteArrayTypes.lookup(ID, Token);
4619 assert(!existing && "Shouldn't be in the map!"); (void) existing;
4620 }
4621
4622 auto *newType = new (*this, alignof(IncompleteArrayType))
4623 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
4624
4625 IncompleteArrayTypes.insert(newType, Token);
4626 Types.push_back(newType);
4627 return QualType(newType, 0);
4628}
4629
4632#define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
4633 {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
4634 NUMVECTORS};
4635
4636#define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
4637 {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
4638
4639 switch (Ty->getKind()) {
4640 default:
4641 llvm_unreachable("Unsupported builtin vector type");
4642
4643#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4644 ElBits, NF, IsSigned) \
4645 case BuiltinType::Id: \
4646 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4647 llvm::ElementCount::getScalable(NumEls), NF};
4648#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4649 ElBits, NF) \
4650 case BuiltinType::Id: \
4651 return {ElBits == 16 ? HalfTy : (ElBits == 32 ? FloatTy : DoubleTy), \
4652 llvm::ElementCount::getScalable(NumEls), NF};
4653#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4654 ElBits, NF) \
4655 case BuiltinType::Id: \
4656 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4657#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4658 ElBits, NF) \
4659 case BuiltinType::Id: \
4660 return {MFloat8Ty, llvm::ElementCount::getScalable(NumEls), NF};
4661#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4662 case BuiltinType::Id: \
4663 return {BoolTy, llvm::ElementCount::getScalable(NumEls), NF};
4664#include "clang/Basic/AArch64ACLETypes.def"
4665
4666#define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
4667 IsSigned) \
4668 case BuiltinType::Id: \
4669 return {getIntTypeForBitwidth(ElBits, IsSigned), \
4670 llvm::ElementCount::getScalable(NumEls), NF};
4671#define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4672 case BuiltinType::Id: \
4673 return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
4674 llvm::ElementCount::getScalable(NumEls), NF};
4675#define RVV_VECTOR_TYPE_BFLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
4676 case BuiltinType::Id: \
4677 return {BFloat16Ty, llvm::ElementCount::getScalable(NumEls), NF};
4678#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4679 case BuiltinType::Id: \
4680 return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
4681#include "clang/Basic/RISCVVTypes.def"
4682 }
4683}
4684
4685/// getExternrefType - Return a WebAssembly externref type, which represents an
4686/// opaque reference to a host value.
4688 if (Target->getTriple().isWasm() && Target->hasFeature("reference-types")) {
4689#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
4690 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
4691 return SingletonId;
4692#include "clang/Basic/WebAssemblyReferenceTypes.def"
4693 }
4694 llvm_unreachable(
4695 "shouldn't try to generate type externref outside WebAssembly target");
4696}
4697
4698/// getScalableVectorType - Return the unique reference to a scalable vector
4699/// type of the specified element type and size. VectorType must be a built-in
4700/// type.
4702 unsigned NumFields) const {
4703 auto K = llvm::ScalableVecTyKey{EltTy, NumElts, NumFields};
4704 if (auto It = ScalableVecTyMap.find(K); It != ScalableVecTyMap.end())
4705 return It->second;
4706
4707 if (Target->hasAArch64ACLETypes()) {
4708 uint64_t EltTySize = getTypeSize(EltTy);
4709
4710#define SVE_VECTOR_TYPE_INT(Name, MangledName, Id, SingletonId, NumEls, \
4711 ElBits, NF, IsSigned) \
4712 if (EltTy->hasIntegerRepresentation() && !EltTy->isBooleanType() && \
4713 EltTy->hasSignedIntegerRepresentation() == IsSigned && \
4714 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4715 return ScalableVecTyMap[K] = SingletonId; \
4716 }
4717#define SVE_VECTOR_TYPE_FLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4718 ElBits, NF) \
4719 if (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4720 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4721 return ScalableVecTyMap[K] = SingletonId; \
4722 }
4723#define SVE_VECTOR_TYPE_BFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4724 ElBits, NF) \
4725 if (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4726 EltTySize == ElBits && NumElts == (NumEls * NF) && NumFields == 1) { \
4727 return ScalableVecTyMap[K] = SingletonId; \
4728 }
4729#define SVE_VECTOR_TYPE_MFLOAT(Name, MangledName, Id, SingletonId, NumEls, \
4730 ElBits, NF) \
4731 if (EltTy->isMFloat8Type() && EltTySize == ElBits && \
4732 NumElts == (NumEls * NF) && NumFields == 1) { \
4733 return ScalableVecTyMap[K] = SingletonId; \
4734 }
4735#define SVE_PREDICATE_TYPE_ALL(Name, MangledName, Id, SingletonId, NumEls, NF) \
4736 if (EltTy->isBooleanType() && NumElts == (NumEls * NF) && NumFields == 1) \
4737 return ScalableVecTyMap[K] = SingletonId;
4738#include "clang/Basic/AArch64ACLETypes.def"
4739 } else if (Target->hasRISCVVTypes()) {
4740 uint64_t EltTySize = getTypeSize(EltTy);
4741#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
4742 IsFP, IsBF) \
4743 if (!EltTy->isBooleanType() && \
4744 ((EltTy->hasIntegerRepresentation() && \
4745 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
4746 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
4747 IsFP && !IsBF) || \
4748 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
4749 IsBF && !IsFP)) && \
4750 EltTySize == ElBits && NumElts == NumEls && NumFields == NF) \
4751 return ScalableVecTyMap[K] = SingletonId;
4752#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
4753 if (EltTy->isBooleanType() && NumElts == NumEls) \
4754 return ScalableVecTyMap[K] = SingletonId;
4755#include "clang/Basic/RISCVVTypes.def"
4756 }
4757 return QualType();
4758}
4759
4760/// getVectorType - Return the unique reference to a vector type of
4761/// the specified element type and size. VectorType must be a built-in type.
4763 VectorKind VecKind) const {
4764 assert(vecType->isBuiltinType() ||
4765 (vecType->isBitIntType() &&
4766 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4767 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4768
4769 // Check if we've already instantiated a vector of this type.
4770 llvm::FoldingSetNodeID ID;
4771 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
4772
4773 llvm::FoldingSetInsertToken Token;
4774 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4775 return QualType(VTP, 0);
4776
4777 // If the element type isn't canonical, this won't be a canonical type either,
4778 // so fill in the canonical type field.
4779 QualType Canonical;
4780 if (!vecType.isCanonical()) {
4781 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
4782
4783 // Get the new insert position for the node we care about.
4784 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4785 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4786 }
4787 auto *New = new (*this, alignof(VectorType))
4788 VectorType(vecType, NumElts, Canonical, VecKind);
4789 VectorTypes.insert(New, Token);
4790 Types.push_back(New);
4791 return QualType(New, 0);
4792}
4793
4795 SourceLocation AttrLoc,
4796 VectorKind VecKind) const {
4797 llvm::FoldingSetNodeID ID;
4798 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
4799 VecKind);
4800 llvm::FoldingSetInsertToken Token;
4801 DependentVectorType *Canon = DependentVectorTypes.lookup(ID, Token);
4803
4804 if (Canon) {
4805 New = new (*this, alignof(DependentVectorType)) DependentVectorType(
4806 VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
4807 } else {
4808 QualType CanonVecTy = getCanonicalType(VecType);
4809 if (CanonVecTy == VecType) {
4810 New = new (*this, alignof(DependentVectorType))
4811 DependentVectorType(VecType, QualType(), SizeExpr, AttrLoc, VecKind);
4812
4813 DependentVectorType *CanonCheck = DependentVectorTypes.lookup(ID, Token);
4814 assert(!CanonCheck &&
4815 "Dependent-sized vector_size canonical type broken");
4816 (void)CanonCheck;
4817 DependentVectorTypes.insert(New, Token);
4818 } else {
4819 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
4820 SourceLocation(), VecKind);
4821 New = new (*this, alignof(DependentVectorType))
4822 DependentVectorType(VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
4823 }
4824 }
4825
4826 Types.push_back(New);
4827 return QualType(New, 0);
4828}
4829
4830/// getExtVectorType - Return the unique reference to an extended vector type of
4831/// the specified element type and size. VectorType must be a built-in type.
4833 unsigned NumElts) const {
4834 assert(vecType->isBuiltinType() || vecType->isDependentType() ||
4835 (vecType->isBitIntType() &&
4836 // Only support _BitInt elements with byte-sized power of 2 NumBits.
4837 llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
4838
4839 // Check if we've already instantiated a vector of this type.
4840 llvm::FoldingSetNodeID ID;
4841 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
4843 llvm::FoldingSetInsertToken Token;
4844 if (VectorType *VTP = VectorTypes.lookup(ID, Token))
4845 return QualType(VTP, 0);
4846
4847 // If the element type isn't canonical, this won't be a canonical type either,
4848 // so fill in the canonical type field.
4849 QualType Canonical;
4850 if (!vecType.isCanonical()) {
4851 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
4852
4853 // Get the new insert position for the node we care about.
4854 VectorType *NewIP = VectorTypes.lookup(ID, Token);
4855 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4856 }
4857 auto *New = new (*this, alignof(ExtVectorType))
4858 ExtVectorType(vecType, NumElts, Canonical);
4859 VectorTypes.insert(New, Token);
4860 Types.push_back(New);
4861 return QualType(New, 0);
4862}
4863
4866 Expr *SizeExpr,
4867 SourceLocation AttrLoc) const {
4868 llvm::FoldingSetNodeID ID;
4870 SizeExpr);
4871
4872 llvm::FoldingSetInsertToken Token;
4874 DependentSizedExtVectorTypes.lookup(ID, Token);
4876 if (Canon) {
4877 // We already have a canonical version of this array type; use it as
4878 // the canonical type for a newly-built type.
4879 New = new (*this, alignof(DependentSizedExtVectorType))
4880 DependentSizedExtVectorType(vecType, QualType(Canon, 0), SizeExpr,
4881 AttrLoc);
4882 } else {
4883 QualType CanonVecTy = getCanonicalType(vecType);
4884 if (CanonVecTy == vecType) {
4885 New = new (*this, alignof(DependentSizedExtVectorType))
4886 DependentSizedExtVectorType(vecType, QualType(), SizeExpr, AttrLoc);
4887
4888 DependentSizedExtVectorType *CanonCheck =
4889 DependentSizedExtVectorTypes.lookup(ID, Token);
4890 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
4891 (void)CanonCheck;
4892 DependentSizedExtVectorTypes.insert(New, Token);
4893 } else {
4894 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
4895 SourceLocation());
4896 New = new (*this, alignof(DependentSizedExtVectorType))
4897 DependentSizedExtVectorType(vecType, CanonExtTy, SizeExpr, AttrLoc);
4898 }
4899 }
4900
4901 Types.push_back(New);
4902 return QualType(New, 0);
4903}
4904
4906 QualType ElementTy, unsigned NumRows, unsigned NumColumns,
4907 std::optional<MatrixType::LayoutKind> Layout) const {
4908 llvm::FoldingSetNodeID ID;
4909 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns, Layout,
4910 Type::ConstantMatrix);
4911
4912 assert(MatrixType::isValidElementType(ElementTy, getLangOpts()) &&
4913 "need a valid element type");
4914 assert(NumRows > 0 && NumRows <= LangOpts.MaxMatrixDimension &&
4915 NumColumns > 0 && NumColumns <= LangOpts.MaxMatrixDimension &&
4916 "need valid matrix dimensions");
4917 llvm::FoldingSetInsertToken Token;
4918 if (ConstantMatrixType *MTP = MatrixTypes.lookup(ID, Token))
4919 return QualType(MTP, 0);
4920
4921 QualType Canonical;
4922 if (Layout || !ElementTy.isCanonical()) {
4923 Canonical = getConstantMatrixType(getCanonicalType(ElementTy), NumRows,
4924 NumColumns, std::nullopt);
4925
4926 ConstantMatrixType *NewIP = MatrixTypes.lookup(ID, Token);
4927 assert(!NewIP && "Matrix type shouldn't already exist in the map");
4928 (void)NewIP;
4929 }
4930
4931 auto *New = new (*this, alignof(ConstantMatrixType))
4932 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical, Layout);
4933 MatrixTypes.insert(New, Token);
4934 Types.push_back(New);
4935 return QualType(New, 0);
4936}
4937
4939 Expr *RowExpr,
4940 Expr *ColumnExpr,
4941 SourceLocation AttrLoc) const {
4942 QualType CanonElementTy = getCanonicalType(ElementTy);
4943 llvm::FoldingSetNodeID ID;
4944 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
4945 ColumnExpr);
4946
4947 llvm::FoldingSetInsertToken Token;
4948 DependentSizedMatrixType *Canon = DependentSizedMatrixTypes.lookup(ID, Token);
4949
4950 if (!Canon) {
4951 Canon = new (*this, alignof(DependentSizedMatrixType))
4952 DependentSizedMatrixType(CanonElementTy, QualType(), RowExpr,
4953 ColumnExpr, AttrLoc);
4954#ifndef NDEBUG
4955 DependentSizedMatrixType *CanonCheck =
4956 DependentSizedMatrixTypes.lookup(ID, Token);
4957 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
4958#endif
4959 DependentSizedMatrixTypes.insert(Canon, Token);
4960 Types.push_back(Canon);
4961 }
4962
4963 // Already have a canonical version of the matrix type
4964 //
4965 // If it exactly matches the requested type, use it directly.
4966 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
4967 Canon->getRowExpr() == ColumnExpr)
4968 return QualType(Canon, 0);
4969
4970 // Use Canon as the canonical type for newly-built type.
4972 DependentSizedMatrixType(ElementTy, QualType(Canon, 0), RowExpr,
4973 ColumnExpr, AttrLoc);
4974 Types.push_back(New);
4975 return QualType(New, 0);
4976}
4977
4980 MatrixType::LayoutKind Layout) const {
4981 Qualifiers Quals = T.getQualifiers();
4982 const Type *Ty = T->getUnqualifiedDesugaredType();
4983
4984 if (const auto *MT = dyn_cast<ConstantMatrixType>(Ty))
4985 return getQualifiedType(getConstantMatrixType(MT->getElementType(),
4986 MT->getNumRows(),
4987 MT->getNumColumns(), Layout),
4988 Quals);
4989
4990 const auto *CAT = dyn_cast<ConstantArrayType>(Ty);
4991 if (!CAT)
4992 return T;
4993
4995 getMatrixTypeWithLayout(CAT->getElementType(), Layout), CAT->getSize(),
4996 CAT->getSizeExpr(), CAT->getSizeModifier(),
4997 CAT->getIndexTypeCVRQualifiers());
4998 if (isa<ArrayParameterType>(CAT))
5000
5001 return getQualifiedType(Result, Quals);
5002}
5003
5005 Expr *AddrSpaceExpr,
5006 SourceLocation AttrLoc) const {
5007 assert(AddrSpaceExpr->isInstantiationDependent());
5008
5009 QualType canonPointeeType = getCanonicalType(PointeeType);
5010
5011 llvm::FoldingSetInsertToken Token;
5012 llvm::FoldingSetNodeID ID;
5013 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
5014 AddrSpaceExpr);
5015
5016 DependentAddressSpaceType *canonTy =
5017 DependentAddressSpaceTypes.lookup(ID, Token);
5018
5019 if (!canonTy) {
5020 canonTy = new (*this, alignof(DependentAddressSpaceType))
5021 DependentAddressSpaceType(canonPointeeType, QualType(), AddrSpaceExpr,
5022 AttrLoc);
5023 DependentAddressSpaceTypes.insert(canonTy, Token);
5024 Types.push_back(canonTy);
5025 }
5026
5027 if (canonPointeeType == PointeeType &&
5028 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
5029 return QualType(canonTy, 0);
5030
5031 auto *sugaredType = new (*this, alignof(DependentAddressSpaceType))
5032 DependentAddressSpaceType(PointeeType, QualType(canonTy, 0),
5033 AddrSpaceExpr, AttrLoc);
5034 Types.push_back(sugaredType);
5035 return QualType(sugaredType, 0);
5036}
5037
5038/// Determine whether \p T is canonical as the result type of a function.
5040 return T.isCanonical() &&
5041 (T.getObjCLifetime() == Qualifiers::OCL_None ||
5042 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
5043}
5044
5045/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
5046QualType
5048 const FunctionType::ExtInfo &Info) const {
5049 // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
5050 // functionality creates a function without a prototype regardless of
5051 // language mode (so it makes them even in C++). Once the rewriter has been
5052 // fixed, this assertion can be enabled again.
5053 //assert(!LangOpts.requiresStrictPrototypes() &&
5054 // "strict prototypes are disabled");
5055
5056 // Unique functions, to guarantee there is only one function of a particular
5057 // structure.
5058 llvm::FoldingSetNodeID ID;
5059 FunctionNoProtoType::Profile(ID, ResultTy, Info);
5060
5061 llvm::FoldingSetInsertToken Token;
5062 if (FunctionNoProtoType *FT = FunctionNoProtoTypes.lookup(ID, Token))
5063 return QualType(FT, 0);
5064
5065 QualType Canonical;
5066 if (!isCanonicalResultType(ResultTy)) {
5067 Canonical =
5069
5070 // Get the new insert position for the node we care about.
5071 FunctionNoProtoType *NewIP = FunctionNoProtoTypes.lookup(ID, Token);
5072 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5073 }
5074
5075 auto *New = new (*this, alignof(FunctionNoProtoType))
5076 FunctionNoProtoType(ResultTy, Canonical, Info);
5077 Types.push_back(New);
5078 FunctionNoProtoTypes.insert(New, Token);
5079 return QualType(New, 0);
5080}
5081
5084 CanQualType CanResultType = getCanonicalType(ResultType);
5085
5086 // Canonical result types do not have ARC lifetime qualifiers.
5087 if (CanResultType.getQualifiers().hasObjCLifetime()) {
5088 Qualifiers Qs = CanResultType.getQualifiers();
5089 Qs.removeObjCLifetime();
5091 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
5092 }
5093
5094 return CanResultType;
5095}
5096
5098 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
5099 if (ESI.Type == EST_None)
5100 return true;
5101 if (!NoexceptInType)
5102 return false;
5103
5104 // C++17 onwards: exception specification is part of the type, as a simple
5105 // boolean "can this function type throw".
5106 if (ESI.Type == EST_BasicNoexcept)
5107 return true;
5108
5109 // A noexcept(expr) specification is (possibly) canonical if expr is
5110 // value-dependent.
5111 if (ESI.Type == EST_DependentNoexcept)
5112 return true;
5113
5114 // A dynamic exception specification is canonical if it only contains pack
5115 // expansions (so we can't tell whether it's non-throwing) and all its
5116 // contained types are canonical.
5117 if (ESI.Type == EST_Dynamic) {
5118 bool AnyPackExpansions = false;
5119 for (QualType ET : ESI.Exceptions) {
5120 if (!ET.isCanonical())
5121 return false;
5122 if (ET->getAs<PackExpansionType>())
5123 AnyPackExpansions = true;
5124 }
5125 return AnyPackExpansions;
5126 }
5127
5128 return false;
5129}
5130
5131QualType ASTContext::getFunctionTypeInternal(
5132 QualType ResultTy, ArrayRef<QualType> ArgArray,
5133 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
5134 size_t NumArgs = ArgArray.size();
5135
5136 // Unique functions, to guarantee there is only one function of a particular
5137 // structure.
5138 llvm::FoldingSetNodeID ID;
5139 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
5140 *this);
5141
5142 QualType Canonical;
5143 bool Unique = false;
5144
5145 llvm::FoldingSetInsertToken Token;
5146 if (FunctionProtoType *FPT = FunctionProtoTypes.lookup(ID, Token)) {
5147 QualType Existing = QualType(FPT, 0);
5148
5149 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
5150 // it so long as our exception specification doesn't contain a dependent
5151 // noexcept expression, or we're just looking for a canonical type.
5152 // Otherwise, we're going to need to create a type
5153 // sugar node to hold the concrete expression.
5154 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
5155 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
5156 return Existing;
5157
5158 // We need a new type sugar node for this one, to hold the new noexcept
5159 // expression. We do no canonicalization here, but that's OK since we don't
5160 // expect to see the same noexcept expression much more than once.
5161 Canonical = getCanonicalType(Existing);
5162 Unique = true;
5163 }
5164
5165 bool NoexceptInType = getLangOpts().CPlusPlus17;
5166 bool IsCanonicalExceptionSpec =
5168
5169 // Determine whether the type being created is already canonical or not.
5170 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
5171 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
5172 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
5173 if (!ArgArray[i].isCanonicalAsParam())
5174 isCanonical = false;
5175
5176 if (OnlyWantCanonical)
5177 assert(isCanonical &&
5178 "given non-canonical parameters constructing canonical type");
5179
5180 // If this type isn't canonical, get the canonical version of it if we don't
5181 // already have it. The exception spec is only partially part of the
5182 // canonical type, and only in C++17 onwards.
5183 if (!isCanonical && Canonical.isNull()) {
5184 SmallVector<QualType, 16> CanonicalArgs;
5185 CanonicalArgs.reserve(NumArgs);
5186 for (unsigned i = 0; i != NumArgs; ++i)
5187 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
5188
5189 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
5190 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
5191 CanonicalEPI.HasTrailingReturn = false;
5192
5193 if (IsCanonicalExceptionSpec) {
5194 // Exception spec is already OK.
5195 } else if (NoexceptInType) {
5196 switch (EPI.ExceptionSpec.Type) {
5198 // We don't know yet. It shouldn't matter what we pick here; no-one
5199 // should ever look at this.
5200 [[fallthrough]];
5201 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
5202 CanonicalEPI.ExceptionSpec.Type = EST_None;
5203 break;
5204
5205 // A dynamic exception specification is almost always "not noexcept",
5206 // with the exception that a pack expansion might expand to no types.
5207 case EST_Dynamic: {
5208 bool AnyPacks = false;
5209 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
5210 if (ET->getAs<PackExpansionType>())
5211 AnyPacks = true;
5212 ExceptionTypeStorage.push_back(getCanonicalType(ET));
5213 }
5214 if (!AnyPacks)
5215 CanonicalEPI.ExceptionSpec.Type = EST_None;
5216 else {
5217 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
5218 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
5219 }
5220 break;
5221 }
5222
5223 case EST_DynamicNone:
5224 case EST_BasicNoexcept:
5225 case EST_NoexceptTrue:
5226 case EST_NoThrow:
5227 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
5228 break;
5229
5231 llvm_unreachable("dependent noexcept is already canonical");
5232 }
5233 } else {
5234 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
5235 }
5236
5237 // Adjust the canonical function result type.
5238 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
5239 Canonical =
5240 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
5241
5242 // Get the new insert position for the node we care about.
5243 FunctionProtoType *NewIP = FunctionProtoTypes.lookup(ID, Token);
5244 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5245 }
5246
5247 // Compute the needed size to hold this FunctionProtoType and the
5248 // various trailing objects.
5249 auto ESH = FunctionProtoType::getExceptionSpecSize(
5250 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
5251 size_t Size = FunctionProtoType::totalSizeToAlloc<
5252 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
5253 FunctionType::FunctionTypeExtraAttributeInfo,
5254 FunctionType::FunctionTypeArmAttributes, FunctionType::ExceptionType,
5255 Expr *, FunctionDecl *, FunctionProtoType::ExtParameterInfo, Qualifiers,
5256 FunctionEffect, EffectConditionExpr>(
5259 EPI.requiresFunctionProtoTypeArmAttributes(), ESH.NumExceptionType,
5260 ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
5261 EPI.ExtParameterInfos ? NumArgs : 0,
5263 EPI.FunctionEffects.conditions().size());
5264
5265 auto *FTP = (FunctionProtoType *)Allocate(Size, alignof(FunctionProtoType));
5266 FunctionProtoType::ExtProtoInfo newEPI = EPI;
5267 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
5268 Types.push_back(FTP);
5269 if (!Unique)
5270 FunctionProtoTypes.insert(FTP, Token);
5271 if (!EPI.FunctionEffects.empty())
5272 AnyFunctionEffects = true;
5273 return QualType(FTP, 0);
5274}
5275
5276QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
5277 llvm::FoldingSetInsertToken Token;
5278 if (PipeType *PT = PipeTypes.lookup({T, ReadOnly}, Token))
5279 return QualType(PT, 0);
5280
5281 // If the pipe element type isn't canonical, this won't be a canonical type
5282 // either, so fill in the canonical type field.
5283 QualType Canonical;
5284 if (!T.isCanonical()) {
5285 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
5286
5287 assert(!PipeTypes.lookup({T, ReadOnly}, Token) &&
5288 "Shouldn't be in the map!");
5289 }
5290 auto *New = new (*this, alignof(PipeType)) PipeType(T, Canonical, ReadOnly);
5291 Types.push_back(New);
5292 PipeTypes.insert(New, Token);
5293 return QualType(New, 0);
5294}
5295
5297 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
5298 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
5299 : Ty;
5300}
5301
5303 return getPipeType(T, true);
5304}
5305
5307 return getPipeType(T, false);
5308}
5309
5310QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
5311 auto Key = std::make_pair(unsigned(IsUnsigned), NumBits);
5312
5313 llvm::FoldingSetInsertToken Token;
5314 if (BitIntType *EIT = BitIntTypes.lookup(Key, Token))
5315 return QualType(EIT, 0);
5316
5317 auto *New = new (*this, alignof(BitIntType)) BitIntType(IsUnsigned, NumBits);
5318 BitIntTypes.insert(New, Token);
5319 Types.push_back(New);
5320 return QualType(New, 0);
5321}
5322
5324 Expr *NumBitsExpr) const {
5325 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
5326 llvm::FoldingSetNodeID ID;
5327 DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
5328
5329 llvm::FoldingSetInsertToken Token;
5330 if (DependentBitIntType *Existing = DependentBitIntTypes.lookup(ID, Token))
5331 return QualType(Existing, 0);
5332
5333 auto *New = new (*this, alignof(DependentBitIntType))
5334 DependentBitIntType(IsUnsigned, NumBitsExpr);
5335 DependentBitIntTypes.insert(New, Token);
5336
5337 Types.push_back(New);
5338 return QualType(New, 0);
5339}
5340
5343 using Kind = PredefinedSugarType::Kind;
5344
5345 if (auto *Target = PredefinedSugarTypes[llvm::to_underlying(KD)];
5346 Target != nullptr)
5347 return QualType(Target, 0);
5348
5349 auto getCanonicalType = [](const ASTContext &Ctx, Kind KDI) -> QualType {
5350 switch (KDI) {
5351 // size_t (C99TC3 6.5.3.4), signed size_t (C++23 5.13.2) and
5352 // ptrdiff_t (C99TC3 6.5.6) Although these types are not built-in, they
5353 // are part of the core language and are widely used. Using
5354 // PredefinedSugarType makes these types as named sugar types rather than
5355 // standard integer types, enabling better hints and diagnostics.
5356 case Kind::SizeT:
5357 return Ctx.getFromTargetType(Ctx.Target->getSizeType());
5358 case Kind::SignedSizeT:
5359 return Ctx.getFromTargetType(Ctx.Target->getSignedSizeType());
5360 case Kind::PtrdiffT:
5361 return Ctx.getFromTargetType(Ctx.Target->getPtrDiffType(LangAS::Default));
5362 }
5363 llvm_unreachable("unexpected kind");
5364 };
5365 auto *New = new (*this, alignof(PredefinedSugarType))
5366 PredefinedSugarType(KD, &Idents.get(PredefinedSugarType::getName(KD)),
5367 getCanonicalType(*this, static_cast<Kind>(KD)));
5368 Types.push_back(New);
5369 PredefinedSugarTypes[llvm::to_underlying(KD)] = New;
5370 return QualType(New, 0);
5371}
5372
5374 NestedNameSpecifier Qualifier,
5375 const TypeDecl *Decl) const {
5376 if (auto *Tag = dyn_cast<TagDecl>(Decl))
5377 return getTagType(Keyword, Qualifier, Tag,
5378 /*OwnsTag=*/false);
5379 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
5380 return getTypedefType(Keyword, Qualifier, Typedef);
5381 if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5382 return getUnresolvedUsingType(Keyword, Qualifier, UD);
5383
5385 assert(!Qualifier);
5386 return QualType(Decl->TypeForDecl, 0);
5387}
5388
5390 if (auto *Tag = dyn_cast<TagDecl>(TD))
5391 return getCanonicalTagType(Tag);
5392 if (auto *TN = dyn_cast<TypedefNameDecl>(TD))
5393 return getCanonicalType(TN->getUnderlyingType());
5394 if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TD))
5396 assert(TD->TypeForDecl);
5397 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5398}
5399
5401 if (const auto *TD = dyn_cast<TagDecl>(Decl))
5402 return getCanonicalTagType(TD);
5403 if (const auto *TD = dyn_cast<TypedefNameDecl>(Decl);
5404 isa_and_nonnull<TypedefDecl, TypeAliasDecl>(TD))
5406 /*Qualifier=*/std::nullopt, TD);
5407 if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl))
5408 return getCanonicalUnresolvedUsingType(Using);
5409
5410 assert(Decl->TypeForDecl);
5411 return QualType(Decl->TypeForDecl, 0);
5412}
5413
5414/// getTypedefType - Return the unique reference to the type for the
5415/// specified typedef name decl.
5418 NestedNameSpecifier Qualifier,
5419 const TypedefNameDecl *Decl, QualType UnderlyingType,
5420 std::optional<bool> TypeMatchesDeclOrNone) const {
5421 if (!TypeMatchesDeclOrNone) {
5422 QualType DeclUnderlyingType = Decl->getUnderlyingType();
5423 assert(!DeclUnderlyingType.isNull());
5424 if (UnderlyingType.isNull())
5425 UnderlyingType = DeclUnderlyingType;
5426 else
5427 assert(hasSameType(UnderlyingType, DeclUnderlyingType));
5428 TypeMatchesDeclOrNone = UnderlyingType == DeclUnderlyingType;
5429 } else {
5430 // FIXME: This is a workaround for a serialization cycle: assume the decl
5431 // underlying type is not available; don't touch it.
5432 assert(!UnderlyingType.isNull());
5433 }
5434
5435 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier &&
5436 *TypeMatchesDeclOrNone) {
5437 if (Decl->TypeForDecl)
5438 return QualType(Decl->TypeForDecl, 0);
5439
5440 auto *NewType = new (*this, alignof(TypedefType))
5441 TypedefType(Type::Typedef, Keyword, Qualifier, Decl, UnderlyingType,
5442 !*TypeMatchesDeclOrNone);
5443
5444 Types.push_back(NewType);
5445 Decl->TypeForDecl = NewType;
5446 return QualType(NewType, 0);
5447 }
5448
5449 llvm::FoldingSetNodeID ID;
5450 TypedefType::Profile(ID, Keyword, Qualifier, Decl,
5451 *TypeMatchesDeclOrNone ? QualType() : UnderlyingType);
5452
5453 llvm::FoldingSetInsertToken Token;
5454 if (FoldingSetPlaceholder<TypedefType> *Placeholder =
5455 TypedefTypes.lookup(ID, Token))
5456 return QualType(Placeholder->getType(), 0);
5457
5458 void *Mem =
5459 Allocate(TypedefType::totalSizeToAlloc<FoldingSetPlaceholder<TypedefType>,
5461 1, !!Qualifier, !*TypeMatchesDeclOrNone),
5462 alignof(TypedefType));
5463 auto *NewType =
5464 new (Mem) TypedefType(Type::Typedef, Keyword, Qualifier, Decl,
5465 UnderlyingType, !*TypeMatchesDeclOrNone);
5466 auto *Placeholder = new (NewType->getFoldingSetPlaceholder())
5468 TypedefTypes.insert(Placeholder, Token);
5469 Types.push_back(NewType);
5470 return QualType(NewType, 0);
5471}
5472
5474 NestedNameSpecifier Qualifier,
5475 const UsingShadowDecl *D,
5476 QualType UnderlyingType) const {
5477 // FIXME: This is expensive to compute every time!
5478 if (UnderlyingType.isNull()) {
5479 const auto *UD = cast<UsingDecl>(D->getIntroducer());
5480 UnderlyingType =
5483 UD->getQualifier(), cast<TypeDecl>(D->getTargetDecl()));
5484 }
5485
5486 llvm::FoldingSetNodeID ID;
5487 UsingType::Profile(ID, Keyword, Qualifier, D, UnderlyingType);
5488
5489 llvm::FoldingSetInsertToken Token;
5490 if (const UsingType *T = UsingTypes.lookup(ID, Token))
5491 return QualType(T, 0);
5492
5493 assert(!UnderlyingType.hasLocalQualifiers());
5494
5495 assert(
5497 UnderlyingType));
5498
5499 void *Mem =
5500 Allocate(UsingType::totalSizeToAlloc<NestedNameSpecifier>(!!Qualifier),
5501 alignof(UsingType));
5502 UsingType *T = new (Mem) UsingType(Keyword, Qualifier, D, UnderlyingType);
5503 Types.push_back(T);
5504 UsingTypes.insert(T, Token);
5505 return QualType(T, 0);
5506}
5507
5508TagType *ASTContext::getTagTypeInternal(ElaboratedTypeKeyword Keyword,
5509 NestedNameSpecifier Qualifier,
5510 const TagDecl *TD, bool OwnsTag,
5511 bool IsInjected,
5512 const Type *CanonicalType,
5513 bool WithFoldingSetNode) const {
5514 auto [TC, Size] = [&] {
5515 switch (TD->getDeclKind()) {
5516 case Decl::Enum:
5517 static_assert(alignof(EnumType) == alignof(TagType));
5518 return std::make_tuple(Type::Enum, sizeof(EnumType));
5519 case Decl::ClassTemplatePartialSpecialization:
5520 case Decl::ClassTemplateSpecialization:
5521 case Decl::CXXRecord:
5522 static_assert(alignof(RecordType) == alignof(TagType));
5523 static_assert(alignof(InjectedClassNameType) == alignof(TagType));
5524 if (cast<CXXRecordDecl>(TD)->hasInjectedClassType())
5525 return std::make_tuple(Type::InjectedClassName,
5526 sizeof(InjectedClassNameType));
5527 [[fallthrough]];
5528 case Decl::Record:
5529 return std::make_tuple(Type::Record, sizeof(RecordType));
5530 default:
5531 llvm_unreachable("unexpected decl kind");
5532 }
5533 }();
5534
5535 if (Qualifier) {
5536 static_assert(alignof(NestedNameSpecifier) <= alignof(TagType));
5537 Size = llvm::alignTo(Size, alignof(NestedNameSpecifier)) +
5538 sizeof(NestedNameSpecifier);
5539 }
5540 void *Mem;
5541 if (WithFoldingSetNode) {
5542 // FIXME: It would be more profitable to tail allocate the folding set node
5543 // from the type, instead of the other way around, due to the greater
5544 // alignment requirements of the type. But this makes it harder to deal with
5545 // the different type node sizes. This would require either uniquing from
5546 // different folding sets, or having the folding setaccept a
5547 // contextual parameter which is not fixed at construction.
5548 Mem = Allocate(
5549 sizeof(TagTypeFoldingSetPlaceholder) +
5550 TagTypeFoldingSetPlaceholder::getOffset() + Size,
5551 std::max(alignof(TagTypeFoldingSetPlaceholder), alignof(TagType)));
5552 auto *T = new (Mem) TagTypeFoldingSetPlaceholder();
5553 Mem = T->getTagType();
5554 } else {
5555 Mem = Allocate(Size, alignof(TagType));
5556 }
5557
5558 auto *T = [&, TC = TC]() -> TagType * {
5559 switch (TC) {
5560 case Type::Enum: {
5561 assert(isa<EnumDecl>(TD));
5562 auto *T = new (Mem) EnumType(TC, Keyword, Qualifier, TD, OwnsTag,
5563 IsInjected, CanonicalType);
5564 assert(reinterpret_cast<void *>(T) ==
5565 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5566 "TagType must be the first base of EnumType");
5567 return T;
5568 }
5569 case Type::Record: {
5570 assert(isa<RecordDecl>(TD));
5571 auto *T = new (Mem) RecordType(TC, Keyword, Qualifier, TD, OwnsTag,
5572 IsInjected, CanonicalType);
5573 assert(reinterpret_cast<void *>(T) ==
5574 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5575 "TagType must be the first base of RecordType");
5576 return T;
5577 }
5578 case Type::InjectedClassName: {
5579 auto *T = new (Mem) InjectedClassNameType(Keyword, Qualifier, TD,
5580 IsInjected, CanonicalType);
5581 assert(reinterpret_cast<void *>(T) ==
5582 reinterpret_cast<void *>(static_cast<TagType *>(T)) &&
5583 "TagType must be the first base of InjectedClassNameType");
5584 return T;
5585 }
5586 default:
5587 llvm_unreachable("unexpected type class");
5588 }
5589 }();
5590 assert(T->getKeyword() == Keyword);
5591 assert(T->getQualifier() == Qualifier);
5592 assert(T->getDecl() == TD);
5593 assert(T->isInjected() == IsInjected);
5594 assert(T->isTagOwned() == OwnsTag);
5595 assert((T->isCanonicalUnqualified()
5596 ? QualType()
5597 : T->getCanonicalTypeInternal()) == QualType(CanonicalType, 0));
5598 Types.push_back(T);
5599 return T;
5600}
5601
5602static const TagDecl *getNonInjectedClassName(const TagDecl *TD) {
5603 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD);
5604 RD && RD->isInjectedClassName())
5605 return cast<TagDecl>(RD->getDeclContext());
5606 return TD;
5607}
5608
5611 if (TD->TypeForDecl)
5612 return TD->TypeForDecl->getCanonicalTypeUnqualified();
5613
5614 const Type *CanonicalType = getTagTypeInternal(
5616 /*Qualifier=*/std::nullopt, TD,
5617 /*OwnsTag=*/false, /*IsInjected=*/false, /*CanonicalType=*/nullptr,
5618 /*WithFoldingSetNode=*/false);
5619 TD->TypeForDecl = CanonicalType;
5620 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5621}
5622
5624 NestedNameSpecifier Qualifier,
5625 const TagDecl *TD, bool OwnsTag) const {
5626
5627 const TagDecl *NonInjectedTD = ::getNonInjectedClassName(TD);
5628 bool IsInjected = TD != NonInjectedTD;
5629
5630 ElaboratedTypeKeyword PreferredKeyword =
5633 NonInjectedTD->getTagKind());
5634
5635 if (Keyword == PreferredKeyword && !Qualifier && !OwnsTag) {
5636 if (const Type *T = TD->TypeForDecl; T && !T->isCanonicalUnqualified())
5637 return QualType(T, 0);
5638
5639 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5640 const Type *T =
5641 getTagTypeInternal(Keyword,
5642 /*Qualifier=*/std::nullopt, NonInjectedTD,
5643 /*OwnsTag=*/false, IsInjected, CanonicalType,
5644 /*WithFoldingSetNode=*/false);
5645 TD->TypeForDecl = T;
5646 return QualType(T, 0);
5647 }
5648
5649 llvm::FoldingSetNodeID ID;
5650 TagTypeFoldingSetPlaceholder::Profile(ID, Keyword, Qualifier, NonInjectedTD,
5651 OwnsTag, IsInjected);
5652
5653 llvm::FoldingSetInsertToken Token;
5654 if (TagTypeFoldingSetPlaceholder *T = TagTypes.lookup(ID, Token))
5655 return QualType(T->getTagType(), 0);
5656
5657 const Type *CanonicalType = getCanonicalTagType(NonInjectedTD).getTypePtr();
5658 TagType *T =
5659 getTagTypeInternal(Keyword, Qualifier, NonInjectedTD, OwnsTag, IsInjected,
5660 CanonicalType, /*WithFoldingSetNode=*/true);
5661 TagTypes.insert(TagTypeFoldingSetPlaceholder::fromTagType(T), Token);
5662 return QualType(T, 0);
5663}
5664
5665bool ASTContext::computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits,
5666 unsigned NumPositiveBits,
5667 QualType &BestType,
5668 QualType &BestPromotionType) {
5669 unsigned IntWidth = Target->getIntWidth();
5670 unsigned CharWidth = Target->getCharWidth();
5671 unsigned ShortWidth = Target->getShortWidth();
5672 bool EnumTooLarge = false;
5673 unsigned BestWidth;
5674 if (NumNegativeBits) {
5675 // If there is a negative value, figure out the smallest integer type (of
5676 // int/long/longlong) that fits.
5677 // If it's packed, check also if it fits a char or a short.
5678 if (IsPacked && NumNegativeBits <= CharWidth &&
5679 NumPositiveBits < CharWidth) {
5680 BestType = SignedCharTy;
5681 BestWidth = CharWidth;
5682 } else if (IsPacked && NumNegativeBits <= ShortWidth &&
5683 NumPositiveBits < ShortWidth) {
5684 BestType = ShortTy;
5685 BestWidth = ShortWidth;
5686 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
5687 BestType = IntTy;
5688 BestWidth = IntWidth;
5689 } else {
5690 BestWidth = Target->getLongWidth();
5691
5692 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
5693 BestType = LongTy;
5694 } else {
5695 BestWidth = Target->getLongLongWidth();
5696
5697 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
5698 EnumTooLarge = true;
5699 BestType = LongLongTy;
5700 }
5701 }
5702 BestPromotionType = (BestWidth <= IntWidth ? IntTy : BestType);
5703 } else {
5704 // If there is no negative value, figure out the smallest type that fits
5705 // all of the enumerator values.
5706 // If it's packed, check also if it fits a char or a short.
5707 if (IsPacked && NumPositiveBits <= CharWidth) {
5708 BestType = UnsignedCharTy;
5709 BestPromotionType = IntTy;
5710 BestWidth = CharWidth;
5711 } else if (IsPacked && NumPositiveBits <= ShortWidth) {
5712 BestType = UnsignedShortTy;
5713 BestPromotionType = IntTy;
5714 BestWidth = ShortWidth;
5715 } else if (NumPositiveBits <= IntWidth) {
5716 BestType = UnsignedIntTy;
5717 BestWidth = IntWidth;
5718 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5720 : IntTy;
5721 } else if (NumPositiveBits <= (BestWidth = Target->getLongWidth())) {
5722 BestType = UnsignedLongTy;
5723 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5725 : LongTy;
5726 } else {
5727 BestWidth = Target->getLongLongWidth();
5728 if (NumPositiveBits > BestWidth) {
5729 // This can happen with bit-precise integer types, but those are not
5730 // allowed as the type for an enumerator per C23 6.7.2.2p4 and p12.
5731 // FIXME: GCC uses __int128_t and __uint128_t for cases that fit within
5732 // a 128-bit integer, we should consider doing the same.
5733 EnumTooLarge = true;
5734 }
5735 BestType = UnsignedLongLongTy;
5736 BestPromotionType = (NumPositiveBits == BestWidth || !LangOpts.CPlusPlus)
5738 : LongLongTy;
5739 }
5740 }
5741 return EnumTooLarge;
5742}
5743
5745 assert((T->isIntegralType(*this) || T->isEnumeralType()) &&
5746 "Integral type required!");
5747 unsigned BitWidth = getIntWidth(T);
5748
5749 if (Value.isUnsigned() || Value.isNonNegative()) {
5750 if (T->isSignedIntegerOrEnumerationType())
5751 --BitWidth;
5752 return Value.getActiveBits() <= BitWidth;
5753 }
5754 return Value.getSignificantBits() <= BitWidth;
5755}
5756
5757UnresolvedUsingType *ASTContext::getUnresolvedUsingTypeInternal(
5759 const UnresolvedUsingTypenameDecl *D, llvm::FoldingSetInsertToken Token,
5760 const Type *CanonicalType) const {
5761 void *Mem = Allocate(
5762 UnresolvedUsingType::totalSizeToAlloc<
5764 !!Token, !!Qualifier),
5765 alignof(UnresolvedUsingType));
5766 auto *T = new (Mem) UnresolvedUsingType(Keyword, Qualifier, D, CanonicalType);
5767 if (Token) {
5768 auto *Placeholder = new (T->getFoldingSetPlaceholder())
5770 UnresolvedUsingTypes.insert(Placeholder, Token);
5771 }
5772 Types.push_back(T);
5773 return T;
5774}
5775
5777 const UnresolvedUsingTypenameDecl *D) const {
5778 D = D->getCanonicalDecl();
5779 if (D->TypeForDecl)
5780 return D->TypeForDecl->getCanonicalTypeUnqualified();
5781
5782 const Type *CanonicalType =
5783 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5784 /*Qualifier=*/std::nullopt, D,
5785 /*Token=*/{}, /*CanonicalType=*/nullptr);
5786 D->TypeForDecl = CanonicalType;
5787 return CanQualType::CreateUnsafe(QualType(CanonicalType, 0));
5788}
5789
5792 NestedNameSpecifier Qualifier,
5793 const UnresolvedUsingTypenameDecl *D) const {
5794 if (Keyword == ElaboratedTypeKeyword::None && !Qualifier) {
5795 if (const Type *T = D->TypeForDecl; T && !T->isCanonicalUnqualified())
5796 return QualType(T, 0);
5797
5798 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5799 const Type *T =
5800 getUnresolvedUsingTypeInternal(ElaboratedTypeKeyword::None,
5801 /*Qualifier=*/std::nullopt, D,
5802 /*Token=*/{}, CanonicalType);
5803 D->TypeForDecl = T;
5804 return QualType(T, 0);
5805 }
5806
5807 llvm::FoldingSetNodeID ID;
5808 UnresolvedUsingType::Profile(ID, Keyword, Qualifier, D);
5809
5810 llvm::FoldingSetInsertToken Token;
5812 UnresolvedUsingTypes.lookup(ID, Token))
5813 return QualType(Placeholder->getType(), 0);
5814 assert(Token);
5815
5816 const Type *CanonicalType = getCanonicalUnresolvedUsingType(D).getTypePtr();
5817 const Type *T = getUnresolvedUsingTypeInternal(Keyword, Qualifier, D, Token,
5818 CanonicalType);
5819 return QualType(T, 0);
5820}
5821
5823 QualType modifiedType,
5824 QualType equivalentType,
5825 const Attr *attr) const {
5826 llvm::FoldingSetNodeID id;
5827 AttributedType::Profile(id, *this, attrKind, modifiedType, equivalentType,
5828 attr);
5829
5830 llvm::FoldingSetInsertToken Token;
5831 AttributedType *type = AttributedTypes.lookup(id, Token);
5832 if (type) return QualType(type, 0);
5833
5834 assert(!attr || attr->getKind() == attrKind);
5835
5836 QualType canon = getCanonicalType(equivalentType);
5837 type = new (*this, alignof(AttributedType))
5838 AttributedType(canon, attrKind, attr, modifiedType, equivalentType);
5839
5840 Types.push_back(type);
5841 AttributedTypes.insert(type, Token);
5842
5843 return QualType(type, 0);
5844}
5845
5847 QualType equivalentType) const {
5848 return getAttributedType(attr->getKind(), modifiedType, equivalentType, attr);
5849}
5850
5852 QualType modifiedType,
5853 QualType equivalentType) const {
5854 switch (nullability) {
5856 return getAttributedType(attr::TypeNonNull, modifiedType, equivalentType);
5857
5859 return getAttributedType(attr::TypeNullable, modifiedType, equivalentType);
5860
5862 return getAttributedType(attr::TypeNullableResult, modifiedType,
5863 equivalentType);
5864
5866 return getAttributedType(attr::TypeNullUnspecified, modifiedType,
5867 equivalentType);
5868 }
5869
5870 llvm_unreachable("Unknown nullability kind");
5871}
5872
5873QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
5874 QualType Wrapped) const {
5875 llvm::FoldingSetNodeID ID;
5876 BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
5877
5878 llvm::FoldingSetInsertToken Token;
5879 BTFTagAttributedType *Ty = BTFTagAttributedTypes.lookup(ID, Token);
5880 if (Ty)
5881 return QualType(Ty, 0);
5882
5883 QualType Canon = getCanonicalType(Wrapped);
5884 Ty = new (*this, alignof(BTFTagAttributedType))
5885 BTFTagAttributedType(Canon, Wrapped, BTFAttr);
5886
5887 Types.push_back(Ty);
5888 BTFTagAttributedTypes.insert(Ty, Token);
5889
5890 return QualType(Ty, 0);
5891}
5892
5894 QualType Underlying) const {
5895 const IdentifierInfo *II = Attr->getBehaviorKind();
5896 StringRef IdentName = II->getName();
5897 OverflowBehaviorType::OverflowBehaviorKind Kind;
5898 if (IdentName == "wrap") {
5899 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
5900 } else if (IdentName == "trap") {
5901 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
5902 } else {
5903 return Underlying;
5904 }
5905
5906 return getOverflowBehaviorType(Kind, Underlying);
5907}
5908
5910 OverflowBehaviorType::OverflowBehaviorKind Kind,
5911 QualType Underlying) const {
5912 assert(!Underlying->isOverflowBehaviorType() &&
5913 "Cannot have underlying types that are themselves OBTs");
5914
5915 llvm::FoldingSetInsertToken Token;
5916 if (OverflowBehaviorType *OBT =
5917 OverflowBehaviorTypes.lookup({Underlying, Kind}, Token)) {
5918 return QualType(OBT, 0);
5919 }
5920
5921 QualType Canonical;
5922 if (!Underlying.isCanonical() || Underlying.hasLocalQualifiers()) {
5923 SplitQualType canonSplit = getCanonicalType(Underlying).split();
5924 Canonical = getOverflowBehaviorType(Kind, QualType(canonSplit.Ty, 0));
5925 Canonical = getQualifiedType(Canonical, canonSplit.Quals);
5926 assert(!OverflowBehaviorTypes.lookup({Underlying, Kind}, Token) &&
5927 "Shouldn't be in the map");
5928 }
5929
5930 OverflowBehaviorType *Ty = new (*this, alignof(OverflowBehaviorType))
5931 OverflowBehaviorType(*this, Canonical, Underlying, Kind);
5932
5933 Types.push_back(Ty);
5934 OverflowBehaviorTypes.insert(Ty, Token);
5935 return QualType(Ty, 0);
5936}
5937
5939 QualType Wrapped, QualType Contained,
5940 const HLSLAttributedResourceType::Attributes &Attrs) {
5941
5942 llvm::FoldingSetNodeID ID;
5943 HLSLAttributedResourceType::Profile(ID, *this, Wrapped, Contained, Attrs);
5944
5945 llvm::FoldingSetInsertToken Token;
5946 HLSLAttributedResourceType *Ty =
5947 HLSLAttributedResourceTypes.lookup(ID, Token);
5948 if (Ty)
5949 return QualType(Ty, 0);
5950
5951 Ty = new (*this, alignof(HLSLAttributedResourceType))
5952 HLSLAttributedResourceType(Wrapped, Contained, Attrs);
5953
5954 Types.push_back(Ty);
5955 HLSLAttributedResourceTypes.insert(Ty, Token);
5956
5957 return QualType(Ty, 0);
5958}
5959
5960QualType ASTContext::getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size,
5961 uint32_t Alignment,
5962 ArrayRef<SpirvOperand> Operands) {
5963 llvm::FoldingSetNodeID ID;
5964 HLSLInlineSpirvType::Profile(ID, Opcode, Size, Alignment, Operands);
5965
5966 llvm::FoldingSetInsertToken Token;
5967 HLSLInlineSpirvType *Ty = HLSLInlineSpirvTypes.lookup(ID, Token);
5968 if (Ty)
5969 return QualType(Ty, 0);
5970
5971 void *Mem = Allocate(
5972 HLSLInlineSpirvType::totalSizeToAlloc<SpirvOperand>(Operands.size()),
5973 alignof(HLSLInlineSpirvType));
5974
5975 Ty = new (Mem) HLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
5976
5977 Types.push_back(Ty);
5978 HLSLInlineSpirvTypes.insert(Ty, Token);
5979
5980 return QualType(Ty, 0);
5981}
5982
5983/// Retrieve a substitution-result type.
5985 Decl *AssociatedDecl,
5986 unsigned Index,
5988 bool Final) const {
5989 auto Key =
5990 std::make_tuple(Replacement, AssociatedDecl, Index,
5991 PackIndex.toInternalRepresentation(), unsigned(Final));
5992 llvm::FoldingSetInsertToken Token;
5993 SubstTemplateTypeParmType *SubstParm =
5994 SubstTemplateTypeParmTypes.lookup(Key, Token);
5995
5996 if (!SubstParm) {
5997 void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
5998 !Replacement.isCanonical()),
5999 alignof(SubstTemplateTypeParmType));
6000 SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
6001 Index, PackIndex, Final);
6002 Types.push_back(SubstParm);
6003 SubstTemplateTypeParmTypes.insert(SubstParm, Token);
6004 }
6005
6006 return QualType(SubstParm, 0);
6007}
6008
6011 unsigned Index, bool Final,
6012 const TemplateArgument &ArgPack) {
6013#ifndef NDEBUG
6014 for (const auto &P : ArgPack.pack_elements())
6015 assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
6016#endif
6017
6018 llvm::FoldingSetNodeID ID;
6019 SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
6020 ArgPack);
6021 llvm::FoldingSetInsertToken Token;
6022 if (SubstTemplateTypeParmPackType *SubstParm =
6023 SubstTemplateTypeParmPackTypes.lookup(ID, Token))
6024 return QualType(SubstParm, 0);
6025
6026 QualType Canon;
6027 {
6028 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6029 if (!AssociatedDecl->isCanonicalDecl() ||
6030 !CanonArgPack.structurallyEquals(ArgPack)) {
6032 AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
6033 [[maybe_unused]] const auto *Nothing =
6034 SubstTemplateTypeParmPackTypes.lookup(ID, Token);
6035 assert(!Nothing);
6036 }
6037 }
6038
6039 auto *SubstParm = new (*this, alignof(SubstTemplateTypeParmPackType))
6040 SubstTemplateTypeParmPackType(Canon, AssociatedDecl, Index, Final,
6041 ArgPack);
6042 Types.push_back(SubstParm);
6043 SubstTemplateTypeParmPackTypes.insert(SubstParm, Token);
6044 return QualType(SubstParm, 0);
6045}
6046
6049 assert(llvm::all_of(ArgPack.pack_elements(),
6050 [](const auto &P) {
6051 return P.getKind() == TemplateArgument::Type;
6052 }) &&
6053 "Pack contains a non-type");
6054
6055 llvm::FoldingSetNodeID ID;
6056 SubstBuiltinTemplatePackType::Profile(ID, ArgPack);
6057
6058 llvm::FoldingSetInsertToken Token;
6059 if (auto *T = SubstBuiltinTemplatePackTypes.lookup(ID, Token))
6060 return QualType(T, 0);
6061
6062 QualType Canon;
6063 TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
6064 if (!CanonArgPack.structurallyEquals(ArgPack)) {
6065 Canon = getSubstBuiltinTemplatePack(CanonArgPack);
6066 // Refresh Token, in case the recursive call above caused rehashing,
6067 // which would invalidate the bucket pointer.
6068 [[maybe_unused]] const auto *Nothing =
6069 SubstBuiltinTemplatePackTypes.lookup(ID, Token);
6070 assert(!Nothing);
6071 }
6072
6073 auto *PackType = new (*this, alignof(SubstBuiltinTemplatePackType))
6074 SubstBuiltinTemplatePackType(Canon, ArgPack);
6075 Types.push_back(PackType);
6076 SubstBuiltinTemplatePackTypes.insert(PackType, Token);
6077 return QualType(PackType, 0);
6078}
6079
6080/// Retrieve the template type parameter type for a template
6081/// parameter or parameter pack with the given depth, index, and (optionally)
6082/// name.
6084ASTContext::getTemplateTypeParmType(int Depth, int Index, bool ParameterPack,
6085 TemplateTypeParmDecl *TTPDecl) const {
6086 assert(Depth >= 0 && "Depth must be non-negative");
6087 assert(Index >= 0 && "Index must be non-negative");
6088
6089 auto Key = std::make_tuple(unsigned(Depth), unsigned(Index),
6090 unsigned(ParameterPack), TTPDecl);
6091 llvm::FoldingSetInsertToken Token;
6092 TemplateTypeParmType *TypeParm = TemplateTypeParmTypes.lookup(Key, Token);
6093
6094 if (TypeParm)
6095 return QualType(TypeParm, 0);
6096
6097 if (TTPDecl) {
6098 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
6099 TypeParm = new (*this, alignof(TemplateTypeParmType))
6100 TemplateTypeParmType(Depth, Index, ParameterPack, TTPDecl, Canon);
6101 } else
6102 TypeParm = new (*this, alignof(TemplateTypeParmType)) TemplateTypeParmType(
6103 Depth, Index, ParameterPack, /*TTPDecl=*/nullptr, /*Canon=*/QualType());
6104
6105 Types.push_back(TypeParm);
6106 TemplateTypeParmTypes.insert(TypeParm, Token);
6107
6108 return QualType(TypeParm, 0);
6109}
6110
6113 switch (Keyword) {
6114 // These are just themselves.
6120 return Keyword;
6121
6122 // These are equivalent.
6125
6126 // These are functionally equivalent, so relying on their equivalence is
6127 // IFNDR. By making them equivalent, we disallow overloading, which at least
6128 // can produce a diagnostic.
6131 }
6132 llvm_unreachable("unexpected keyword kind");
6133}
6134
6136 ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc,
6137 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc,
6138 TemplateName Name, SourceLocation NameLoc,
6139 const TemplateArgumentListInfo &SpecifiedArgs,
6140 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6142 Keyword, Name, SpecifiedArgs.arguments(), CanonicalArgs, Underlying);
6143
6146 ElaboratedKeywordLoc, QualifierLoc, TemplateKeywordLoc, NameLoc,
6147 SpecifiedArgs);
6148 return TSI;
6149}
6150
6153 ArrayRef<TemplateArgumentLoc> SpecifiedArgs,
6154 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6155 SmallVector<TemplateArgument, 4> SpecifiedArgVec;
6156 SpecifiedArgVec.reserve(SpecifiedArgs.size());
6157 for (const TemplateArgumentLoc &Arg : SpecifiedArgs)
6158 SpecifiedArgVec.push_back(Arg.getArgument());
6159
6160 return getTemplateSpecializationType(Keyword, Template, SpecifiedArgVec,
6161 CanonicalArgs, Underlying);
6162}
6163
6164[[maybe_unused]] static bool
6166 for (const TemplateArgument &Arg : Args)
6167 if (Arg.isPackExpansion())
6168 return true;
6169 return false;
6170}
6171
6174 ArrayRef<TemplateArgument> Args) const {
6175 assert(Template ==
6176 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true));
6178 Template.getAsDependentTemplateName()));
6179#ifndef NDEBUG
6180 for (const auto &Arg : Args)
6181 assert(Arg.structurallyEquals(getCanonicalTemplateArgument(Arg)));
6182#endif
6183
6184 llvm::FoldingSetNodeID ID;
6185 TemplateSpecializationType::Profile(ID, Keyword, Template, Args, QualType(),
6186 *this);
6187 llvm::FoldingSetInsertToken Token;
6188 if (auto *T = TemplateSpecializationTypes.lookup(ID, Token))
6189 return QualType(T, 0);
6190
6191 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6192 sizeof(TemplateArgument) * Args.size(),
6193 alignof(TemplateSpecializationType));
6194 auto *Spec =
6195 new (Mem) TemplateSpecializationType(Keyword, Template,
6196 /*IsAlias=*/false, Args, QualType());
6197 assert(Spec->isDependentType() &&
6198 "canonical template specialization must be dependent");
6199 Types.push_back(Spec);
6200 TemplateSpecializationTypes.insert(Spec, Token);
6201 return QualType(Spec, 0);
6202}
6203
6206 ArrayRef<TemplateArgument> SpecifiedArgs,
6207 ArrayRef<TemplateArgument> CanonicalArgs, QualType Underlying) const {
6208 const auto *TD = Template.getAsTemplateDecl(/*IgnoreDeduced=*/true);
6209 bool IsTypeAlias = TD && TD->isTypeAlias();
6210 if (Underlying.isNull()) {
6211 TemplateName CanonTemplate =
6212 getCanonicalTemplateName(Template, /*IgnoreDeduced=*/true);
6213 ElaboratedTypeKeyword CanonKeyword =
6214 CanonTemplate.getAsDependentTemplateName()
6217 bool NonCanonical = Template != CanonTemplate || Keyword != CanonKeyword;
6219 if (CanonicalArgs.empty()) {
6220 CanonArgsVec = SmallVector<TemplateArgument, 4>(SpecifiedArgs);
6221 NonCanonical |= canonicalizeTemplateArguments(CanonArgsVec);
6222 CanonicalArgs = CanonArgsVec;
6223 } else {
6224 NonCanonical |= !llvm::equal(
6225 SpecifiedArgs, CanonicalArgs,
6226 [](const TemplateArgument &A, const TemplateArgument &B) {
6227 return A.structurallyEquals(B);
6228 });
6229 }
6230
6231 // We can get here with an alias template when the specialization
6232 // contains a pack expansion that does not match up with a parameter
6233 // pack, or a builtin template which cannot be resolved due to dependency.
6234 assert((!isa_and_nonnull<TypeAliasTemplateDecl>(TD) ||
6235 hasAnyPackExpansions(CanonicalArgs)) &&
6236 "Caller must compute aliased type");
6237 IsTypeAlias = false;
6238
6240 CanonKeyword, CanonTemplate, CanonicalArgs);
6241 if (!NonCanonical)
6242 return Underlying;
6243 }
6244 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
6245 sizeof(TemplateArgument) * SpecifiedArgs.size() +
6246 (IsTypeAlias ? sizeof(QualType) : 0),
6247 alignof(TemplateSpecializationType));
6248 auto *Spec = new (Mem) TemplateSpecializationType(
6249 Keyword, Template, IsTypeAlias, SpecifiedArgs, Underlying);
6250 Types.push_back(Spec);
6251 return QualType(Spec, 0);
6252}
6253
6256 llvm::FoldingSetInsertToken Token;
6257 ParenType *T = ParenTypes.lookup(InnerType, Token);
6258 if (T)
6259 return QualType(T, 0);
6260
6261 QualType Canon = InnerType;
6262 if (!Canon.isCanonical()) {
6263 Canon = getCanonicalType(InnerType);
6264 assert(!ParenTypes.lookup(InnerType, Token) &&
6265 "Paren canonical type broken");
6266 }
6267
6268 T = new (*this, alignof(ParenType)) ParenType(InnerType, Canon);
6269 Types.push_back(T);
6270 ParenTypes.insert(T, Token);
6271 return QualType(T, 0);
6272}
6273
6276 const IdentifierInfo *MacroII) const {
6277 QualType Canon = UnderlyingTy;
6278 if (!Canon.isCanonical())
6279 Canon = getCanonicalType(UnderlyingTy);
6280
6281 auto *newType = new (*this, alignof(MacroQualifiedType))
6282 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
6283 Types.push_back(newType);
6284 return QualType(newType, 0);
6285}
6286
6289 const IdentifierInfo *Name) const {
6290 llvm::FoldingSetNodeID ID;
6291 DependentNameType::Profile(ID, Keyword, NNS, Name);
6292
6293 llvm::FoldingSetInsertToken Token;
6294 if (DependentNameType *T = DependentNameTypes.lookup(ID, Token))
6295 return QualType(T, 0);
6296
6297 ElaboratedTypeKeyword CanonKeyword =
6299 NestedNameSpecifier CanonNNS = NNS.getCanonical();
6300
6301 QualType Canon;
6302 if (CanonKeyword != Keyword || CanonNNS != NNS) {
6303 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
6304 [[maybe_unused]] DependentNameType *T =
6305 DependentNameTypes.lookup(ID, Token);
6306 assert(!T && "broken canonicalization");
6307 assert(Canon.isCanonical());
6308 }
6309
6310 DependentNameType *T = new (*this, alignof(DependentNameType))
6311 DependentNameType(Keyword, NNS, Name, Canon);
6312 Types.push_back(T);
6313 DependentNameTypes.insert(T, Token);
6314 return QualType(T, 0);
6315}
6316
6318 TemplateArgument Arg;
6319 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6321 if (TTP->isParameterPack())
6322 ArgType = getPackExpansionType(ArgType, std::nullopt);
6323
6325 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6326 QualType T =
6327 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
6328 // For class NTTPs, ensure we include the 'const' so the type matches that
6329 // of a real template argument.
6330 // FIXME: It would be more faithful to model this as something like an
6331 // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
6333 if (T->isRecordType()) {
6334 // C++ [temp.param]p8: An id-expression naming a non-type
6335 // template-parameter of class type T denotes a static storage duration
6336 // object of type const T.
6337 T.addConst();
6338 VK = VK_LValue;
6339 } else {
6340 VK = Expr::getValueKindForType(NTTP->getType());
6341 }
6342 Expr *E = new (*this)
6343 DeclRefExpr(*this, NTTP, /*RefersToEnclosingVariableOrCapture=*/false,
6344 T, VK, NTTP->getLocation());
6345
6346 if (NTTP->isParameterPack())
6347 E = new (*this) PackExpansionExpr(E, NTTP->getLocation(), std::nullopt);
6348 Arg = TemplateArgument(E, /*IsCanonical=*/false);
6349 } else {
6350 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
6352 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
6353 TemplateName(TTP));
6354 if (TTP->isParameterPack())
6355 Arg = TemplateArgument(Name, /*NumExpansions=*/std::nullopt);
6356 else
6357 Arg = TemplateArgument(Name);
6358 }
6359
6360 if (Param->isTemplateParameterPack())
6361 Arg =
6362 TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this), Arg);
6363
6364 return Arg;
6365}
6366
6368 UnsignedOrNone NumExpansions,
6369 bool ExpectPackInType) const {
6370 assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
6371 "Pack expansions must expand one or more parameter packs");
6372
6373 auto Key = std::make_pair(Pattern, NumExpansions.toInternalRepresentation());
6374
6375 llvm::FoldingSetInsertToken Token;
6376 PackExpansionType *T = PackExpansionTypes.lookup(Key, Token);
6377 if (T)
6378 return QualType(T, 0);
6379
6380 QualType Canon;
6381 if (!Pattern.isCanonical()) {
6382 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
6383 /*ExpectPackInType=*/false);
6384
6385 // Find the insert position again, in case we inserted an element into
6386 // PackExpansionTypes and invalidated our insert position.
6387 PackExpansionTypes.lookup(Key, Token);
6388 }
6389
6390 T = new (*this, alignof(PackExpansionType))
6391 PackExpansionType(Pattern, Canon, NumExpansions);
6392 Types.push_back(T);
6393 PackExpansionTypes.insert(T, Token);
6394 return QualType(T, 0);
6395}
6396
6397/// CmpProtocolNames - Comparison predicate for sorting protocols
6398/// alphabetically.
6399static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
6400 ObjCProtocolDecl *const *RHS) {
6401 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
6402}
6403
6405 if (Protocols.empty()) return true;
6406
6407 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
6408 return false;
6409
6410 for (unsigned i = 1; i != Protocols.size(); ++i)
6411 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
6412 Protocols[i]->getCanonicalDecl() != Protocols[i])
6413 return false;
6414 return true;
6415}
6416
6417static void
6419 // Sort protocols, keyed by name.
6420 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
6421
6422 // Canonicalize.
6423 for (ObjCProtocolDecl *&P : Protocols)
6424 P = P->getCanonicalDecl();
6425
6426 // Remove duplicates.
6427 auto ProtocolsEnd = llvm::unique(Protocols);
6428 Protocols.erase(ProtocolsEnd, Protocols.end());
6429}
6430
6432 ObjCProtocolDecl * const *Protocols,
6433 unsigned NumProtocols) const {
6434 return getObjCObjectType(BaseType, {}, ArrayRef(Protocols, NumProtocols),
6435 /*isKindOf=*/false);
6436}
6437
6439 QualType baseType,
6440 ArrayRef<QualType> typeArgs,
6442 bool isKindOf) const {
6443 // If the base type is an interface and there aren't any protocols or
6444 // type arguments to add, then the interface type will do just fine.
6445 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
6446 isa<ObjCInterfaceType>(baseType))
6447 return baseType;
6448
6449 // Look in the folding set for an existing type.
6450 llvm::FoldingSetNodeID ID;
6451 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
6452 llvm::FoldingSetInsertToken Token;
6453 if (ObjCObjectType *QT = ObjCObjectTypes.lookup(ID, Token))
6454 return QualType(QT, 0);
6455
6456 // Determine the type arguments to be used for canonicalization,
6457 // which may be explicitly specified here or written on the base
6458 // type.
6459 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
6460 if (effectiveTypeArgs.empty()) {
6461 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
6462 effectiveTypeArgs = baseObject->getTypeArgs();
6463 }
6464
6465 // Build the canonical type, which has the canonical base type and a
6466 // sorted-and-uniqued list of protocols and the type arguments
6467 // canonicalized.
6468 QualType canonical;
6469 bool typeArgsAreCanonical = llvm::all_of(
6470 effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
6471 bool protocolsSorted = areSortedAndUniqued(protocols);
6472 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
6473 // Determine the canonical type arguments.
6474 ArrayRef<QualType> canonTypeArgs;
6475 SmallVector<QualType, 4> canonTypeArgsVec;
6476 if (!typeArgsAreCanonical) {
6477 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
6478 for (auto typeArg : effectiveTypeArgs)
6479 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
6480 canonTypeArgs = canonTypeArgsVec;
6481 } else {
6482 canonTypeArgs = effectiveTypeArgs;
6483 }
6484
6485 ArrayRef<ObjCProtocolDecl *> canonProtocols;
6486 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
6487 if (!protocolsSorted) {
6488 canonProtocolsVec.append(protocols.begin(), protocols.end());
6489 SortAndUniqueProtocols(canonProtocolsVec);
6490 canonProtocols = canonProtocolsVec;
6491 } else {
6492 canonProtocols = protocols;
6493 }
6494
6495 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
6496 canonProtocols, isKindOf);
6497
6498 // Regenerate Token.
6499 ObjCObjectTypes.lookup(ID, Token);
6500 }
6501
6502 unsigned size = sizeof(ObjCObjectTypeImpl);
6503 size += typeArgs.size() * sizeof(QualType);
6504 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6505 void *mem = Allocate(size, alignof(ObjCObjectTypeImpl));
6506 auto *T =
6507 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
6508 isKindOf);
6509
6510 Types.push_back(T);
6511 ObjCObjectTypes.insert(T, Token);
6512 return QualType(T, 0);
6513}
6514
6515/// Apply Objective-C protocol qualifiers to the given type.
6516/// If this is for the canonical type of a type parameter, we can apply
6517/// protocol qualifiers on the ObjCObjectPointerType.
6520 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
6521 bool allowOnPointerType) const {
6522 hasError = false;
6523
6524 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
6525 return getObjCTypeParamType(objT->getDecl(), protocols);
6526 }
6527
6528 // Apply protocol qualifiers to ObjCObjectPointerType.
6529 if (allowOnPointerType) {
6530 if (const auto *objPtr =
6531 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
6532 const ObjCObjectType *objT = objPtr->getObjectType();
6533 // Merge protocol lists and construct ObjCObjectType.
6535 protocolsVec.append(objT->qual_begin(),
6536 objT->qual_end());
6537 protocolsVec.append(protocols.begin(), protocols.end());
6538 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
6540 objT->getBaseType(),
6541 objT->getTypeArgsAsWritten(),
6542 protocols,
6543 objT->isKindOfTypeAsWritten());
6545 }
6546 }
6547
6548 // Apply protocol qualifiers to ObjCObjectType.
6549 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
6550 // FIXME: Check for protocols to which the class type is already
6551 // known to conform.
6552
6553 return getObjCObjectType(objT->getBaseType(),
6554 objT->getTypeArgsAsWritten(),
6555 protocols,
6556 objT->isKindOfTypeAsWritten());
6557 }
6558
6559 // If the canonical type is ObjCObjectType, ...
6560 if (type->isObjCObjectType()) {
6561 // Silently overwrite any existing protocol qualifiers.
6562 // TODO: determine whether that's the right thing to do.
6563
6564 // FIXME: Check for protocols to which the class type is already
6565 // known to conform.
6566 return getObjCObjectType(type, {}, protocols, false);
6567 }
6568
6569 // id<protocol-list>
6570 if (type->isObjCIdType()) {
6571 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6572 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
6573 objPtr->isKindOfType());
6575 }
6576
6577 // Class<protocol-list>
6578 if (type->isObjCClassType()) {
6579 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
6580 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
6581 objPtr->isKindOfType());
6583 }
6584
6585 hasError = true;
6586 return type;
6587}
6588
6591 ArrayRef<ObjCProtocolDecl *> protocols) const {
6592 // We canonicalize to the underlying type.
6593 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
6594 if (!protocols.empty()) {
6595 // Apply the protocol qualifers.
6596 bool hasError;
6598 Canonical, protocols, hasError, true /*allowOnPointerType*/));
6599 assert(!hasError && "Error when apply protocol qualifier to bound type");
6600 }
6601
6602 // Key on the canonical type the node is constructed with, which is what
6603 // Profile() reports; the decl's underlying type can be updated later.
6604 auto Key = std::make_tuple(Decl, Canonical, protocols);
6605 llvm::FoldingSetInsertToken Token;
6606 if (ObjCTypeParamType *TypeParam = ObjCTypeParamTypes.lookup(Key, Token))
6607 return QualType(TypeParam, 0);
6608
6609 unsigned size = sizeof(ObjCTypeParamType);
6610 size += protocols.size() * sizeof(ObjCProtocolDecl *);
6611 void *mem = Allocate(size, alignof(ObjCTypeParamType));
6612 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
6613
6614 Types.push_back(newType);
6615 ObjCTypeParamTypes.insert(newType, Token);
6616 return QualType(newType, 0);
6617}
6618
6620 ObjCTypeParamDecl *New) const {
6621 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
6622 // Update TypeForDecl after updating TypeSourceInfo.
6623 auto *NewTypeParamTy = cast<ObjCTypeParamType>(New->TypeForDecl);
6625 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
6626 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
6627 New->TypeForDecl = UpdatedTy.getTypePtr();
6628}
6629
6630/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
6631/// protocol list adopt all protocols in QT's qualified-id protocol
6632/// list.
6634 ObjCInterfaceDecl *IC) {
6635 if (!QT->isObjCQualifiedIdType())
6636 return false;
6637
6638 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
6639 // If both the right and left sides have qualifiers.
6640 for (auto *Proto : OPT->quals()) {
6641 if (!IC->ClassImplementsProtocol(Proto, false))
6642 return false;
6643 }
6644 return true;
6645 }
6646 return false;
6647}
6648
6649/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
6650/// QT's qualified-id protocol list adopt all protocols in IDecl's list
6651/// of protocols.
6653 ObjCInterfaceDecl *IDecl) {
6654 if (!QT->isObjCQualifiedIdType())
6655 return false;
6656 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
6657 if (!OPT)
6658 return false;
6659 if (!IDecl->hasDefinition())
6660 return false;
6662 CollectInheritedProtocols(IDecl, InheritedProtocols);
6663 if (InheritedProtocols.empty())
6664 return false;
6665 // Check that if every protocol in list of id<plist> conforms to a protocol
6666 // of IDecl's, then bridge casting is ok.
6667 bool Conforms = false;
6668 for (auto *Proto : OPT->quals()) {
6669 Conforms = false;
6670 for (auto *PI : InheritedProtocols) {
6671 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
6672 Conforms = true;
6673 break;
6674 }
6675 }
6676 if (!Conforms)
6677 break;
6678 }
6679 if (Conforms)
6680 return true;
6681
6682 for (auto *PI : InheritedProtocols) {
6683 // If both the right and left sides have qualifiers.
6684 bool Adopts = false;
6685 for (auto *Proto : OPT->quals()) {
6686 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
6687 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
6688 break;
6689 }
6690 if (!Adopts)
6691 return false;
6692 }
6693 return true;
6694}
6695
6696/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
6697/// the given object type.
6699 llvm::FoldingSetInsertToken Token;
6700 if (ObjCObjectPointerType *QT = ObjCObjectPointerTypes.lookup(ObjectT, Token))
6701 return QualType(QT, 0);
6702
6703 // Find the canonical object type.
6704 QualType Canonical;
6705 if (!ObjectT.isCanonical())
6706 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
6707
6708 // No match.
6709 void *Mem =
6711 auto *QType =
6712 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
6713
6714 Types.push_back(QType);
6715 ObjCObjectPointerTypes.insert(QType, Token);
6716 return QualType(QType, 0);
6717}
6718
6719/// getObjCInterfaceType - Return the unique reference to the type for the
6720/// specified ObjC interface decl. The list of protocols is optional.
6722 ObjCInterfaceDecl *PrevDecl) const {
6723 if (Decl->TypeForDecl)
6724 return QualType(Decl->TypeForDecl, 0);
6725
6726 if (PrevDecl) {
6727 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
6728 Decl->TypeForDecl = PrevDecl->TypeForDecl;
6729 return QualType(PrevDecl->TypeForDecl, 0);
6730 }
6731
6732 // Prefer the definition, if there is one.
6733 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
6734 Decl = Def;
6735
6736 void *Mem = Allocate(sizeof(ObjCInterfaceType), alignof(ObjCInterfaceType));
6737 auto *T = new (Mem) ObjCInterfaceType(Decl);
6738 Decl->TypeForDecl = T;
6739 Types.push_back(T);
6740 return QualType(T, 0);
6741}
6742
6743/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
6744/// TypeOfExprType AST's (since expression's are never shared). For example,
6745/// multiple declarations that refer to "typeof(x)" all contain different
6746/// DeclRefExpr's. This doesn't effect the type checker, since it operates
6747/// on canonical type's (which are always unique).
6749 TypeOfExprType *toe;
6750 if (tofExpr->isTypeDependent()) {
6751 llvm::FoldingSetNodeID ID;
6752 DependentTypeOfExprType::Profile(ID, *this, tofExpr,
6753 Kind == TypeOfKind::Unqualified);
6754
6755 llvm::FoldingSetInsertToken Token;
6756 DependentTypeOfExprType *Canon = DependentTypeOfExprTypes.lookup(ID, Token);
6757 if (Canon) {
6758 // We already have a "canonical" version of an identical, dependent
6759 // typeof(expr) type. Use that as our canonical type.
6760 toe = new (*this, alignof(TypeOfExprType)) TypeOfExprType(
6761 *this, tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
6762 } else {
6763 // Build a new, canonical typeof(expr) type.
6764 Canon = new (*this, alignof(DependentTypeOfExprType))
6765 DependentTypeOfExprType(*this, tofExpr, Kind);
6766 DependentTypeOfExprTypes.insert(Canon, Token);
6767 toe = Canon;
6768 }
6769 } else {
6770 QualType Canonical = getCanonicalType(tofExpr->getType());
6771 toe = new (*this, alignof(TypeOfExprType))
6772 TypeOfExprType(*this, tofExpr, Kind, Canonical);
6773 }
6774 Types.push_back(toe);
6775 return QualType(toe, 0);
6776}
6777
6778/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
6779/// TypeOfType nodes. The only motivation to unique these nodes would be
6780/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
6781/// an issue. This doesn't affect the type checker, since it operates
6782/// on canonical types (which are always unique).
6784 QualType Canonical = getCanonicalType(tofType);
6785 auto *tot = new (*this, alignof(TypeOfType))
6786 TypeOfType(*this, tofType, Canonical, Kind);
6787 Types.push_back(tot);
6788 return QualType(tot, 0);
6789}
6790
6791/// getReferenceQualifiedType - Given an expr, will return the type for
6792/// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
6793/// and class member access into account.
6795 // C++11 [dcl.type.simple]p4:
6796 // [...]
6797 QualType T = E->getType();
6798 switch (E->getValueKind()) {
6799 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6800 // type of e;
6801 case VK_XValue:
6802 return getRValueReferenceType(T);
6803 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6804 // type of e;
6805 case VK_LValue:
6806 return getLValueReferenceType(T);
6807 // - otherwise, decltype(e) is the type of e.
6808 case VK_PRValue:
6809 return T;
6810 }
6811 llvm_unreachable("Unknown value kind");
6812}
6813
6814/// Unlike many "get<Type>" functions, we don't unique DecltypeType
6815/// nodes. This would never be helpful, since each such type has its own
6816/// expression, and would not give a significant memory saving, since there
6817/// is an Expr tree under each such type.
6819 // C++11 [temp.type]p2:
6820 // If an expression e involves a template parameter, decltype(e) denotes a
6821 // unique dependent type. Two such decltype-specifiers refer to the same
6822 // type only if their expressions are equivalent (14.5.6.1).
6823 QualType CanonType;
6824 if (!E->isInstantiationDependent()) {
6825 CanonType = getCanonicalType(UnderlyingType);
6826 } else if (!UnderlyingType.isNull()) {
6827 CanonType = getDecltypeType(E, QualType());
6828 } else {
6829 llvm::FoldingSetNodeID ID;
6830 DependentDecltypeType::Profile(ID, *this, E);
6831
6832 llvm::FoldingSetInsertToken Token;
6833 if (DependentDecltypeType *Canon = DependentDecltypeTypes.lookup(ID, Token))
6834 return QualType(Canon, 0);
6835
6836 // Build a new, canonical decltype(expr) type.
6837 auto *DT =
6838 new (*this, alignof(DependentDecltypeType)) DependentDecltypeType(E);
6839 DependentDecltypeTypes.insert(DT, Token);
6840 Types.push_back(DT);
6841 return QualType(DT, 0);
6842 }
6843 auto *DT = new (*this, alignof(DecltypeType))
6844 DecltypeType(E, UnderlyingType, CanonType);
6845 Types.push_back(DT);
6846 return QualType(DT, 0);
6847}
6848
6850 bool FullySubstituted,
6851 ArrayRef<QualType> Expansions,
6852 UnsignedOrNone Index) const {
6853 QualType Canonical;
6854 if (FullySubstituted && Index) {
6855 Canonical = getCanonicalType(Expansions[*Index]);
6856 } else {
6857 llvm::FoldingSetNodeID ID;
6858 PackIndexingType::Profile(ID, *this, Pattern.getCanonicalType(), IndexExpr,
6859 FullySubstituted, Expansions);
6860 llvm::FoldingSetInsertToken Token;
6861 PackIndexingType *Canon = DependentPackIndexingTypes.lookup(ID, Token);
6862 if (!Canon) {
6863 void *Mem = Allocate(
6864 PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6866 Canon =
6867 new (Mem) PackIndexingType(QualType(), Pattern.getCanonicalType(),
6868 IndexExpr, FullySubstituted, Expansions);
6869 DependentPackIndexingTypes.insert(Canon, Token);
6870 }
6871 Canonical = QualType(Canon, 0);
6872 }
6873
6874 void *Mem =
6875 Allocate(PackIndexingType::totalSizeToAlloc<QualType>(Expansions.size()),
6877 auto *T = new (Mem) PackIndexingType(Canonical, Pattern, IndexExpr,
6878 FullySubstituted, Expansions);
6879 Types.push_back(T);
6880 return QualType(T, 0);
6881}
6882
6883/// getUnaryTransformationType - We don't unique these, since the memory
6884/// savings are minimal and these are rare.
6887 UnaryTransformType::UTTKind Kind) const {
6888 // Clear UnderlyingType for a dependent base before building the ID: that is
6889 // what the node is constructed with, and what Profile() reports.
6890 if (BaseType->isDependentType()) {
6891 assert(UnderlyingType.isNull() || BaseType == UnderlyingType);
6892 UnderlyingType = QualType();
6893 }
6894
6895 auto Key = std::make_tuple(BaseType, UnderlyingType, Kind);
6896
6897 llvm::FoldingSetInsertToken Token;
6898 if (UnaryTransformType *UT = UnaryTransformTypes.lookup(Key, Token))
6899 return QualType(UT, 0);
6900
6901 QualType CanonType;
6902 if (!BaseType->isDependentType()) {
6903 CanonType = UnderlyingType.getCanonicalType();
6904 } else {
6905 if (QualType CanonBase = BaseType.getCanonicalType();
6906 BaseType != CanonBase) {
6907 CanonType = getUnaryTransformType(CanonBase, QualType(), Kind);
6908 assert(CanonType.isCanonical());
6909 }
6910 }
6911
6912 auto *UT = new (*this, alignof(UnaryTransformType))
6913 UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType);
6914 UnaryTransformTypes.insert(UT, Token);
6915 Types.push_back(UT);
6916 return QualType(UT, 0);
6917}
6918
6919/// getAutoType - Return the uniqued reference to the 'auto' type which has been
6920/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
6921/// canonical deduced-but-dependent 'auto' type.
6925 TemplateName TypeConstraintConcept,
6926 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
6928 TypeConstraintConcept.isNull()) {
6929 assert(DeducedAsType.isNull() && "");
6930 assert(TypeConstraintArgs.empty() && "");
6931 return getAutoDeductType();
6932 }
6933
6934 // Look in the folding set for an existing type.
6935 llvm::FoldingSetNodeID ID;
6936 AutoType::Profile(ID, *this, DK, DeducedAsType, Keyword,
6937 TypeConstraintConcept, TypeConstraintArgs);
6938 if (auto const AT_iter = AutoTypes.find_as(ID); AT_iter != AutoTypes.end())
6939 return QualType(AT_iter->getSecond(), 0);
6940
6941 if (DK == DeducedKind::Deduced) {
6942 assert(!DeducedAsType.isNull() && "deduced type must be provided");
6943 } else {
6944 assert(DeducedAsType.isNull() && "deduced type must not be provided");
6945 if (!TypeConstraintConcept.isNull()) {
6946 bool AnyNonCanonArgs = false;
6947 TemplateName CanonicalConcept =
6948 getCanonicalTemplateName(TypeConstraintConcept);
6949 auto CanonicalConceptArgs = ::getCanonicalTemplateArguments(
6950 *this, TypeConstraintArgs, AnyNonCanonArgs);
6951 if (TypeConstraintConcept != CanonicalConcept || AnyNonCanonArgs)
6952 DeducedAsType = getAutoType(DK, QualType(), Keyword, CanonicalConcept,
6953 CanonicalConceptArgs);
6954 }
6955 }
6956
6957 void *Mem = Allocate(sizeof(AutoType) +
6958 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
6959 alignof(AutoType));
6960 auto *AT = new (Mem) AutoType(DK, DeducedAsType, Keyword,
6961 TypeConstraintConcept, TypeConstraintArgs);
6962#ifndef NDEBUG
6963 llvm::FoldingSetNodeID InsertedID;
6964 AT->Profile(InsertedID, *this);
6965 assert(InsertedID == ID && "ID does not match");
6966#endif
6967 Types.push_back(AT);
6968 AutoTypes.try_emplace(ID.Intern(BumpAlloc), AT);
6969 return QualType(AT, 0);
6970}
6971
6973 QualType CanonT = T.getNonPackExpansionType().getCanonicalType();
6974
6975 // Remove a type-constraint from a top-level auto or decltype(auto).
6976 if (auto *AT = CanonT->getAs<AutoType>()) {
6977 if (!AT->isConstrained())
6978 return T;
6979 return getQualifiedType(
6980 getAutoType(AT->getDeducedKind(), QualType(), AT->getKeyword()),
6981 T.getQualifiers());
6982 }
6983
6984 // FIXME: We only support constrained auto at the top level in the type of a
6985 // non-type template parameter at the moment. Once we lift that restriction,
6986 // we'll need to recursively build types containing auto here.
6987 assert(!CanonT->getContainedAutoType() ||
6988 !CanonT->getContainedAutoType()->isConstrained());
6989 return T;
6990}
6991
6992/// Return the uniqued reference to the deduced template specialization type
6993/// which has been deduced to the given type, or to the canonical undeduced
6994/// such type, or the canonical deduced-but-dependent such type.
6997 TemplateName Template) const {
6998 // Look in the folding set for an existing type.
6999 llvm::FoldingSetInsertToken Token;
7000 llvm::FoldingSetNodeID ID;
7001 DeducedTemplateSpecializationType::Profile(ID, DK, DeducedAsType, Keyword,
7002 Template);
7003 if (DeducedTemplateSpecializationType *DTST =
7004 DeducedTemplateSpecializationTypes.lookup(ID, Token))
7005 return QualType(DTST, 0);
7006
7007 if (DK == DeducedKind::Deduced) {
7008 assert(!DeducedAsType.isNull() && "deduced type must be provided");
7009 } else {
7010 assert(DeducedAsType.isNull() && "deduced type must not be provided");
7011 TemplateName CanonTemplateName = getCanonicalTemplateName(Template);
7012 // FIXME: Can this be formed from a DependentTemplateName, such that the
7013 // keyword should be part of the canonical type?
7015 Template != CanonTemplateName) {
7017 DK, QualType(), ElaboratedTypeKeyword::None, CanonTemplateName);
7018 // Find the insertion position again.
7019 [[maybe_unused]] DeducedTemplateSpecializationType *DTST =
7020 DeducedTemplateSpecializationTypes.lookup(ID, Token);
7021 assert(!DTST && "broken canonicalization");
7022 }
7023 }
7024
7025 auto *DTST = new (*this, alignof(DeducedTemplateSpecializationType))
7026 DeducedTemplateSpecializationType(DK, DeducedAsType, Keyword, Template);
7027
7028#ifndef NDEBUG
7029 llvm::FoldingSetNodeID TempID;
7030 DTST->Profile(TempID);
7031 assert(ID == TempID && "ID does not match");
7032#endif
7033 Types.push_back(DTST);
7034 DeducedTemplateSpecializationTypes.insert(DTST, Token);
7035 return QualType(DTST, 0);
7036}
7037
7038/// getAtomicType - Return the uniqued reference to the atomic type for
7039/// the given value type.
7041 // Unique pointers, to guarantee there is only one pointer of a particular
7042 // structure.
7043 llvm::FoldingSetInsertToken Token;
7044 if (AtomicType *AT = AtomicTypes.lookup(T, Token))
7045 return QualType(AT, 0);
7046
7047 // If the atomic value type isn't canonical, this won't be a canonical type
7048 // either, so fill in the canonical type field.
7049 QualType Canonical;
7050 if (!T.isCanonical()) {
7051 Canonical = getAtomicType(getCanonicalType(T));
7052
7053 assert(!AtomicTypes.lookup(T, Token) && "Shouldn't be in the map!");
7054 }
7055 auto *New = new (*this, alignof(AtomicType)) AtomicType(T, Canonical);
7056 Types.push_back(New);
7057 AtomicTypes.insert(New, Token);
7058 return QualType(New, 0);
7059}
7060
7061/// getAutoDeductType - Get type pattern for deducing against 'auto'.
7063 if (AutoDeductTy.isNull())
7065 new (*this, alignof(AutoType))
7067 /*TypeConstraintConcept=*/TemplateName(),
7068 /*TypeConstraintArgs=*/{}),
7069 0);
7070 return AutoDeductTy;
7071}
7072
7073/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
7075 if (AutoRRefDeductTy.isNull())
7077 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
7078 return AutoRRefDeductTy;
7079}
7080
7081/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
7082/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
7083/// needs to agree with the definition in <stddef.h>.
7087
7089 return getFromTargetType(Target->getSizeType());
7090}
7091
7092/// Return the unique signed counterpart of the integer type
7093/// corresponding to size_t.
7097
7098/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
7099/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
7103
7104/// Return the unique unsigned counterpart of "ptrdiff_t"
7105/// integer type. The standard (C11 7.21.6.1p7) refers to this type
7106/// in the definition of %tu format specifier.
7108 return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
7109}
7110
7111/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
7113 return getFromTargetType(Target->getIntMaxType());
7114}
7115
7116/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
7118 return getFromTargetType(Target->getUIntMaxType());
7119}
7120
7121/// getSignedWCharType - Return the type of "signed wchar_t".
7122/// Used when in C++, as a GCC extension.
7124 // FIXME: derive from "Target" ?
7125 return WCharTy;
7126}
7127
7128/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
7129/// Used when in C++, as a GCC extension.
7131 // FIXME: derive from "Target" ?
7132 return UnsignedIntTy;
7133}
7134
7136 return getFromTargetType(Target->getIntPtrType());
7137}
7138
7142
7143/// Return the unique type for "pid_t" defined in
7144/// <sys/types.h>. We need this to compute the correct type for vfork().
7146 return getFromTargetType(Target->getProcessIDType());
7147}
7148
7149//===----------------------------------------------------------------------===//
7150// Type Operators
7151//===----------------------------------------------------------------------===//
7152
7154 // Push qualifiers into arrays, and then discard any remaining
7155 // qualifiers.
7156 T = getCanonicalType(T);
7158 const Type *Ty = T.getTypePtr();
7162 } else if (isa<ArrayType>(Ty)) {
7164 } else if (isa<FunctionType>(Ty)) {
7165 Result = getPointerType(QualType(Ty, 0));
7166 } else {
7167 Result = QualType(Ty, 0);
7168 }
7169
7171}
7172
7174 Qualifiers &quals) const {
7175 SplitQualType splitType = type.getSplitUnqualifiedType();
7176
7177 // FIXME: getSplitUnqualifiedType() actually walks all the way to
7178 // the unqualified desugared type and then drops it on the floor.
7179 // We then have to strip that sugar back off with
7180 // getUnqualifiedDesugaredType(), which is silly.
7181 const auto *AT =
7182 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
7183
7184 // If we don't have an array, just use the results in splitType.
7185 if (!AT) {
7186 quals = splitType.Quals;
7187 return QualType(splitType.Ty, 0);
7188 }
7189
7190 // Otherwise, recurse on the array's element type.
7191 QualType elementType = AT->getElementType();
7192 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
7193
7194 // If that didn't change the element type, AT has no qualifiers, so we
7195 // can just use the results in splitType.
7196 if (elementType == unqualElementType) {
7197 assert(quals.empty()); // from the recursive call
7198 quals = splitType.Quals;
7199 return QualType(splitType.Ty, 0);
7200 }
7201
7202 // Otherwise, add in the qualifiers from the outermost type, then
7203 // build the type back up.
7204 quals.addConsistentQualifiers(splitType.Quals);
7205
7206 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
7207 return getConstantArrayType(unqualElementType, CAT->getSize(),
7208 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
7209 }
7210
7211 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
7212 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
7213 }
7214
7215 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
7216 return getVariableArrayType(unqualElementType, VAT->getSizeExpr(),
7217 VAT->getSizeModifier(),
7218 VAT->getIndexTypeCVRQualifiers());
7219 }
7220
7221 const auto *DSAT = cast<DependentSizedArrayType>(AT);
7222 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
7223 DSAT->getSizeModifier(), 0);
7224}
7225
7226/// Attempt to unwrap two types that may both be array types with the same bound
7227/// (or both be array types of unknown bound) for the purpose of comparing the
7228/// cv-decomposition of two types per C++ [conv.qual].
7229///
7230/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7231/// C++20 [conv.qual], if permitted by the current language mode.
7233 bool AllowPiMismatch) const {
7234 while (true) {
7235 auto *AT1 = getAsArrayType(T1);
7236 if (!AT1)
7237 return;
7238
7239 auto *AT2 = getAsArrayType(T2);
7240 if (!AT2)
7241 return;
7242
7243 // If we don't have two array types with the same constant bound nor two
7244 // incomplete array types, we've unwrapped everything we can.
7245 // C++20 also permits one type to be a constant array type and the other
7246 // to be an incomplete array type.
7247 // FIXME: Consider also unwrapping array of unknown bound and VLA.
7248 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
7249 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
7250 if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
7251 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7253 return;
7254 } else if (isa<IncompleteArrayType>(AT1)) {
7255 if (!(isa<IncompleteArrayType>(AT2) ||
7256 (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
7258 return;
7259 } else {
7260 return;
7261 }
7262
7263 T1 = AT1->getElementType();
7264 T2 = AT2->getElementType();
7265 }
7266}
7267
7268/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
7269///
7270/// If T1 and T2 are both pointer types of the same kind, or both array types
7271/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
7272/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
7273///
7274/// This function will typically be called in a loop that successively
7275/// "unwraps" pointer and pointer-to-member types to compare them at each
7276/// level.
7277///
7278/// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
7279/// C++20 [conv.qual], if permitted by the current language mode.
7280///
7281/// \return \c true if a pointer type was unwrapped, \c false if we reached a
7282/// pair of types that can't be unwrapped further.
7284 bool AllowPiMismatch) const {
7285 UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
7286
7287 const auto *T1PtrType = T1->getAs<PointerType>();
7288 const auto *T2PtrType = T2->getAs<PointerType>();
7289 if (T1PtrType && T2PtrType) {
7290 T1 = T1PtrType->getPointeeType();
7291 T2 = T2PtrType->getPointeeType();
7292 return true;
7293 }
7294
7295 if (const auto *T1MPType = T1->getAsCanonical<MemberPointerType>(),
7296 *T2MPType = T2->getAsCanonical<MemberPointerType>();
7297 T1MPType && T2MPType) {
7298 // Compare the qualifiers of the canonical type, as the non-canonical type
7299 // may have qualifiers pointing to a base or derived class.
7300 if (T1MPType->getQualifier() != T2MPType->getQualifier())
7301 return false;
7302 // Get the pointee types of the non-canonical type, in order to preserve
7303 // their sugar.
7304 T1 = T1->getAs<MemberPointerType>()->getPointeeType();
7305 T2 = T2->getAs<MemberPointerType>()->getPointeeType();
7306 return true;
7307 }
7308
7309 if (getLangOpts().ObjC) {
7310 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
7311 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
7312 if (T1OPType && T2OPType) {
7313 T1 = T1OPType->getPointeeType();
7314 T2 = T2OPType->getPointeeType();
7315 return true;
7316 }
7317 }
7318
7319 // FIXME: Block pointers, too?
7320
7321 return false;
7322}
7323
7325 while (true) {
7326 Qualifiers Quals;
7327 T1 = getUnqualifiedArrayType(T1, Quals);
7328 T2 = getUnqualifiedArrayType(T2, Quals);
7329 if (hasSameType(T1, T2))
7330 return true;
7331 if (!UnwrapSimilarTypes(T1, T2))
7332 return false;
7333 }
7334}
7335
7337 while (true) {
7338 Qualifiers Quals1, Quals2;
7339 T1 = getUnqualifiedArrayType(T1, Quals1);
7340 T2 = getUnqualifiedArrayType(T2, Quals2);
7341
7342 Quals1.removeCVRQualifiers();
7343 Quals2.removeCVRQualifiers();
7344 if (Quals1 != Quals2)
7345 return false;
7346
7347 if (hasSameType(T1, T2))
7348 return true;
7349
7350 if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
7351 return false;
7352 }
7353}
7354
7357 SourceLocation NameLoc) const {
7358 switch (Name.getKind()) {
7361 // DNInfo work in progress: CHECKME: what about DNLoc?
7363 NameLoc);
7364
7367 // DNInfo work in progress: CHECKME: what about DNLoc?
7368 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
7369 }
7370
7373 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
7374 }
7375
7379 DeclarationName DName;
7380 if (const IdentifierInfo *II = TN.getIdentifier()) {
7381 DName = DeclarationNames.getIdentifier(II);
7382 return DeclarationNameInfo(DName, NameLoc);
7383 } else {
7384 DName = DeclarationNames.getCXXOperatorName(TN.getOperator());
7385 // DNInfo work in progress: FIXME: source locations?
7386 DeclarationNameLoc DNLoc =
7388 return DeclarationNameInfo(DName, NameLoc, DNLoc);
7389 }
7390 }
7391
7395 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
7396 NameLoc);
7397 }
7398
7403 NameLoc);
7404 }
7407 NameLoc);
7410 return getNameForTemplate(DTS->getUnderlying(), NameLoc);
7411 }
7414 return getNameForTemplate(PI->getPattern(), NameLoc);
7415 }
7416 }
7417
7418 llvm_unreachable("bad template name kind!");
7419}
7420
7421const TemplateArgument *
7423 auto handleParam = [](auto *TP) -> const TemplateArgument * {
7424 if (!TP->hasDefaultArgument())
7425 return nullptr;
7426 return &TP->getDefaultArgument().getArgument();
7427 };
7428 switch (P->getKind()) {
7429 case NamedDecl::TemplateTypeParm:
7430 return handleParam(cast<TemplateTypeParmDecl>(P));
7431 case NamedDecl::NonTypeTemplateParm:
7432 return handleParam(cast<NonTypeTemplateParmDecl>(P));
7433 case NamedDecl::TemplateTemplateParm:
7434 return handleParam(cast<TemplateTemplateParmDecl>(P));
7435 default:
7436 llvm_unreachable("Unexpected template parameter kind");
7437 }
7438}
7439
7441 bool IgnoreDeduced) const {
7442 while (std::optional<TemplateName> UnderlyingOrNone =
7443 Name.desugar(IgnoreDeduced))
7444 Name = *UnderlyingOrNone;
7445
7446 switch (Name.getKind()) {
7449 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
7451
7452 // The canonical template name is the canonical template declaration.
7453 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
7454 }
7455
7457 // An assumed template is just a name, so it is already canonical.
7458 return Name;
7459
7461 llvm_unreachable("cannot canonicalize overloaded template");
7462
7465 assert(DTN && "Non-dependent template names must refer to template decls.");
7466 NestedNameSpecifier Qualifier = DTN->getQualifier();
7467 NestedNameSpecifier CanonQualifier = Qualifier.getCanonical();
7468 if (Qualifier != CanonQualifier || !DTN->hasTemplateKeyword())
7469 return getDependentTemplateName({CanonQualifier, DTN->getName(),
7470 /*HasTemplateKeyword=*/true});
7471 return Name;
7472 }
7473
7477 TemplateArgument canonArgPack =
7480 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
7481 subst->getIndex(), subst->getFinal());
7482 }
7483
7486 SmallVector<TemplateName, 4> CanonExpansions;
7487 for (TemplateName T : PI->getExpansions())
7488 CanonExpansions.push_back(getCanonicalTemplateName(T, IgnoreDeduced));
7490 getCanonicalTemplateName(PI->getPattern(), IgnoreDeduced),
7491 PI->getIndexExpr(), PI->isFullySubstituted(), CanonExpansions);
7492 }
7494 assert(IgnoreDeduced == false);
7496 DefaultArguments DefArgs = DTS->getDefaultArguments();
7497 TemplateName Underlying = DTS->getUnderlying();
7498
7499 TemplateName CanonUnderlying =
7500 getCanonicalTemplateName(Underlying, /*IgnoreDeduced=*/true);
7501 bool NonCanonical = CanonUnderlying != Underlying;
7502 auto CanonArgs =
7503 getCanonicalTemplateArguments(*this, DefArgs.Args, NonCanonical);
7504
7505 ArrayRef<NamedDecl *> Params =
7506 CanonUnderlying.getAsTemplateDecl()->getTemplateParameters()->asArray();
7507 assert(CanonArgs.size() <= Params.size());
7508 // A deduced template name which deduces the same default arguments already
7509 // declared in the underlying template is the same template as the
7510 // underlying template. We need need to note any arguments which differ from
7511 // the corresponding declaration. If any argument differs, we must build a
7512 // deduced template name.
7513 for (int I = CanonArgs.size() - 1; I >= 0; --I) {
7515 if (!A)
7516 break;
7517 auto CanonParamDefArg = getCanonicalTemplateArgument(*A);
7518 TemplateArgument &CanonDefArg = CanonArgs[I];
7519 if (CanonDefArg.structurallyEquals(CanonParamDefArg))
7520 continue;
7521 // Keep popping from the back any deault arguments which are the same.
7522 if (I == int(CanonArgs.size() - 1))
7523 CanonArgs.pop_back();
7524 NonCanonical = true;
7525 }
7526 return NonCanonical ? getDeducedTemplateName(
7527 CanonUnderlying,
7528 /*DefaultArgs=*/{DefArgs.StartPos, CanonArgs})
7529 : Name;
7530 }
7534 llvm_unreachable("always sugar node");
7535 }
7536
7537 llvm_unreachable("bad template name!");
7538}
7539
7541 const TemplateName &Y,
7542 bool IgnoreDeduced) const {
7543 return getCanonicalTemplateName(X, IgnoreDeduced) ==
7544 getCanonicalTemplateName(Y, IgnoreDeduced);
7545}
7546
7548 const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const {
7549 if (ACX.ArgPackSubstIndex != ACY.ArgPackSubstIndex)
7550 return false;
7552 return false;
7553 return true;
7554}
7555
7556bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
7557 if (!XCE != !YCE)
7558 return false;
7559
7560 if (!XCE)
7561 return true;
7562
7563 llvm::FoldingSetNodeID XCEID, YCEID;
7564 XCE->Profile(XCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7565 YCE->Profile(YCEID, *this, /*Canonical=*/true, /*ProfileLambdaExpr=*/true);
7566 return XCEID == YCEID;
7567}
7568
7570 const TypeConstraint *YTC) const {
7571 if (!XTC != !YTC)
7572 return false;
7573
7574 if (!XTC)
7575 return true;
7576
7579 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
7580 return false;
7583 return false;
7585 if (XTC->getConceptReference()
7587 ->NumTemplateArgs !=
7589 return false;
7590
7591 // Compare slowly by profiling.
7592 //
7593 // We couldn't compare the profiling result for the template
7594 // args here. Consider the following example in different modules:
7595 //
7596 // template <__integer_like _Tp, C<_Tp> Sentinel>
7597 // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
7598 // return __t;
7599 // }
7600 //
7601 // When we compare the profiling result for `C<_Tp>` in different
7602 // modules, it will compare the type of `_Tp` in different modules.
7603 // However, the type of `_Tp` in different modules refer to different
7604 // types here naturally. So we couldn't compare the profiling result
7605 // for the template args directly.
7608}
7609
7611 const NamedDecl *Y) const {
7612 if (X->getKind() != Y->getKind())
7613 return false;
7614
7615 if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
7616 auto *TY = cast<TemplateTypeParmDecl>(Y);
7617 if (TX->isParameterPack() != TY->isParameterPack())
7618 return false;
7619 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
7620 return false;
7621 return isSameTypeConstraint(TX->getTypeConstraint(),
7622 TY->getTypeConstraint());
7623 }
7624
7625 if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7626 auto *TY = cast<NonTypeTemplateParmDecl>(Y);
7627 return TX->isParameterPack() == TY->isParameterPack() &&
7628 TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
7629 isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
7630 TY->getPlaceholderTypeConstraint());
7631 }
7632
7634 auto *TY = cast<TemplateTemplateParmDecl>(Y);
7635 return TX->isParameterPack() == TY->isParameterPack() &&
7636 isSameTemplateParameterList(TX->getTemplateParameters(),
7637 TY->getTemplateParameters());
7638}
7639
7641 const TemplateParameterList *X, const TemplateParameterList *Y) const {
7642 if (X->size() != Y->size())
7643 return false;
7644
7645 for (unsigned I = 0, N = X->size(); I != N; ++I)
7646 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
7647 return false;
7648
7649 return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
7650}
7651
7653 const NamedDecl *Y) const {
7654 // If the type parameter isn't the same already, we don't need to check the
7655 // default argument further.
7656 if (!isSameTemplateParameter(X, Y))
7657 return false;
7658
7659 if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
7660 auto *TTPY = cast<TemplateTypeParmDecl>(Y);
7661 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7662 return false;
7663
7664 return hasSameType(TTPX->getDefaultArgument().getArgument().getAsType(),
7665 TTPY->getDefaultArgument().getArgument().getAsType());
7666 }
7667
7668 if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
7669 auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
7670 if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
7671 return false;
7672
7673 Expr *DefaultArgumentX =
7674 NTTPX->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7675 Expr *DefaultArgumentY =
7676 NTTPY->getDefaultArgument().getArgument().getAsExpr()->IgnoreImpCasts();
7677 llvm::FoldingSetNodeID XID, YID;
7678 DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
7679 DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
7680 return XID == YID;
7681 }
7682
7683 auto *TTPX = cast<TemplateTemplateParmDecl>(X);
7684 auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
7685
7686 if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
7687 return false;
7688
7689 const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
7690 const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
7691 return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
7692}
7693
7695 const NestedNameSpecifier Y) {
7696 if (X == Y)
7697 return true;
7698 if (!X || !Y)
7699 return false;
7700
7701 auto Kind = X.getKind();
7702 if (Kind != Y.getKind())
7703 return false;
7704
7705 // FIXME: For namespaces and types, we're permitted to check that the entity
7706 // is named via the same tokens. We should probably do so.
7707 switch (Kind) {
7709 auto [NamespaceX, PrefixX] = X.getAsNamespaceAndPrefix();
7710 auto [NamespaceY, PrefixY] = Y.getAsNamespaceAndPrefix();
7711 if (!declaresSameEntity(NamespaceX->getNamespace(),
7712 NamespaceY->getNamespace()))
7713 return false;
7714 return isSameQualifier(PrefixX, PrefixY);
7715 }
7717 const auto *TX = X.getAsType(), *TY = Y.getAsType();
7718 if (TX->getCanonicalTypeInternal() != TY->getCanonicalTypeInternal())
7719 return false;
7720 return isSameQualifier(TX->getPrefix(), TY->getPrefix());
7721 }
7725 return true;
7726 }
7727 llvm_unreachable("unhandled qualifier kind");
7728}
7729
7730static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B) {
7731 if (!A->getASTContext().getLangOpts().CUDA)
7732 return true; // Target attributes are overloadable in CUDA compilation only.
7733 if (A->hasAttr<CUDADeviceAttr>() != B->hasAttr<CUDADeviceAttr>())
7734 return false;
7735 if (A->hasAttr<CUDADeviceAttr>() && B->hasAttr<CUDADeviceAttr>())
7736 return A->hasAttr<CUDAHostAttr>() == B->hasAttr<CUDAHostAttr>();
7737 return true; // unattributed and __host__ functions are the same.
7738}
7739
7740/// Determine whether the attributes we can overload on are identical for A and
7741/// B. Will ignore any overloadable attrs represented in the type of A and B.
7743 const FunctionDecl *B) {
7744 // Note that pass_object_size attributes are represented in the function's
7745 // ExtParameterInfo, so we don't need to check them here.
7746
7747 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
7748 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
7749 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
7750
7751 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
7752 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
7753 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
7754
7755 // Return false if the number of enable_if attributes is different.
7756 if (!Cand1A || !Cand2A)
7757 return false;
7758
7759 Cand1ID.clear();
7760 Cand2ID.clear();
7761
7762 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
7763 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
7764
7765 // Return false if any of the enable_if expressions of A and B are
7766 // different.
7767 if (Cand1ID != Cand2ID)
7768 return false;
7769 }
7770 return hasSameCudaAttrs(A, B);
7771}
7772
7773bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
7774 // Caution: this function is called by the AST reader during deserialization,
7775 // so it cannot rely on AST invariants being met. Non-trivial accessors
7776 // should be avoided, along with any traversal of redeclaration chains.
7777
7778 if (X == Y)
7779 return true;
7780
7781 if (X->getDeclName() != Y->getDeclName())
7782 return false;
7783
7784 // Must be in the same context.
7785 //
7786 // Note that we can't use DeclContext::Equals here, because the DeclContexts
7787 // could be two different declarations of the same function. (We will fix the
7788 // semantic DC to refer to the primary definition after merging.)
7789 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
7791 return false;
7792
7793 // If either X or Y are local to the owning module, they are only possible to
7794 // be the same entity if they are in the same module.
7795 if (X->isModuleLocal() || Y->isModuleLocal())
7796 if (!isInSameModule(X->getOwningModule(), Y->getOwningModule()))
7797 return false;
7798
7799 // Two typedefs refer to the same entity if they have the same underlying
7800 // type.
7801 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
7802 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
7803 return hasSameType(TypedefX->getUnderlyingType(),
7804 TypedefY->getUnderlyingType());
7805
7806 // Must have the same kind.
7807 if (X->getKind() != Y->getKind())
7808 return false;
7809
7810 // Objective-C classes and protocols with the same name always match.
7812 return true;
7813
7815 // No need to handle these here: we merge them when adding them to the
7816 // template.
7817 return false;
7818 }
7819
7820 // Compatible tags match.
7821 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
7822 const auto *TagY = cast<TagDecl>(Y);
7823 return (TagX->getTagKind() == TagY->getTagKind()) ||
7824 ((TagX->getTagKind() == TagTypeKind::Struct ||
7825 TagX->getTagKind() == TagTypeKind::Class ||
7826 TagX->getTagKind() == TagTypeKind::Interface) &&
7827 (TagY->getTagKind() == TagTypeKind::Struct ||
7828 TagY->getTagKind() == TagTypeKind::Class ||
7829 TagY->getTagKind() == TagTypeKind::Interface));
7830 }
7831
7832 // Functions with the same type and linkage match.
7833 // FIXME: This needs to cope with merging of prototyped/non-prototyped
7834 // functions, etc.
7835 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
7836 const auto *FuncY = cast<FunctionDecl>(Y);
7837 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
7838 const auto *CtorY = cast<CXXConstructorDecl>(Y);
7839 if (CtorX->getInheritedConstructor() &&
7840 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
7841 CtorY->getInheritedConstructor().getConstructor()))
7842 return false;
7843 }
7844
7845 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
7846 return false;
7847
7848 // Multiversioned functions with different feature strings are represented
7849 // as separate declarations.
7850 if (FuncX->isMultiVersion()) {
7851 const auto *TAX = FuncX->getAttr<TargetAttr>();
7852 const auto *TAY = FuncY->getAttr<TargetAttr>();
7853 assert(TAX && TAY && "Multiversion Function without target attribute");
7854
7855 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
7856 return false;
7857 }
7858
7859 // Per C++20 [temp.over.link]/4, friends in different classes are sometimes
7860 // not the same entity if they are constrained.
7861 if ((FuncX->isMemberLikeConstrainedFriend() ||
7862 FuncY->isMemberLikeConstrainedFriend()) &&
7863 !FuncX->getLexicalDeclContext()->Equals(
7864 FuncY->getLexicalDeclContext())) {
7865 return false;
7866 }
7867
7868 if (!isSameAssociatedConstraint(FuncX->getTrailingRequiresClause(),
7869 FuncY->getTrailingRequiresClause()))
7870 return false;
7871
7872 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
7873 // Map to the first declaration that we've already merged into this one.
7874 // The TSI of redeclarations might not match (due to calling conventions
7875 // being inherited onto the type but not the TSI), but the TSI type of
7876 // the first declaration of the function should match across modules.
7877 FD = FD->getCanonicalDecl();
7878 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
7879 : FD->getType();
7880 };
7881 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
7882 if (!hasSameType(XT, YT)) {
7883 // We can get functions with different types on the redecl chain in C++17
7884 // if they have differing exception specifications and at least one of
7885 // the excpetion specs is unresolved.
7886 auto *XFPT = XT->getAs<FunctionProtoType>();
7887 auto *YFPT = YT->getAs<FunctionProtoType>();
7888 if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
7889 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
7892 return true;
7893 return false;
7894 }
7895
7896 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
7897 hasSameOverloadableAttrs(FuncX, FuncY);
7898 }
7899
7900 // Variables with the same type and linkage match.
7901 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
7902 const auto *VarY = cast<VarDecl>(Y);
7903 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
7904 // During deserialization, we might compare variables before we load
7905 // their types. Assume the types will end up being the same.
7906 if (VarX->getType().isNull() || VarY->getType().isNull())
7907 return true;
7908
7909 if (hasSameType(VarX->getType(), VarY->getType()))
7910 return true;
7911
7912 // We can get decls with different types on the redecl chain. Eg.
7913 // template <typename T> struct S { static T Var[]; }; // #1
7914 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
7915 // Only? happens when completing an incomplete array type. In this case
7916 // when comparing #1 and #2 we should go through their element type.
7917 const ArrayType *VarXTy = getAsArrayType(VarX->getType());
7918 const ArrayType *VarYTy = getAsArrayType(VarY->getType());
7919 if (!VarXTy || !VarYTy)
7920 return false;
7921 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
7922 return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
7923 }
7924 return false;
7925 }
7926
7927 // Namespaces with the same name and inlinedness match.
7928 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
7929 const auto *NamespaceY = cast<NamespaceDecl>(Y);
7930 return NamespaceX->isInline() == NamespaceY->isInline();
7931 }
7932
7933 // Identical template names and kinds match if their template parameter lists
7934 // and patterns match.
7935 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
7936 const auto *TemplateY = cast<TemplateDecl>(Y);
7937
7938 // ConceptDecl wouldn't be the same if their constraint expression differs.
7939 if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
7940 const auto *ConceptY = cast<ConceptDecl>(Y);
7941 if (!isSameConstraintExpr(ConceptX->getConstraintExpr(),
7942 ConceptY->getConstraintExpr()))
7943 return false;
7944 }
7945
7946 return isSameEntity(TemplateX->getTemplatedDecl(),
7947 TemplateY->getTemplatedDecl()) &&
7948 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
7949 TemplateY->getTemplateParameters());
7950 }
7951
7952 // Fields with the same name and the same type match.
7953 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
7954 const auto *FDY = cast<FieldDecl>(Y);
7955 // FIXME: Also check the bitwidth is odr-equivalent, if any.
7956 return hasSameType(FDX->getType(), FDY->getType());
7957 }
7958
7959 // Indirect fields with the same target field match.
7960 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
7961 const auto *IFDY = cast<IndirectFieldDecl>(Y);
7962 return IFDX->getAnonField()->getCanonicalDecl() ==
7963 IFDY->getAnonField()->getCanonicalDecl();
7964 }
7965
7966 // Enumerators with the same name match.
7968 // FIXME: Also check the value is odr-equivalent.
7969 return true;
7970
7971 // Using shadow declarations with the same target match.
7972 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
7973 const auto *USY = cast<UsingShadowDecl>(Y);
7974 return declaresSameEntity(USX->getTargetDecl(), USY->getTargetDecl());
7975 }
7976
7977 // Using declarations with the same qualifier match. (We already know that
7978 // the name matches.)
7979 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
7980 const auto *UY = cast<UsingDecl>(Y);
7981 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7982 UX->hasTypename() == UY->hasTypename() &&
7983 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7984 }
7985 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
7986 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
7987 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
7988 UX->isAccessDeclaration() == UY->isAccessDeclaration();
7989 }
7990 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
7991 return isSameQualifier(
7992 UX->getQualifier(),
7993 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
7994 }
7995
7996 // Using-pack declarations are only created by instantiation, and match if
7997 // they're instantiated from matching UnresolvedUsing...Decls.
7998 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
7999 return declaresSameEntity(
8000 UX->getInstantiatedFromUsingDecl(),
8001 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
8002 }
8003
8004 // Namespace alias definitions with the same target match.
8005 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
8006 const auto *NAY = cast<NamespaceAliasDecl>(Y);
8007 return NAX->getNamespace()->Equals(NAY->getNamespace());
8008 }
8009
8010 if (const auto *UX = dyn_cast<UsingEnumDecl>(X)) {
8011 const auto *UY = cast<UsingEnumDecl>(Y);
8012 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
8013 declaresSameEntity(UX->getEnumDecl(), UY->getEnumDecl());
8014 }
8015
8016 return false;
8017}
8018
8021 switch (Arg.getKind()) {
8023 return Arg;
8024
8026 return TemplateArgument(Arg.getAsExpr(), /*IsCanonical=*/true,
8027 Arg.getIsDefaulted());
8028
8030 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
8032 Arg.getIsDefaulted());
8033 }
8034
8037 /*isNullPtr*/ true, Arg.getIsDefaulted());
8038
8041 Arg.getIsDefaulted());
8042
8044 return TemplateArgument(
8047
8050
8052 return TemplateArgument(*this,
8055
8058 /*isNullPtr*/ false, Arg.getIsDefaulted());
8059
8061 bool AnyNonCanonArgs = false;
8062 auto CanonArgs = ::getCanonicalTemplateArguments(
8063 *this, Arg.pack_elements(), AnyNonCanonArgs);
8064 if (!AnyNonCanonArgs)
8065 return Arg;
8067 const_cast<ASTContext &>(*this), CanonArgs);
8068 NewArg.setIsDefaulted(Arg.getIsDefaulted());
8069 return NewArg;
8070 }
8071 }
8072
8073 // Silence GCC warning
8074 llvm_unreachable("Unhandled template argument kind");
8075}
8076
8078 const TemplateArgument &Arg2) const {
8079 if (Arg1.getKind() != Arg2.getKind())
8080 return false;
8081
8082 switch (Arg1.getKind()) {
8084 llvm_unreachable("Comparing NULL template argument");
8085
8087 return hasSameType(Arg1.getAsType(), Arg2.getAsType());
8088
8090 return Arg1.getAsDecl()->getUnderlyingDecl()->getCanonicalDecl() ==
8092
8094 return hasSameType(Arg1.getNullPtrType(), Arg2.getNullPtrType());
8095
8100
8102 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
8103 Arg2.getAsIntegral());
8104
8106 return Arg1.structurallyEquals(Arg2);
8107
8109 llvm::FoldingSetNodeID ID1, ID2;
8110 Arg1.getAsExpr()->Profile(ID1, *this, /*Canonical=*/true);
8111 Arg2.getAsExpr()->Profile(ID2, *this, /*Canonical=*/true);
8112 return ID1 == ID2;
8113 }
8114
8116 return llvm::equal(
8117 Arg1.getPackAsArray(), Arg2.getPackAsArray(),
8118 [&](const TemplateArgument &Arg1, const TemplateArgument &Arg2) {
8119 return isSameTemplateArgument(Arg1, Arg2);
8120 });
8121 }
8122
8123 llvm_unreachable("Unhandled template argument kind");
8124}
8125
8127 // Handle the non-qualified case efficiently.
8128 if (!T.hasLocalQualifiers()) {
8129 // Handle the common positive case fast.
8130 if (const auto *AT = dyn_cast<ArrayType>(T))
8131 return AT;
8132 }
8133
8134 // Handle the common negative case fast.
8135 if (!isa<ArrayType>(T.getCanonicalType()))
8136 return nullptr;
8137
8138 // Apply any qualifiers from the array type to the element type. This
8139 // implements C99 6.7.3p8: "If the specification of an array type includes
8140 // any type qualifiers, the element type is so qualified, not the array type."
8141
8142 // If we get here, we either have type qualifiers on the type, or we have
8143 // sugar such as a typedef in the way. If we have type qualifiers on the type
8144 // we must propagate them down into the element type.
8145
8146 SplitQualType split = T.getSplitDesugaredType();
8147 Qualifiers qs = split.Quals;
8148
8149 // If we have a simple case, just return now.
8150 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
8151 if (!ATy || qs.empty())
8152 return ATy;
8153
8154 // Otherwise, we have an array and we have qualifiers on it. Push the
8155 // qualifiers into the array element type and return a new array type.
8156 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
8157
8158 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
8159 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
8160 CAT->getSizeExpr(),
8161 CAT->getSizeModifier(),
8162 CAT->getIndexTypeCVRQualifiers()));
8163 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
8165 IAT->getSizeModifier(),
8166 IAT->getIndexTypeCVRQualifiers()));
8167
8168 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
8170 NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(),
8171 DSAT->getIndexTypeCVRQualifiers()));
8172
8173 const auto *VAT = cast<VariableArrayType>(ATy);
8174 return cast<ArrayType>(
8175 getVariableArrayType(NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(),
8176 VAT->getIndexTypeCVRQualifiers()));
8177}
8178
8180 if (getLangOpts().HLSL && T.getAddressSpace() == LangAS::hlsl_groupshared)
8181 return getLValueReferenceType(T);
8182 if (getLangOpts().HLSL && T->isConstantArrayType())
8183 return getArrayParameterType(T);
8184 if (T->isArrayType() || T->isFunctionType())
8185 return getDecayedType(T);
8186 return T;
8187}
8188
8192 return T.getUnqualifiedType();
8193}
8194
8196 // C++ [except.throw]p3:
8197 // A throw-expression initializes a temporary object, called the exception
8198 // object, the type of which is determined by removing any top-level
8199 // cv-qualifiers from the static type of the operand of throw and adjusting
8200 // the type from "array of T" or "function returning T" to "pointer to T"
8201 // or "pointer to function returning T", [...]
8203 if (T->isArrayType() || T->isFunctionType())
8204 T = getDecayedType(T);
8205 return T.getUnqualifiedType();
8206}
8207
8208/// getArrayDecayedType - Return the properly qualified result of decaying the
8209/// specified array type to a pointer. This operation is non-trivial when
8210/// handling typedefs etc. The canonical type of "T" must be an array type,
8211/// this returns a pointer to a properly qualified element of the array.
8212///
8213/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
8215 // Get the element type with 'getAsArrayType' so that we don't lose any
8216 // typedefs in the element type of the array. This also handles propagation
8217 // of type qualifiers from the array type into the element type if present
8218 // (C99 6.7.3p8).
8219 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
8220 assert(PrettyArrayType && "Not an array type!");
8221
8222 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
8223
8224 // int x[restrict 4] -> int *restrict
8226 PrettyArrayType->getIndexTypeQualifiers());
8227
8228 // int x[_Nullable] -> int * _Nullable
8229 if (auto Nullability = Ty->getNullability()) {
8230 Result = getAttributedType(*Nullability, Result, Result);
8231 }
8232 return Result;
8233}
8234
8236 return getBaseElementType(array->getElementType());
8237}
8238
8240 Qualifiers qs;
8241 while (true) {
8242 SplitQualType split = type.getSplitDesugaredType();
8243 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
8244 if (!array) break;
8245
8246 type = array->getElementType();
8248 }
8249
8250 return getQualifiedType(type, qs);
8251}
8252
8254 uint64_t ElementCount = 1;
8255 do {
8256 ElementCount *= CA->getZExtSize();
8257 CA = dyn_cast_if_present<ConstantArrayType>(
8259 } while (CA);
8260 return ElementCount;
8261}
8262
8263uint64_t
8265 if (!AILE)
8266 return 0;
8267
8268 uint64_t ElementCount = 1;
8269
8270 do {
8271 ElementCount *= AILE->getArraySize().getZExtValue();
8272 AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
8273 } while (AILE);
8274
8275 return ElementCount;
8276}
8277
8278/// getFloatingRank - Return a relative rank for floating point types.
8279/// This routine will assert if passed a built-in type that isn't a float.
8281 if (const auto *CT = T->getAs<ComplexType>())
8282 return getFloatingRank(CT->getElementType());
8283
8284 switch (T->castAs<BuiltinType>()->getKind()) {
8285 default: llvm_unreachable("getFloatingRank(): not a floating type");
8286 case BuiltinType::Float16: return Float16Rank;
8287 case BuiltinType::Half: return HalfRank;
8288 case BuiltinType::Float: return FloatRank;
8289 case BuiltinType::Double: return DoubleRank;
8290 case BuiltinType::LongDouble: return LongDoubleRank;
8291 case BuiltinType::Float128: return Float128Rank;
8292 case BuiltinType::BFloat16: return BFloat16Rank;
8293 case BuiltinType::Ibm128: return Ibm128Rank;
8294 }
8295}
8296
8297/// getFloatingTypeOrder - Compare the rank of the two specified floating
8298/// point types, ignoring the domain of the type (i.e. 'double' ==
8299/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
8300/// LHS < RHS, return -1.
8302 FloatingRank LHSR = getFloatingRank(LHS);
8303 FloatingRank RHSR = getFloatingRank(RHS);
8304
8305 if (LHSR == RHSR)
8306 return 0;
8307 if (LHSR > RHSR)
8308 return 1;
8309 return -1;
8310}
8311
8314 return 0;
8315 return getFloatingTypeOrder(LHS, RHS);
8316}
8317
8318/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
8319/// routine will assert if passed a built-in type that isn't an integer or enum,
8320/// or if it is not canonicalized.
8321unsigned ASTContext::getIntegerRank(const Type *T) const {
8322 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
8323
8324 // Results in this 'losing' to any type of the same size, but winning if
8325 // larger.
8326 if (const auto *EIT = dyn_cast<BitIntType>(T))
8327 return 0 + (EIT->getNumBits() << 3);
8328
8329 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(T))
8330 return getIntegerRank(OBT->getUnderlyingType().getTypePtr());
8331
8332 switch (cast<BuiltinType>(T)->getKind()) {
8333 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
8334 case BuiltinType::Bool:
8335 return 1 + (getIntWidth(BoolTy) << 3);
8336 case BuiltinType::Char_S:
8337 case BuiltinType::Char_U:
8338 case BuiltinType::SChar:
8339 case BuiltinType::UChar:
8340 return 2 + (getIntWidth(CharTy) << 3);
8341 case BuiltinType::Short:
8342 case BuiltinType::UShort:
8343 return 3 + (getIntWidth(ShortTy) << 3);
8344 case BuiltinType::Int:
8345 case BuiltinType::UInt:
8346 return 4 + (getIntWidth(IntTy) << 3);
8347 case BuiltinType::Long:
8348 case BuiltinType::ULong:
8349 return 5 + (getIntWidth(LongTy) << 3);
8350 case BuiltinType::LongLong:
8351 case BuiltinType::ULongLong:
8352 return 6 + (getIntWidth(LongLongTy) << 3);
8353 case BuiltinType::Int128:
8354 case BuiltinType::UInt128:
8355 return 7 + (getIntWidth(Int128Ty) << 3);
8356
8357 // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
8358 // their underlying types" [c++20 conv.rank]
8359 case BuiltinType::Char8:
8360 return getIntegerRank(UnsignedCharTy.getTypePtr());
8361 case BuiltinType::Char16:
8362 return getIntegerRank(
8363 getFromTargetType(Target->getChar16Type()).getTypePtr());
8364 case BuiltinType::Char32:
8365 return getIntegerRank(
8366 getFromTargetType(Target->getChar32Type()).getTypePtr());
8367 case BuiltinType::WChar_S:
8368 case BuiltinType::WChar_U:
8369 return getIntegerRank(
8370 getFromTargetType(Target->getWCharType()).getTypePtr());
8371 }
8372}
8373
8374/// Whether this is a promotable bitfield reference according
8375/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
8376///
8377/// \returns the type this bit-field will promote to, or NULL if no
8378/// promotion occurs.
8380 if (E->isTypeDependent() || E->isValueDependent())
8381 return {};
8382
8383 // C++ [conv.prom]p5:
8384 // If the bit-field has an enumerated type, it is treated as any other
8385 // value of that type for promotion purposes.
8387 return {};
8388
8389 // FIXME: We should not do this unless E->refersToBitField() is true. This
8390 // matters in C where getSourceBitField() will find bit-fields for various
8391 // cases where the source expression is not a bit-field designator.
8392
8393 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
8394 if (!Field)
8395 return {};
8396
8397 QualType FT = Field->getType();
8398
8399 uint64_t BitWidth = Field->getBitWidthValue();
8400 uint64_t IntSize = getTypeSize(IntTy);
8401 // C++ [conv.prom]p5:
8402 // A prvalue for an integral bit-field can be converted to a prvalue of type
8403 // int if int can represent all the values of the bit-field; otherwise, it
8404 // can be converted to unsigned int if unsigned int can represent all the
8405 // values of the bit-field. If the bit-field is larger yet, no integral
8406 // promotion applies to it.
8407 // C11 6.3.1.1/2:
8408 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
8409 // If an int can represent all values of the original type (as restricted by
8410 // the width, for a bit-field), the value is converted to an int; otherwise,
8411 // it is converted to an unsigned int.
8412 //
8413 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
8414 // We perform that promotion here to match GCC and C++.
8415 // FIXME: C does not permit promotion of an enum bit-field whose rank is
8416 // greater than that of 'int'. We perform that promotion to match GCC.
8417 //
8418 // C23 6.3.1.1p2:
8419 // The value from a bit-field of a bit-precise integer type is converted to
8420 // the corresponding bit-precise integer type. (The rest is the same as in
8421 // C11.)
8422 if (QualType QT = Field->getType(); QT->isBitIntType())
8423 return QT;
8424
8425 if (BitWidth < IntSize)
8426 return IntTy;
8427
8428 if (BitWidth == IntSize)
8429 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
8430
8431 // Bit-fields wider than int are not subject to promotions, and therefore act
8432 // like the base type. GCC has some weird bugs in this area that we
8433 // deliberately do not follow (GCC follows a pre-standard resolution to
8434 // C's DR315 which treats bit-width as being part of the type, and this leaks
8435 // into their semantics in some cases).
8436 return {};
8437}
8438
8439/// getPromotedIntegerType - Returns the type that Promotable will
8440/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
8441/// integer type.
8443 assert(!Promotable.isNull());
8444 assert(isPromotableIntegerType(Promotable));
8445 if (const auto *ED = Promotable->getAsEnumDecl())
8446 return ED->getPromotionType();
8447
8448 // OverflowBehaviorTypes promote their underlying type and preserve OBT
8449 // qualifier.
8450 if (const auto *OBT = Promotable->getAs<OverflowBehaviorType>()) {
8451 QualType PromotedUnderlying =
8452 getPromotedIntegerType(OBT->getUnderlyingType());
8453 return getOverflowBehaviorType(OBT->getBehaviorKind(), PromotedUnderlying);
8454 }
8455
8456 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
8457 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
8458 // (3.9.1) can be converted to a prvalue of the first of the following
8459 // types that can represent all the values of its underlying type:
8460 // int, unsigned int, long int, unsigned long int, long long int, or
8461 // unsigned long long int [...]
8462 // FIXME: Is there some better way to compute this?
8463 if (BT->getKind() == BuiltinType::WChar_S ||
8464 BT->getKind() == BuiltinType::WChar_U ||
8465 BT->getKind() == BuiltinType::Char8 ||
8466 BT->getKind() == BuiltinType::Char16 ||
8467 BT->getKind() == BuiltinType::Char32) {
8468 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
8469 uint64_t FromSize = getTypeSize(BT);
8470 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
8472 for (const auto &PT : PromoteTypes) {
8473 uint64_t ToSize = getTypeSize(PT);
8474 if (FromSize < ToSize ||
8475 (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
8476 return PT;
8477 }
8478 llvm_unreachable("char type should fit into long long");
8479 }
8480 }
8481
8482 // At this point, we should have a signed or unsigned integer type.
8483 if (Promotable->isSignedIntegerType())
8484 return IntTy;
8485 uint64_t PromotableSize = getIntWidth(Promotable);
8486 uint64_t IntSize = getIntWidth(IntTy);
8487 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
8488 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
8489}
8490
8491/// Recurses in pointer/array types until it finds an objc retainable
8492/// type and returns its ownership.
8494 while (!T.isNull()) {
8495 if (T.getObjCLifetime() != Qualifiers::OCL_None)
8496 return T.getObjCLifetime();
8497 if (T->isArrayType())
8499 else if (const auto *PT = T->getAs<PointerType>())
8500 T = PT->getPointeeType();
8501 else if (const auto *RT = T->getAs<ReferenceType>())
8502 T = RT->getPointeeType();
8503 else
8504 break;
8505 }
8506
8507 return Qualifiers::OCL_None;
8508}
8509
8510static const Type *getIntegerTypeForEnum(const EnumType *ET) {
8511 // Incomplete enum types are not treated as integer types.
8512 // FIXME: In C++, enum types are never integer types.
8513 const EnumDecl *ED = ET->getDecl()->getDefinitionOrSelf();
8514 if (ED->isComplete() && !ED->isScoped())
8515 return ED->getIntegerType().getTypePtr();
8516 return nullptr;
8517}
8518
8519/// getIntegerTypeOrder - Returns the highest ranked integer type:
8520/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
8521/// LHS < RHS, return -1.
8523 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
8524 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
8525
8526 // Unwrap enums to their underlying type.
8527 if (const auto *ET = dyn_cast<EnumType>(LHSC))
8528 LHSC = getIntegerTypeForEnum(ET);
8529 if (const auto *ET = dyn_cast<EnumType>(RHSC))
8530 RHSC = getIntegerTypeForEnum(ET);
8531
8532 if (LHSC == RHSC) return 0;
8533
8534 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
8535 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
8536
8537 unsigned LHSRank = getIntegerRank(LHSC);
8538 unsigned RHSRank = getIntegerRank(RHSC);
8539
8540 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
8541 if (LHSRank == RHSRank) return 0;
8542 return LHSRank > RHSRank ? 1 : -1;
8543 }
8544
8545 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
8546 if (LHSUnsigned) {
8547 // If the unsigned [LHS] type is larger, return it.
8548 if (LHSRank >= RHSRank)
8549 return 1;
8550
8551 // If the signed type can represent all values of the unsigned type, it
8552 // wins. Because we are dealing with 2's complement and types that are
8553 // powers of two larger than each other, this is always safe.
8554 return -1;
8555 }
8556
8557 // If the unsigned [RHS] type is larger, return it.
8558 if (RHSRank >= LHSRank)
8559 return -1;
8560
8561 // If the signed type can represent all values of the unsigned type, it
8562 // wins. Because we are dealing with 2's complement and types that are
8563 // powers of two larger than each other, this is always safe.
8564 return 1;
8565}
8566
8568 if (CFConstantStringTypeDecl)
8569 return CFConstantStringTypeDecl;
8570
8571 assert(!CFConstantStringTagDecl &&
8572 "tag and typedef should be initialized together");
8573 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
8574 CFConstantStringTagDecl->startDefinition();
8575
8576 struct {
8577 QualType Type;
8578 const char *Name;
8579 } Fields[5];
8580 unsigned Count = 0;
8581
8582 /// Objective-C ABI
8583 ///
8584 /// typedef struct __NSConstantString_tag {
8585 /// const int *isa;
8586 /// int flags;
8587 /// const char *str;
8588 /// long length;
8589 /// } __NSConstantString;
8590 ///
8591 /// Swift ABI (4.1, 4.2)
8592 ///
8593 /// typedef struct __NSConstantString_tag {
8594 /// uintptr_t _cfisa;
8595 /// uintptr_t _swift_rc;
8596 /// _Atomic(uint64_t) _cfinfoa;
8597 /// const char *_ptr;
8598 /// uint32_t _length;
8599 /// } __NSConstantString;
8600 ///
8601 /// Swift ABI (5.0)
8602 ///
8603 /// typedef struct __NSConstantString_tag {
8604 /// uintptr_t _cfisa;
8605 /// uintptr_t _swift_rc;
8606 /// _Atomic(uint64_t) _cfinfoa;
8607 /// const char *_ptr;
8608 /// uintptr_t _length;
8609 /// } __NSConstantString;
8610
8611 const auto CFRuntime = getLangOpts().CFRuntime;
8612 if (static_cast<unsigned>(CFRuntime) <
8613 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
8614 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
8615 Fields[Count++] = { IntTy, "flags" };
8616 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
8617 Fields[Count++] = { LongTy, "length" };
8618 } else {
8619 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
8620 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
8621 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
8622 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
8625 Fields[Count++] = { IntTy, "_ptr" };
8626 else
8627 Fields[Count++] = { getUIntPtrType(), "_ptr" };
8628 }
8629
8630 // Create fields
8631 for (unsigned i = 0; i < Count; ++i) {
8632 FieldDecl *Field =
8633 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
8634 SourceLocation(), &Idents.get(Fields[i].Name),
8635 Fields[i].Type, /*TInfo=*/nullptr,
8636 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8637 Field->setAccess(AS_public);
8638 CFConstantStringTagDecl->addDecl(Field);
8639 }
8640
8641 CFConstantStringTagDecl->completeDefinition();
8642 // This type is designed to be compatible with NSConstantString, but cannot
8643 // use the same name, since NSConstantString is an interface.
8644 CanQualType tagType = getCanonicalTagType(CFConstantStringTagDecl);
8645 CFConstantStringTypeDecl =
8646 buildImplicitTypedef(tagType, "__NSConstantString");
8647
8648 return CFConstantStringTypeDecl;
8649}
8650
8652 if (!CFConstantStringTagDecl)
8653 getCFConstantStringDecl(); // Build the tag and the typedef.
8654 return CFConstantStringTagDecl;
8655}
8656
8657// getCFConstantStringType - Return the type used for constant CFStrings.
8662
8664 if (ObjCSuperType.isNull()) {
8665 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
8666 getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
8667 ObjCSuperType = getCanonicalTagType(ObjCSuperTypeDecl);
8668 }
8669 return ObjCSuperType;
8670}
8671
8673 const auto *TT = T->castAs<TypedefType>();
8674 CFConstantStringTypeDecl = cast<TypedefDecl>(TT->getDecl());
8675 CFConstantStringTagDecl = TT->castAsRecordDecl();
8676}
8677
8679 if (BlockDescriptorType)
8680 return getCanonicalTagType(BlockDescriptorType);
8681
8682 RecordDecl *RD;
8683 // FIXME: Needs the FlagAppleBlock bit.
8684 RD = buildImplicitRecord("__block_descriptor");
8685 RD->startDefinition();
8686
8687 QualType FieldTypes[] = {
8690 };
8691
8692 static const char *const FieldNames[] = {
8693 "reserved",
8694 "Size"
8695 };
8696
8697 for (size_t i = 0; i < 2; ++i) {
8699 *this, RD, SourceLocation(), SourceLocation(),
8700 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8701 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
8702 Field->setAccess(AS_public);
8703 RD->addDecl(Field);
8704 }
8705
8706 RD->completeDefinition();
8707
8708 BlockDescriptorType = RD;
8709
8710 return getCanonicalTagType(BlockDescriptorType);
8711}
8712
8714 if (BlockDescriptorExtendedType)
8715 return getCanonicalTagType(BlockDescriptorExtendedType);
8716
8717 RecordDecl *RD;
8718 // FIXME: Needs the FlagAppleBlock bit.
8719 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
8720 RD->startDefinition();
8721
8722 QualType FieldTypes[] = {
8727 };
8728
8729 static const char *const FieldNames[] = {
8730 "reserved",
8731 "Size",
8732 "CopyFuncPtr",
8733 "DestroyFuncPtr"
8734 };
8735
8736 for (size_t i = 0; i < 4; ++i) {
8738 *this, RD, SourceLocation(), SourceLocation(),
8739 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
8740 /*BitWidth=*/nullptr,
8741 /*Mutable=*/false, ICIS_NoInit);
8742 Field->setAccess(AS_public);
8743 RD->addDecl(Field);
8744 }
8745
8746 RD->completeDefinition();
8747
8748 BlockDescriptorExtendedType = RD;
8749 return getCanonicalTagType(BlockDescriptorExtendedType);
8750}
8751
8753 const auto *BT = dyn_cast<BuiltinType>(T);
8754
8755 if (!BT) {
8756 if (isa<PipeType>(T))
8757 return OCLTK_Pipe;
8758
8759 return OCLTK_Default;
8760 }
8761
8762 switch (BT->getKind()) {
8763#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8764 case BuiltinType::Id: \
8765 return OCLTK_Image;
8766#include "clang/Basic/OpenCLImageTypes.def"
8767
8768 case BuiltinType::OCLClkEvent:
8769 return OCLTK_ClkEvent;
8770
8771 case BuiltinType::OCLEvent:
8772 return OCLTK_Event;
8773
8774 case BuiltinType::OCLQueue:
8775 return OCLTK_Queue;
8776
8777 case BuiltinType::OCLReserveID:
8778 return OCLTK_ReserveID;
8779
8780 case BuiltinType::OCLSampler:
8781 return OCLTK_Sampler;
8782
8783 default:
8784 return OCLTK_Default;
8785 }
8786}
8787
8789 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
8790}
8791
8792/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
8793/// requires copy/dispose. Note that this must match the logic
8794/// in buildByrefHelpers.
8796 const VarDecl *D) {
8797 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
8798 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
8799 if (!copyExpr && record->hasTrivialDestructor()) return false;
8800
8801 return true;
8802 }
8803
8805 return true;
8806
8807 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
8808 // move or destroy.
8810 return true;
8811
8812 if (!Ty->isObjCRetainableType()) return false;
8813
8814 Qualifiers qs = Ty.getQualifiers();
8815
8816 // If we have lifetime, that dominates.
8817 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
8818 switch (lifetime) {
8819 case Qualifiers::OCL_None: llvm_unreachable("impossible");
8820
8821 // These are just bits as far as the runtime is concerned.
8824 return false;
8825
8826 // These cases should have been taken care of when checking the type's
8827 // non-triviality.
8830 llvm_unreachable("impossible");
8831 }
8832 llvm_unreachable("fell out of lifetime switch!");
8833 }
8834 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
8836}
8837
8839 Qualifiers::ObjCLifetime &LifeTime,
8840 bool &HasByrefExtendedLayout) const {
8841 if (!getLangOpts().ObjC ||
8842 getLangOpts().getGC() != LangOptions::NonGC)
8843 return false;
8844
8845 HasByrefExtendedLayout = false;
8846 if (Ty->isRecordType()) {
8847 HasByrefExtendedLayout = true;
8848 LifeTime = Qualifiers::OCL_None;
8849 } else if ((LifeTime = Ty.getObjCLifetime())) {
8850 // Honor the ARC qualifiers.
8851 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
8852 // The MRR rule.
8854 } else {
8855 LifeTime = Qualifiers::OCL_None;
8856 }
8857 return true;
8858}
8859
8861 assert(Target && "Expected target to be initialized");
8862 const llvm::Triple &T = Target->getTriple();
8863 // Windows is LLP64 rather than LP64
8864 if (T.isOSWindows() && T.isArch64Bit())
8865 return UnsignedLongLongTy;
8866 return UnsignedLongTy;
8867}
8868
8870 assert(Target && "Expected target to be initialized");
8871 const llvm::Triple &T = Target->getTriple();
8872 // Windows is LLP64 rather than LP64
8873 if (T.isOSWindows() && T.isArch64Bit())
8874 return LongLongTy;
8875 return LongTy;
8876}
8877
8879 if (!ObjCInstanceTypeDecl)
8880 ObjCInstanceTypeDecl =
8881 buildImplicitTypedef(getObjCIdType(), "instancetype");
8882 return ObjCInstanceTypeDecl;
8883}
8884
8885// This returns true if a type has been typedefed to BOOL:
8886// typedef <type> BOOL;
8888 if (const auto *TT = dyn_cast<TypedefType>(T))
8889 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
8890 return II->isStr("BOOL");
8891
8892 return false;
8893}
8894
8895/// getObjCEncodingTypeSize returns size of type for objective-c encoding
8896/// purpose.
8898 if (!type->isIncompleteArrayType() && type->isIncompleteType())
8899 return CharUnits::Zero();
8900
8902
8903 // Make all integer and enum types at least as large as an int
8904 if (sz.isPositive() && type->isIntegralOrEnumerationType())
8905 sz = std::max(sz, getTypeSizeInChars(IntTy));
8906 // Treat arrays as pointers, since that's how they're passed in.
8907 else if (type->isArrayType())
8909 return sz;
8910}
8911
8918
8921 if (!VD->isInline())
8923
8924 // In almost all cases, it's a weak definition.
8925 auto *First = VD->getFirstDecl();
8926 if (First->isInlineSpecified() || !First->isStaticDataMember())
8928
8929 // If there's a file-context declaration in this translation unit, it's a
8930 // non-discardable definition.
8931 for (auto *D : VD->redecls())
8933 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
8935
8936 // If we've not seen one yet, we don't know.
8938}
8939
8940static std::string charUnitsToString(CharUnits CU) {
8941 return llvm::itostr(CU.getQuantity());
8942}
8943
8944/// getObjCEncodingForBlock - Return the encoded type for this block
8945/// declaration.
8947 std::string S;
8948
8949 const BlockDecl *Decl = Expr->getBlockDecl();
8950 QualType BlockTy =
8952 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
8953 // Encode result type.
8954 if (getLangOpts().EncodeExtendedBlockSig)
8956 true /*Extended*/);
8957 else
8958 getObjCEncodingForType(BlockReturnTy, S);
8959 // Compute size of all parameters.
8960 // Start with computing size of a pointer in number of bytes.
8961 // FIXME: There might(should) be a better way of doing this computation!
8963 CharUnits ParmOffset = PtrSize;
8964 for (auto *PI : Decl->parameters()) {
8965 QualType PType = PI->getType();
8967 if (sz.isZero())
8968 continue;
8969 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
8970 ParmOffset += sz;
8971 }
8972 // Size of the argument frame
8973 S += charUnitsToString(ParmOffset);
8974 // Block pointer and offset.
8975 S += "@?0";
8976
8977 // Argument types.
8978 ParmOffset = PtrSize;
8979 for (auto *PVDecl : Decl->parameters()) {
8980 QualType PType = PVDecl->getOriginalType();
8981 if (const auto *AT =
8982 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
8983 // Use array's original type only if it has known number of
8984 // elements.
8985 if (!isa<ConstantArrayType>(AT))
8986 PType = PVDecl->getType();
8987 } else if (PType->isFunctionType())
8988 PType = PVDecl->getType();
8989 if (getLangOpts().EncodeExtendedBlockSig)
8991 S, true /*Extended*/);
8992 else
8993 getObjCEncodingForType(PType, S);
8994 S += charUnitsToString(ParmOffset);
8995 ParmOffset += getObjCEncodingTypeSize(PType);
8996 }
8997
8998 return S;
8999}
9000
9001std::string
9003 std::string S;
9004 // Encode result type.
9005 getObjCEncodingForType(Decl->getReturnType(), S);
9006 CharUnits ParmOffset;
9007 // Compute size of all parameters.
9008 for (auto *PI : Decl->parameters()) {
9009 QualType PType = PI->getType();
9011 if (sz.isZero())
9012 continue;
9013
9014 assert(sz.isPositive() &&
9015 "getObjCEncodingForFunctionDecl - Incomplete param type");
9016 ParmOffset += sz;
9017 }
9018 S += charUnitsToString(ParmOffset);
9019 ParmOffset = CharUnits::Zero();
9020
9021 // Argument types.
9022 for (auto *PVDecl : Decl->parameters()) {
9023 QualType PType = PVDecl->getOriginalType();
9024 if (const auto *AT =
9025 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9026 // Use array's original type only if it has known number of
9027 // elements.
9028 if (!isa<ConstantArrayType>(AT))
9029 PType = PVDecl->getType();
9030 } else if (PType->isFunctionType())
9031 PType = PVDecl->getType();
9032 getObjCEncodingForType(PType, S);
9033 S += charUnitsToString(ParmOffset);
9034 ParmOffset += getObjCEncodingTypeSize(PType);
9035 }
9036
9037 return S;
9038}
9039
9040/// getObjCEncodingForMethodParameter - Return the encoded type for a single
9041/// method parameter or return type. If Extended, include class names and
9042/// block object types.
9044 QualType T, std::string& S,
9045 bool Extended) const {
9046 // Encode type qualifier, 'in', 'inout', etc. for the parameter.
9048 // Encode parameter type.
9049 ObjCEncOptions Options = ObjCEncOptions()
9050 .setExpandPointedToStructures()
9051 .setExpandStructures()
9052 .setIsOutermostType();
9053 if (Extended)
9054 Options.setEncodeBlockParameters().setEncodeClassNames();
9055 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
9056}
9057
9058/// getObjCEncodingForMethodDecl - Return the encoded type for this method
9059/// declaration.
9061 bool Extended) const {
9062 // FIXME: This is not very efficient.
9063 // Encode return type.
9064 std::string S;
9065 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
9066 Decl->getReturnType(), S, Extended);
9067 // Compute size of all parameters.
9068 // Start with computing size of a pointer in number of bytes.
9069 // FIXME: There might(should) be a better way of doing this computation!
9071 // The first two arguments (self and _cmd) are pointers; account for
9072 // their size.
9073 CharUnits ParmOffset = 2 * PtrSize;
9074 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9075 E = Decl->sel_param_end(); PI != E; ++PI) {
9076 QualType PType = (*PI)->getType();
9078 if (sz.isZero())
9079 continue;
9080
9081 assert(sz.isPositive() &&
9082 "getObjCEncodingForMethodDecl - Incomplete param type");
9083 ParmOffset += sz;
9084 }
9085 S += charUnitsToString(ParmOffset);
9086 S += "@0:";
9087 S += charUnitsToString(PtrSize);
9088
9089 // Argument types.
9090 ParmOffset = 2 * PtrSize;
9091 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
9092 E = Decl->sel_param_end(); PI != E; ++PI) {
9093 const ParmVarDecl *PVDecl = *PI;
9094 QualType PType = PVDecl->getOriginalType();
9095 if (const auto *AT =
9096 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
9097 // Use array's original type only if it has known number of
9098 // elements.
9099 if (!isa<ConstantArrayType>(AT))
9100 PType = PVDecl->getType();
9101 } else if (PType->isFunctionType())
9102 PType = PVDecl->getType();
9104 PType, S, Extended);
9105 S += charUnitsToString(ParmOffset);
9106 ParmOffset += getObjCEncodingTypeSize(PType);
9107 }
9108
9109 return S;
9110}
9111
9114 const ObjCPropertyDecl *PD,
9115 const Decl *Container) const {
9116 if (!Container)
9117 return nullptr;
9118 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
9119 for (auto *PID : CID->property_impls())
9120 if (PID->getPropertyDecl() == PD)
9121 return PID;
9122 } else {
9123 const auto *OID = cast<ObjCImplementationDecl>(Container);
9124 for (auto *PID : OID->property_impls())
9125 if (PID->getPropertyDecl() == PD)
9126 return PID;
9127 }
9128 return nullptr;
9129}
9130
9131/// getObjCEncodingForPropertyDecl - Return the encoded type for this
9132/// property declaration. If non-NULL, Container must be either an
9133/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
9134/// NULL when getting encodings for protocol properties.
9135/// Property attributes are stored as a comma-delimited C string. The simple
9136/// attributes readonly and bycopy are encoded as single characters. The
9137/// parametrized attributes, getter=name, setter=name, and ivar=name, are
9138/// encoded as single characters, followed by an identifier. Property types
9139/// are also encoded as a parametrized attribute. The characters used to encode
9140/// these attributes are defined by the following enumeration:
9141/// @code
9142/// enum PropertyAttributes {
9143/// kPropertyReadOnly = 'R', // property is read-only.
9144/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
9145/// kPropertyByref = '&', // property is a reference to the value last assigned
9146/// kPropertyDynamic = 'D', // property is dynamic
9147/// kPropertyGetter = 'G', // followed by getter selector name
9148/// kPropertySetter = 'S', // followed by setter selector name
9149/// kPropertyInstanceVariable = 'V' // followed by instance variable name
9150/// kPropertyType = 'T' // followed by old-style type encoding.
9151/// kPropertyWeak = 'W' // 'weak' property
9152/// kPropertyStrong = 'P' // property GC'able
9153/// kPropertyNonAtomic = 'N' // property non-atomic
9154/// kPropertyOptional = '?' // property optional
9155/// };
9156/// @endcode
9157std::string
9159 const Decl *Container) const {
9160 // Collect information from the property implementation decl(s).
9161 bool Dynamic = false;
9162 ObjCPropertyImplDecl *SynthesizePID = nullptr;
9163
9164 if (ObjCPropertyImplDecl *PropertyImpDecl =
9166 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
9167 Dynamic = true;
9168 else
9169 SynthesizePID = PropertyImpDecl;
9170 }
9171
9172 // FIXME: This is not very efficient.
9173 std::string S = "T";
9174
9175 // Encode result type.
9176 // GCC has some special rules regarding encoding of properties which
9177 // closely resembles encoding of ivars.
9179
9180 if (PD->isOptional())
9181 S += ",?";
9182
9183 if (PD->isReadOnly()) {
9184 S += ",R";
9186 S += ",C";
9188 S += ",&";
9190 S += ",W";
9191 } else {
9192 switch (PD->getSetterKind()) {
9193 case ObjCPropertyDecl::Assign: break;
9194 case ObjCPropertyDecl::Copy: S += ",C"; break;
9195 case ObjCPropertyDecl::Retain: S += ",&"; break;
9196 case ObjCPropertyDecl::Weak: S += ",W"; break;
9197 }
9198 }
9199
9200 // It really isn't clear at all what this means, since properties
9201 // are "dynamic by default".
9202 if (Dynamic)
9203 S += ",D";
9204
9206 S += ",N";
9207
9209 S += ",G";
9210 S += PD->getGetterName().getAsString();
9211 }
9212
9214 S += ",S";
9215 S += PD->getSetterName().getAsString();
9216 }
9217
9218 if (SynthesizePID) {
9219 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
9220 S += ",V";
9221 S += OID->getNameAsString();
9222 }
9223
9224 // FIXME: OBJCGC: weak & strong
9225 return S;
9226}
9227
9228/// getLegacyIntegralTypeEncoding -
9229/// Another legacy compatibility encoding: 32-bit longs are encoded as
9230/// 'l' or 'L' , but not always. For typedefs, we need to use
9231/// 'i' or 'I' instead if encoding a struct field, or a pointer!
9233 if (PointeeTy->getAs<TypedefType>()) {
9234 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
9235 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
9236 PointeeTy = UnsignedIntTy;
9237 else
9238 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
9239 PointeeTy = IntTy;
9240 }
9241 }
9242}
9243
9245 const FieldDecl *Field,
9246 QualType *NotEncodedT) const {
9247 // We follow the behavior of gcc, expanding structures which are
9248 // directly pointed to, and expanding embedded structures. Note that
9249 // these rules are sufficient to prevent recursive encoding of the
9250 // same type.
9251 getObjCEncodingForTypeImpl(T, S,
9252 ObjCEncOptions()
9253 .setExpandPointedToStructures()
9254 .setExpandStructures()
9255 .setIsOutermostType(),
9256 Field, NotEncodedT);
9257}
9258
9260 std::string& S) const {
9261 // Encode result type.
9262 // GCC has some special rules regarding encoding of properties which
9263 // closely resembles encoding of ivars.
9264 getObjCEncodingForTypeImpl(T, S,
9265 ObjCEncOptions()
9266 .setExpandPointedToStructures()
9267 .setExpandStructures()
9268 .setIsOutermostType()
9269 .setEncodingProperty(),
9270 /*Field=*/nullptr);
9271}
9272
9274 const BuiltinType *BT) {
9276 switch (kind) {
9277 case BuiltinType::Void: return 'v';
9278 case BuiltinType::Bool: return 'B';
9279 case BuiltinType::Char8:
9280 case BuiltinType::Char_U:
9281 case BuiltinType::UChar: return 'C';
9282 case BuiltinType::Char16:
9283 case BuiltinType::UShort: return 'S';
9284 case BuiltinType::Char32:
9285 case BuiltinType::UInt: return 'I';
9286 case BuiltinType::ULong:
9287 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
9288 case BuiltinType::UInt128: return 'T';
9289 case BuiltinType::ULongLong: return 'Q';
9290 case BuiltinType::Char_S:
9291 case BuiltinType::SChar: return 'c';
9292 case BuiltinType::Short: return 's';
9293 case BuiltinType::WChar_S:
9294 case BuiltinType::WChar_U:
9295 case BuiltinType::Int: return 'i';
9296 case BuiltinType::Long:
9297 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
9298 case BuiltinType::LongLong: return 'q';
9299 case BuiltinType::Int128: return 't';
9300 case BuiltinType::Float: return 'f';
9301 case BuiltinType::Double: return 'd';
9302 case BuiltinType::LongDouble: return 'D';
9303 case BuiltinType::NullPtr: return '*'; // like char*
9304
9305 case BuiltinType::BFloat16:
9306 case BuiltinType::Float16:
9307 case BuiltinType::Float128:
9308 case BuiltinType::Ibm128:
9309 case BuiltinType::Half:
9310 case BuiltinType::ShortAccum:
9311 case BuiltinType::Accum:
9312 case BuiltinType::LongAccum:
9313 case BuiltinType::UShortAccum:
9314 case BuiltinType::UAccum:
9315 case BuiltinType::ULongAccum:
9316 case BuiltinType::ShortFract:
9317 case BuiltinType::Fract:
9318 case BuiltinType::LongFract:
9319 case BuiltinType::UShortFract:
9320 case BuiltinType::UFract:
9321 case BuiltinType::ULongFract:
9322 case BuiltinType::SatShortAccum:
9323 case BuiltinType::SatAccum:
9324 case BuiltinType::SatLongAccum:
9325 case BuiltinType::SatUShortAccum:
9326 case BuiltinType::SatUAccum:
9327 case BuiltinType::SatULongAccum:
9328 case BuiltinType::SatShortFract:
9329 case BuiltinType::SatFract:
9330 case BuiltinType::SatLongFract:
9331 case BuiltinType::SatUShortFract:
9332 case BuiltinType::SatUFract:
9333 case BuiltinType::SatULongFract:
9334 // FIXME: potentially need @encodes for these!
9335 return ' ';
9336
9337#define SVE_TYPE(Name, Id, SingletonId) \
9338 case BuiltinType::Id:
9339#include "clang/Basic/AArch64ACLETypes.def"
9340#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9341#include "clang/Basic/RISCVVTypes.def"
9342#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9343#include "clang/Basic/WebAssemblyReferenceTypes.def"
9344#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
9345#include "clang/Basic/AMDGPUTypes.def"
9346#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9347#include "clang/Basic/SPIRVTypes.def"
9348 {
9349 DiagnosticsEngine &Diags = C->getDiagnostics();
9350 Diags.Report(diag::err_unsupported_objc_primitive_encoding)
9351 << QualType(BT, 0);
9352 return ' ';
9353 }
9354
9355 case BuiltinType::ObjCId:
9356 case BuiltinType::ObjCClass:
9357 case BuiltinType::ObjCSel:
9358 llvm_unreachable("@encoding ObjC primitive type");
9359
9360 // OpenCL and placeholder types don't need @encodings.
9361#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9362 case BuiltinType::Id:
9363#include "clang/Basic/OpenCLImageTypes.def"
9364#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9365 case BuiltinType::Id:
9366#include "clang/Basic/OpenCLExtensionTypes.def"
9367 case BuiltinType::OCLEvent:
9368 case BuiltinType::OCLClkEvent:
9369 case BuiltinType::OCLQueue:
9370 case BuiltinType::OCLReserveID:
9371 case BuiltinType::OCLSampler:
9372 case BuiltinType::Dependent:
9373 case BuiltinType::MetaInfo:
9374#define PPC_VECTOR_TYPE(Name, Id, Size) \
9375 case BuiltinType::Id:
9376#include "clang/Basic/PPCTypes.def"
9377#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9378#include "clang/Basic/HLSLIntangibleTypes.def"
9379#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
9380#include "clang/Basic/HLSLPackedTypes.def"
9381#define BUILTIN_TYPE(KIND, ID)
9382#define PLACEHOLDER_TYPE(KIND, ID) \
9383 case BuiltinType::KIND:
9384#include "clang/AST/BuiltinTypes.def"
9385 llvm_unreachable("invalid builtin type for @encode");
9386 }
9387 llvm_unreachable("invalid BuiltinType::Kind value");
9388}
9389
9390static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED) {
9392
9393 // The encoding of an non-fixed enum type is always 'i', regardless of size.
9394 if (!Enum->isFixed())
9395 return 'i';
9396
9397 // The encoding of a fixed enum type matches its fixed underlying type.
9398 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
9400}
9401
9402static void EncodeBitField(const ASTContext *Ctx, std::string& S,
9403 QualType T, const FieldDecl *FD) {
9404 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
9405 S += 'b';
9406 // The NeXT runtime encodes bit fields as b followed by the number of bits.
9407 // The GNU runtime requires more information; bitfields are encoded as b,
9408 // then the offset (in bits) of the first element, then the type of the
9409 // bitfield, then the size in bits. For example, in this structure:
9410 //
9411 // struct
9412 // {
9413 // int integer;
9414 // int flags:2;
9415 // };
9416 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
9417 // runtime, but b32i2 for the GNU runtime. The reason for this extra
9418 // information is not especially sensible, but we're stuck with it for
9419 // compatibility with GCC, although providing it breaks anything that
9420 // actually uses runtime introspection and wants to work on both runtimes...
9421 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
9422 uint64_t Offset;
9423
9424 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
9425 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), IVD);
9426 } else {
9427 const RecordDecl *RD = FD->getParent();
9428 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
9429 Offset = RL.getFieldOffset(FD->getFieldIndex());
9430 }
9431
9432 S += llvm::utostr(Offset);
9433
9434 if (const auto *ET = T->getAsCanonical<EnumType>())
9435 S += ObjCEncodingForEnumDecl(Ctx, ET->getDecl());
9436 else {
9437 const auto *BT = T->castAs<BuiltinType>();
9438 S += getObjCEncodingForPrimitiveType(Ctx, BT);
9439 }
9440 }
9441 S += llvm::utostr(FD->getBitWidthValue());
9442}
9443
9444// Helper function for determining whether the encoded type string would include
9445// a template specialization type.
9447 bool VisitBasesAndFields) {
9448 T = T->getBaseElementTypeUnsafe();
9449
9450 if (auto *PT = T->getAs<PointerType>())
9452 PT->getPointeeType().getTypePtr(), false);
9453
9454 auto *CXXRD = T->getAsCXXRecordDecl();
9455
9456 if (!CXXRD)
9457 return false;
9458
9460 return true;
9461
9462 if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
9463 return false;
9464
9465 for (const auto &B : CXXRD->bases())
9466 if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
9467 true))
9468 return true;
9469
9470 for (auto *FD : CXXRD->fields())
9471 if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
9472 true))
9473 return true;
9474
9475 return false;
9476}
9477
9478// FIXME: Use SmallString for accumulating string.
9479void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
9480 const ObjCEncOptions Options,
9481 const FieldDecl *FD,
9482 QualType *NotEncodedT) const {
9484 switch (CT->getTypeClass()) {
9485 case Type::Builtin:
9486 case Type::Enum:
9487 if (FD && FD->isBitField())
9488 return EncodeBitField(this, S, T, FD);
9489 if (const auto *BT = dyn_cast<BuiltinType>(CT))
9490 S += getObjCEncodingForPrimitiveType(this, BT);
9491 else
9492 S += ObjCEncodingForEnumDecl(this, cast<EnumType>(CT)->getDecl());
9493 return;
9494
9495 case Type::Complex:
9496 S += 'j';
9497 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
9498 ObjCEncOptions(),
9499 /*Field=*/nullptr);
9500 return;
9501
9502 case Type::Atomic:
9503 S += 'A';
9504 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
9505 ObjCEncOptions(),
9506 /*Field=*/nullptr);
9507 return;
9508
9509 // encoding for pointer or reference types.
9510 case Type::Pointer:
9511 case Type::LValueReference:
9512 case Type::RValueReference: {
9513 QualType PointeeTy;
9514 if (isa<PointerType>(CT)) {
9515 const auto *PT = T->castAs<PointerType>();
9516 if (PT->isObjCSelType()) {
9517 S += ':';
9518 return;
9519 }
9520 PointeeTy = PT->getPointeeType();
9521 } else {
9522 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
9523 }
9524
9525 bool isReadOnly = false;
9526 // For historical/compatibility reasons, the read-only qualifier of the
9527 // pointee gets emitted _before_ the '^'. The read-only qualifier of
9528 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
9529 // Also, do not emit the 'r' for anything but the outermost type!
9530 if (T->getAs<TypedefType>()) {
9531 if (Options.IsOutermostType() && T.isConstQualified()) {
9532 isReadOnly = true;
9533 S += 'r';
9534 }
9535 } else if (Options.IsOutermostType()) {
9536 QualType P = PointeeTy;
9537 while (auto PT = P->getAs<PointerType>())
9538 P = PT->getPointeeType();
9539 if (P.isConstQualified()) {
9540 isReadOnly = true;
9541 S += 'r';
9542 }
9543 }
9544 if (isReadOnly) {
9545 // Another legacy compatibility encoding. Some ObjC qualifier and type
9546 // combinations need to be rearranged.
9547 // Rewrite "in const" from "nr" to "rn"
9548 if (StringRef(S).ends_with("nr"))
9549 S.replace(S.end()-2, S.end(), "rn");
9550 }
9551
9552 if (PointeeTy->isCharType()) {
9553 // char pointer types should be encoded as '*' unless it is a
9554 // type that has been typedef'd to 'BOOL'.
9555 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
9556 S += '*';
9557 return;
9558 }
9559 } else if (const auto *RTy = PointeeTy->getAsCanonical<RecordType>()) {
9560 const IdentifierInfo *II = RTy->getDecl()->getIdentifier();
9561 // GCC binary compat: Need to convert "struct objc_class *" to "#".
9562 if (II == &Idents.get("objc_class")) {
9563 S += '#';
9564 return;
9565 }
9566 // GCC binary compat: Need to convert "struct objc_object *" to "@".
9567 if (II == &Idents.get("objc_object")) {
9568 S += '@';
9569 return;
9570 }
9571 // If the encoded string for the class includes template names, just emit
9572 // "^v" for pointers to the class.
9573 if (getLangOpts().CPlusPlus &&
9574 (!getLangOpts().EncodeCXXClassTemplateSpec &&
9576 RTy, Options.ExpandPointedToStructures()))) {
9577 S += "^v";
9578 return;
9579 }
9580 // fall through...
9581 }
9582 S += '^';
9584
9585 ObjCEncOptions NewOptions;
9586 if (Options.ExpandPointedToStructures())
9587 NewOptions.setExpandStructures();
9588 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
9589 /*Field=*/nullptr, NotEncodedT);
9590 return;
9591 }
9592
9593 case Type::ConstantArray:
9594 case Type::IncompleteArray:
9595 case Type::VariableArray: {
9596 const auto *AT = cast<ArrayType>(CT);
9597
9598 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
9599 // Incomplete arrays are encoded as a pointer to the array element.
9600 S += '^';
9601
9602 getObjCEncodingForTypeImpl(
9603 AT->getElementType(), S,
9604 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
9605 } else {
9606 S += '[';
9607
9608 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
9609 S += llvm::utostr(CAT->getZExtSize());
9610 else {
9611 //Variable length arrays are encoded as a regular array with 0 elements.
9613 "Unknown array type!");
9614 S += '0';
9615 }
9616
9617 getObjCEncodingForTypeImpl(
9618 AT->getElementType(), S,
9619 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
9620 NotEncodedT);
9621 S += ']';
9622 }
9623 return;
9624 }
9625
9626 case Type::FunctionNoProto:
9627 case Type::FunctionProto:
9628 S += '?';
9629 return;
9630
9631 case Type::Record: {
9632 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
9633 S += RDecl->isUnion() ? '(' : '{';
9634 // Anonymous structures print as '?'
9635 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
9636 S += II->getName();
9637 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
9638 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
9639 llvm::raw_string_ostream OS(S);
9640 printTemplateArgumentList(OS, TemplateArgs.asArray(),
9642 }
9643 } else {
9644 S += '?';
9645 }
9646 if (Options.ExpandStructures()) {
9647 S += '=';
9648 if (!RDecl->isUnion()) {
9649 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
9650 } else {
9651 for (const auto *Field : RDecl->fields()) {
9652 if (FD) {
9653 S += '"';
9654 S += Field->getNameAsString();
9655 S += '"';
9656 }
9657
9658 // Special case bit-fields.
9659 if (Field->isBitField()) {
9660 getObjCEncodingForTypeImpl(Field->getType(), S,
9661 ObjCEncOptions().setExpandStructures(),
9662 Field);
9663 } else {
9664 QualType qt = Field->getType();
9666 getObjCEncodingForTypeImpl(
9667 qt, S,
9668 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
9669 NotEncodedT);
9670 }
9671 }
9672 }
9673 }
9674 S += RDecl->isUnion() ? ')' : '}';
9675 return;
9676 }
9677
9678 case Type::BlockPointer: {
9679 const auto *BT = T->castAs<BlockPointerType>();
9680 S += "@?"; // Unlike a pointer-to-function, which is "^?".
9681 if (Options.EncodeBlockParameters()) {
9682 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
9683
9684 S += '<';
9685 // Block return type
9686 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
9687 Options.forComponentType(), FD, NotEncodedT);
9688 // Block self
9689 S += "@?";
9690 // Block parameters
9691 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
9692 for (const auto &I : FPT->param_types())
9693 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
9694 NotEncodedT);
9695 }
9696 S += '>';
9697 }
9698 return;
9699 }
9700
9701 case Type::ObjCObject: {
9702 // hack to match legacy encoding of *id and *Class
9703 QualType Ty = getObjCObjectPointerType(CT);
9704 if (Ty->isObjCIdType()) {
9705 S += "{objc_object=}";
9706 return;
9707 }
9708 else if (Ty->isObjCClassType()) {
9709 S += "{objc_class=}";
9710 return;
9711 }
9712 // TODO: Double check to make sure this intentionally falls through.
9713 [[fallthrough]];
9714 }
9715
9716 case Type::ObjCInterface: {
9717 // Ignore protocol qualifiers when mangling at this level.
9718 // @encode(class_name)
9719 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
9720 S += '{';
9721 S += OI->getObjCRuntimeNameAsString();
9722 if (Options.ExpandStructures()) {
9723 S += '=';
9724 SmallVector<const ObjCIvarDecl*, 32> Ivars;
9725 DeepCollectObjCIvars(OI, true, Ivars);
9726 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
9727 const FieldDecl *Field = Ivars[i];
9728 if (Field->isBitField())
9729 getObjCEncodingForTypeImpl(Field->getType(), S,
9730 ObjCEncOptions().setExpandStructures(),
9731 Field);
9732 else
9733 getObjCEncodingForTypeImpl(Field->getType(), S,
9734 ObjCEncOptions().setExpandStructures(), FD,
9735 NotEncodedT);
9736 }
9737 }
9738 S += '}';
9739 return;
9740 }
9741
9742 case Type::ObjCObjectPointer: {
9743 const auto *OPT = T->castAs<ObjCObjectPointerType>();
9744 if (OPT->isObjCIdType()) {
9745 S += '@';
9746 return;
9747 }
9748
9749 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
9750 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
9751 // Since this is a binary compatibility issue, need to consult with
9752 // runtime folks. Fortunately, this is a *very* obscure construct.
9753 S += '#';
9754 return;
9755 }
9756
9757 if (OPT->isObjCQualifiedIdType()) {
9758 getObjCEncodingForTypeImpl(
9759 getObjCIdType(), S,
9760 Options.keepingOnly(ObjCEncOptions()
9761 .setExpandPointedToStructures()
9762 .setExpandStructures()),
9763 FD);
9764 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
9765 // Note that we do extended encoding of protocol qualifier list
9766 // Only when doing ivar or property encoding.
9767 S += '"';
9768 for (const auto *I : OPT->quals()) {
9769 S += '<';
9770 S += I->getObjCRuntimeNameAsString();
9771 S += '>';
9772 }
9773 S += '"';
9774 }
9775 return;
9776 }
9777
9778 S += '@';
9779 if (OPT->getInterfaceDecl() &&
9780 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
9781 S += '"';
9782 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
9783 for (const auto *I : OPT->quals()) {
9784 S += '<';
9785 S += I->getObjCRuntimeNameAsString();
9786 S += '>';
9787 }
9788 S += '"';
9789 }
9790 return;
9791 }
9792
9793 // gcc just blithely ignores member pointers.
9794 // FIXME: we should do better than that. 'M' is available.
9795 case Type::MemberPointer:
9796 // This matches gcc's encoding, even though technically it is insufficient.
9797 //FIXME. We should do a better job than gcc.
9798 case Type::Vector:
9799 case Type::ExtVector:
9800 // Until we have a coherent encoding of these three types, issue warning.
9801 if (NotEncodedT)
9802 *NotEncodedT = T;
9803 return;
9804
9805 case Type::ConstantMatrix:
9806 if (NotEncodedT)
9807 *NotEncodedT = T;
9808 return;
9809
9810 case Type::BitInt:
9811 if (NotEncodedT)
9812 *NotEncodedT = T;
9813 return;
9814
9815 // We could see an undeduced auto type here during error recovery.
9816 // Just ignore it.
9817 case Type::Auto:
9818 case Type::DeducedTemplateSpecialization:
9819 return;
9820
9821 case Type::HLSLAttributedResource:
9822 case Type::HLSLInlineSpirv:
9823 case Type::OverflowBehavior:
9824 llvm_unreachable("unexpected type");
9825
9826 case Type::ArrayParameter:
9827 case Type::Pipe:
9828#define ABSTRACT_TYPE(KIND, BASE)
9829#define TYPE(KIND, BASE)
9830#define DEPENDENT_TYPE(KIND, BASE) \
9831 case Type::KIND:
9832#define NON_CANONICAL_TYPE(KIND, BASE) \
9833 case Type::KIND:
9834#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
9835 case Type::KIND:
9836#include "clang/AST/TypeNodes.inc"
9837 llvm_unreachable("@encode for dependent type!");
9838 }
9839 llvm_unreachable("bad type kind!");
9840}
9841
9842void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
9843 std::string &S,
9844 const FieldDecl *FD,
9845 bool includeVBases,
9846 QualType *NotEncodedT) const {
9847 assert(RDecl && "Expected non-null RecordDecl");
9848 assert(!RDecl->isUnion() && "Should not be called for unions");
9849 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
9850 return;
9851
9852 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
9853 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
9854 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
9855
9856 if (CXXRec) {
9857 for (const auto &BI : CXXRec->bases()) {
9858 if (!BI.isVirtual()) {
9859 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9860 if (base->isEmpty())
9861 continue;
9862 uint64_t offs = toBits(layout.getBaseClassOffset(base));
9863 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9864 std::make_pair(offs, base));
9865 }
9866 }
9867 }
9868
9869 for (FieldDecl *Field : RDecl->fields()) {
9870 if (!Field->isZeroLengthBitField() && Field->isZeroSize(*this))
9871 continue;
9872 uint64_t offs = layout.getFieldOffset(Field->getFieldIndex());
9873 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9874 std::make_pair(offs, Field));
9875 }
9876
9877 if (CXXRec && includeVBases) {
9878 for (const auto &BI : CXXRec->vbases()) {
9879 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
9880 if (base->isEmpty())
9881 continue;
9882 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
9883 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
9884 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
9885 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
9886 std::make_pair(offs, base));
9887 }
9888 }
9889
9890 CharUnits size;
9891 if (CXXRec) {
9892 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
9893 } else {
9894 size = layout.getSize();
9895 }
9896
9897#ifndef NDEBUG
9898 uint64_t CurOffs = 0;
9899#endif
9900 std::multimap<uint64_t, NamedDecl *>::iterator
9901 CurLayObj = FieldOrBaseOffsets.begin();
9902
9903 if (CXXRec && CXXRec->isDynamicClass() &&
9904 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
9905 if (FD) {
9906 S += "\"_vptr$";
9907 std::string recname = CXXRec->getNameAsString();
9908 if (recname.empty()) recname = "?";
9909 S += recname;
9910 S += '"';
9911 }
9912 S += "^^?";
9913#ifndef NDEBUG
9914 CurOffs += getTypeSize(VoidPtrTy);
9915#endif
9916 }
9917
9918 if (!RDecl->hasFlexibleArrayMember()) {
9919 // Mark the end of the structure.
9920 uint64_t offs = toBits(size);
9921 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
9922 std::make_pair(offs, nullptr));
9923 }
9924
9925 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
9926#ifndef NDEBUG
9927 assert(CurOffs <= CurLayObj->first);
9928 if (CurOffs < CurLayObj->first) {
9929 uint64_t padding = CurLayObj->first - CurOffs;
9930 // FIXME: There doesn't seem to be a way to indicate in the encoding that
9931 // packing/alignment of members is different that normal, in which case
9932 // the encoding will be out-of-sync with the real layout.
9933 // If the runtime switches to just consider the size of types without
9934 // taking into account alignment, we could make padding explicit in the
9935 // encoding (e.g. using arrays of chars). The encoding strings would be
9936 // longer then though.
9937 CurOffs += padding;
9938 }
9939#endif
9940
9941 NamedDecl *dcl = CurLayObj->second;
9942 if (!dcl)
9943 break; // reached end of structure.
9944
9945 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
9946 // We expand the bases without their virtual bases since those are going
9947 // in the initial structure. Note that this differs from gcc which
9948 // expands virtual bases each time one is encountered in the hierarchy,
9949 // making the encoding type bigger than it really is.
9950 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
9951 NotEncodedT);
9952 assert(!base->isEmpty());
9953#ifndef NDEBUG
9954 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
9955#endif
9956 } else {
9957 const auto *field = cast<FieldDecl>(dcl);
9958 if (FD) {
9959 S += '"';
9960 S += field->getNameAsString();
9961 S += '"';
9962 }
9963
9964 if (field->isBitField()) {
9965 EncodeBitField(this, S, field->getType(), field);
9966#ifndef NDEBUG
9967 CurOffs += field->getBitWidthValue();
9968#endif
9969 } else {
9970 QualType qt = field->getType();
9972 getObjCEncodingForTypeImpl(
9973 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
9974 FD, NotEncodedT);
9975#ifndef NDEBUG
9976 CurOffs += getTypeSize(field->getType());
9977#endif
9978 }
9979 }
9980 }
9981}
9982
9984 std::string& S) const {
9985 if (QT & Decl::OBJC_TQ_In)
9986 S += 'n';
9987 if (QT & Decl::OBJC_TQ_Inout)
9988 S += 'N';
9989 if (QT & Decl::OBJC_TQ_Out)
9990 S += 'o';
9991 if (QT & Decl::OBJC_TQ_Bycopy)
9992 S += 'O';
9993 if (QT & Decl::OBJC_TQ_Byref)
9994 S += 'R';
9995 if (QT & Decl::OBJC_TQ_Oneway)
9996 S += 'V';
9997}
9998
10000 if (!ObjCIdDecl) {
10003 ObjCIdDecl = buildImplicitTypedef(T, "id");
10004 }
10005 return ObjCIdDecl;
10006}
10007
10009 if (!ObjCSelDecl) {
10011 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
10012 }
10013 return ObjCSelDecl;
10014}
10015
10017 if (!ObjCClassDecl) {
10020 ObjCClassDecl = buildImplicitTypedef(T, "Class");
10021 }
10022 return ObjCClassDecl;
10023}
10024
10026 if (!ObjCProtocolClassDecl) {
10027 ObjCProtocolClassDecl
10030 &Idents.get("Protocol"),
10031 /*typeParamList=*/nullptr,
10032 /*PrevDecl=*/nullptr,
10033 SourceLocation(), true);
10034 }
10035
10036 return ObjCProtocolClassDecl;
10037}
10038
10040 if (!getLangOpts().PointerAuthObjcInterfaceSel)
10041 return PointerAuthQualifier();
10043 getLangOpts().PointerAuthObjcInterfaceSelKey,
10044 /*isAddressDiscriminated=*/true, SelPointerConstantDiscriminator,
10046 /*isIsaPointer=*/false,
10047 /*authenticatesNullValues=*/false);
10048}
10049
10050//===----------------------------------------------------------------------===//
10051// __builtin_va_list Construction Functions
10052//===----------------------------------------------------------------------===//
10053
10055 StringRef Name) {
10056 // typedef char* __builtin[_ms]_va_list;
10057 QualType T = Context->getPointerType(Context->CharTy);
10058 return Context->buildImplicitTypedef(T, Name);
10059}
10060
10062 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
10063}
10064
10066 // typedef char *__builtin_zos_va_list[2];
10067 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 2);
10068 QualType T = Context->getPointerType(Context->CharTy);
10069 QualType ArrayType = Context->getConstantArrayType(
10070 T, Size, nullptr, ArraySizeModifier::Normal, 0);
10071 return Context->buildImplicitTypedef(ArrayType, "__builtin_zos_va_list");
10072}
10073
10075 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
10076}
10077
10079 // typedef void* __builtin_va_list;
10080 QualType T = Context->getPointerType(Context->VoidTy);
10081 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10082}
10083
10084static TypedefDecl *
10086 // struct __va_list
10087 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
10088 if (Context->getLangOpts().CPlusPlus) {
10089 // namespace std { struct __va_list {
10090 auto *NS = NamespaceDecl::Create(
10091 const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
10092 /*Inline=*/false, SourceLocation(), SourceLocation(),
10093 &Context->Idents.get("std"),
10094 /*PrevDecl=*/nullptr, /*Nested=*/false);
10095 NS->setImplicit();
10097 }
10098
10099 VaListTagDecl->startDefinition();
10100
10101 const size_t NumFields = 5;
10102 QualType FieldTypes[NumFields];
10103 const char *FieldNames[NumFields];
10104
10105 // void *__stack;
10106 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10107 FieldNames[0] = "__stack";
10108
10109 // void *__gr_top;
10110 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10111 FieldNames[1] = "__gr_top";
10112
10113 // void *__vr_top;
10114 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10115 FieldNames[2] = "__vr_top";
10116
10117 // int __gr_offs;
10118 FieldTypes[3] = Context->IntTy;
10119 FieldNames[3] = "__gr_offs";
10120
10121 // int __vr_offs;
10122 FieldTypes[4] = Context->IntTy;
10123 FieldNames[4] = "__vr_offs";
10124
10125 // Create fields
10126 for (unsigned i = 0; i < NumFields; ++i) {
10127 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10131 &Context->Idents.get(FieldNames[i]),
10132 FieldTypes[i], /*TInfo=*/nullptr,
10133 /*BitWidth=*/nullptr,
10134 /*Mutable=*/false,
10135 ICIS_NoInit);
10136 Field->setAccess(AS_public);
10137 VaListTagDecl->addDecl(Field);
10138 }
10139 VaListTagDecl->completeDefinition();
10140 Context->VaListTagDecl = VaListTagDecl;
10141 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10142
10143 // } __builtin_va_list;
10144 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10145}
10146
10148 // typedef struct __va_list_tag {
10150
10151 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10152 VaListTagDecl->startDefinition();
10153
10154 const size_t NumFields = 5;
10155 QualType FieldTypes[NumFields];
10156 const char *FieldNames[NumFields];
10157
10158 // unsigned char gpr;
10159 FieldTypes[0] = Context->UnsignedCharTy;
10160 FieldNames[0] = "gpr";
10161
10162 // unsigned char fpr;
10163 FieldTypes[1] = Context->UnsignedCharTy;
10164 FieldNames[1] = "fpr";
10165
10166 // unsigned short reserved;
10167 FieldTypes[2] = Context->UnsignedShortTy;
10168 FieldNames[2] = "reserved";
10169
10170 // void* overflow_arg_area;
10171 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10172 FieldNames[3] = "overflow_arg_area";
10173
10174 // void* reg_save_area;
10175 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
10176 FieldNames[4] = "reg_save_area";
10177
10178 // Create fields
10179 for (unsigned i = 0; i < NumFields; ++i) {
10180 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
10183 &Context->Idents.get(FieldNames[i]),
10184 FieldTypes[i], /*TInfo=*/nullptr,
10185 /*BitWidth=*/nullptr,
10186 /*Mutable=*/false,
10187 ICIS_NoInit);
10188 Field->setAccess(AS_public);
10189 VaListTagDecl->addDecl(Field);
10190 }
10191 VaListTagDecl->completeDefinition();
10192 Context->VaListTagDecl = VaListTagDecl;
10193 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10194
10195 // } __va_list_tag;
10196 TypedefDecl *VaListTagTypedefDecl =
10197 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10198
10199 QualType VaListTagTypedefType =
10200 Context->getTypedefType(ElaboratedTypeKeyword::None,
10201 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10202
10203 // typedef __va_list_tag __builtin_va_list[1];
10204 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10205 QualType VaListTagArrayType = Context->getConstantArrayType(
10206 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10207 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10208}
10209
10210static TypedefDecl *
10212 // struct __va_list_tag {
10214 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10215 VaListTagDecl->startDefinition();
10216
10217 const size_t NumFields = 4;
10218 QualType FieldTypes[NumFields];
10219 const char *FieldNames[NumFields];
10220
10221 // unsigned gp_offset;
10222 FieldTypes[0] = Context->UnsignedIntTy;
10223 FieldNames[0] = "gp_offset";
10224
10225 // unsigned fp_offset;
10226 FieldTypes[1] = Context->UnsignedIntTy;
10227 FieldNames[1] = "fp_offset";
10228
10229 // void* overflow_arg_area;
10230 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10231 FieldNames[2] = "overflow_arg_area";
10232
10233 // void* reg_save_area;
10234 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10235 FieldNames[3] = "reg_save_area";
10236
10237 // Create fields
10238 for (unsigned i = 0; i < NumFields; ++i) {
10239 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10243 &Context->Idents.get(FieldNames[i]),
10244 FieldTypes[i], /*TInfo=*/nullptr,
10245 /*BitWidth=*/nullptr,
10246 /*Mutable=*/false,
10247 ICIS_NoInit);
10248 Field->setAccess(AS_public);
10249 VaListTagDecl->addDecl(Field);
10250 }
10251 VaListTagDecl->completeDefinition();
10252 Context->VaListTagDecl = VaListTagDecl;
10253 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10254
10255 // };
10256
10257 // typedef struct __va_list_tag __builtin_va_list[1];
10258 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10259 QualType VaListTagArrayType = Context->getConstantArrayType(
10260 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10261 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10262}
10263
10264static TypedefDecl *
10266 // struct __va_list
10267 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
10268 if (Context->getLangOpts().CPlusPlus) {
10269 // namespace std { struct __va_list {
10270 NamespaceDecl *NS;
10271 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
10272 Context->getTranslationUnitDecl(),
10273 /*Inline=*/false, SourceLocation(),
10274 SourceLocation(), &Context->Idents.get("std"),
10275 /*PrevDecl=*/nullptr, /*Nested=*/false);
10276 NS->setImplicit();
10277 VaListDecl->setDeclContext(NS);
10278 }
10279
10280 VaListDecl->startDefinition();
10281
10282 // void * __ap;
10283 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10284 VaListDecl,
10287 &Context->Idents.get("__ap"),
10288 Context->getPointerType(Context->VoidTy),
10289 /*TInfo=*/nullptr,
10290 /*BitWidth=*/nullptr,
10291 /*Mutable=*/false,
10292 ICIS_NoInit);
10293 Field->setAccess(AS_public);
10294 VaListDecl->addDecl(Field);
10295
10296 // };
10297 VaListDecl->completeDefinition();
10298 Context->VaListTagDecl = VaListDecl;
10299
10300 // typedef struct __va_list __builtin_va_list;
10301 CanQualType T = Context->getCanonicalTagType(VaListDecl);
10302 return Context->buildImplicitTypedef(T, "__builtin_va_list");
10303}
10304
10305static TypedefDecl *
10307 // struct __va_list_tag {
10309 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10310 VaListTagDecl->startDefinition();
10311
10312 const size_t NumFields = 4;
10313 QualType FieldTypes[NumFields];
10314 const char *FieldNames[NumFields];
10315
10316 // long __gpr;
10317 FieldTypes[0] = Context->LongTy;
10318 FieldNames[0] = "__gpr";
10319
10320 // long __fpr;
10321 FieldTypes[1] = Context->LongTy;
10322 FieldNames[1] = "__fpr";
10323
10324 // void *__overflow_arg_area;
10325 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10326 FieldNames[2] = "__overflow_arg_area";
10327
10328 // void *__reg_save_area;
10329 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
10330 FieldNames[3] = "__reg_save_area";
10331
10332 // Create fields
10333 for (unsigned i = 0; i < NumFields; ++i) {
10334 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
10338 &Context->Idents.get(FieldNames[i]),
10339 FieldTypes[i], /*TInfo=*/nullptr,
10340 /*BitWidth=*/nullptr,
10341 /*Mutable=*/false,
10342 ICIS_NoInit);
10343 Field->setAccess(AS_public);
10344 VaListTagDecl->addDecl(Field);
10345 }
10346 VaListTagDecl->completeDefinition();
10347 Context->VaListTagDecl = VaListTagDecl;
10348 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10349
10350 // };
10351
10352 // typedef __va_list_tag __builtin_va_list[1];
10353 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10354 QualType VaListTagArrayType = Context->getConstantArrayType(
10355 VaListTagType, Size, nullptr, ArraySizeModifier::Normal, 0);
10356
10357 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10358}
10359
10361 // typedef struct __va_list_tag {
10363 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10364 VaListTagDecl->startDefinition();
10365
10366 const size_t NumFields = 3;
10367 QualType FieldTypes[NumFields];
10368 const char *FieldNames[NumFields];
10369
10370 // void *CurrentSavedRegisterArea;
10371 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
10372 FieldNames[0] = "__current_saved_reg_area_pointer";
10373
10374 // void *SavedRegAreaEnd;
10375 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
10376 FieldNames[1] = "__saved_reg_area_end_pointer";
10377
10378 // void *OverflowArea;
10379 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
10380 FieldNames[2] = "__overflow_area_pointer";
10381
10382 // Create fields
10383 for (unsigned i = 0; i < NumFields; ++i) {
10385 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
10386 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
10387 /*TInfo=*/nullptr,
10388 /*BitWidth=*/nullptr,
10389 /*Mutable=*/false, ICIS_NoInit);
10390 Field->setAccess(AS_public);
10391 VaListTagDecl->addDecl(Field);
10392 }
10393 VaListTagDecl->completeDefinition();
10394 Context->VaListTagDecl = VaListTagDecl;
10395 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10396
10397 // } __va_list_tag;
10398 TypedefDecl *VaListTagTypedefDecl =
10399 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
10400
10401 QualType VaListTagTypedefType =
10402 Context->getTypedefType(ElaboratedTypeKeyword::None,
10403 /*Qualifier=*/std::nullopt, VaListTagTypedefDecl);
10404
10405 // typedef __va_list_tag __builtin_va_list[1];
10406 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
10407 QualType VaListTagArrayType = Context->getConstantArrayType(
10408 VaListTagTypedefType, Size, nullptr, ArraySizeModifier::Normal, 0);
10409
10410 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
10411}
10412
10413static TypedefDecl *
10415 // typedef struct __va_list_tag {
10416 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
10417
10418 VaListTagDecl->startDefinition();
10419
10420 // int* __va_stk;
10421 // int* __va_reg;
10422 // int __va_ndx;
10423 constexpr size_t NumFields = 3;
10424 QualType FieldTypes[NumFields] = {Context->getPointerType(Context->IntTy),
10425 Context->getPointerType(Context->IntTy),
10426 Context->IntTy};
10427 const char *FieldNames[NumFields] = {"__va_stk", "__va_reg", "__va_ndx"};
10428
10429 // Create fields
10430 for (unsigned i = 0; i < NumFields; ++i) {
10433 &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
10434 /*BitWidth=*/nullptr,
10435 /*Mutable=*/false, ICIS_NoInit);
10436 Field->setAccess(AS_public);
10437 VaListTagDecl->addDecl(Field);
10438 }
10439 VaListTagDecl->completeDefinition();
10440 Context->VaListTagDecl = VaListTagDecl;
10441 CanQualType VaListTagType = Context->getCanonicalTagType(VaListTagDecl);
10442
10443 // } __va_list_tag;
10444 TypedefDecl *VaListTagTypedefDecl =
10445 Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
10446
10447 return VaListTagTypedefDecl;
10448}
10449
10452 switch (Kind) {
10454 return CreateCharPtrBuiltinVaListDecl(Context);
10456 return CreateVoidPtrBuiltinVaListDecl(Context);
10458 return CreateAArch64ABIBuiltinVaListDecl(Context);
10460 return CreatePowerABIBuiltinVaListDecl(Context);
10462 return CreateX86_64ABIBuiltinVaListDecl(Context);
10464 return CreateAAPCSABIBuiltinVaListDecl(Context);
10466 return CreateSystemZBuiltinVaListDecl(Context);
10468 return CreateHexagonBuiltinVaListDecl(Context);
10470 return CreateXtensaABIBuiltinVaListDecl(Context);
10471 }
10472
10473 llvm_unreachable("Unhandled __builtin_va_list type kind");
10474}
10475
10477 if (!BuiltinVaListDecl) {
10478 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
10479 assert(BuiltinVaListDecl->isImplicit());
10480 }
10481
10482 return BuiltinVaListDecl;
10483}
10484
10486 // Force the creation of VaListTagDecl by building the __builtin_va_list
10487 // declaration.
10488 if (!VaListTagDecl)
10489 (void)getBuiltinVaListDecl();
10490
10491 return VaListTagDecl;
10492}
10493
10495 if (!BuiltinMSVaListDecl)
10496 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
10497
10498 return BuiltinMSVaListDecl;
10499}
10500
10502 if (!BuiltinZOSVaListDecl)
10503 BuiltinZOSVaListDecl = CreateZOSVaListDecl(this);
10504
10505 return BuiltinZOSVaListDecl;
10506}
10507
10509 // Allow redecl custom type checking builtin for HLSL.
10510 if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
10511 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10512 return true;
10513 // Allow redecl custom type checking builtin for SPIR-V.
10514 if (getTargetInfo().getTriple().isSPIROrSPIRV() &&
10515 BuiltinInfo.isTSBuiltin(FD->getBuiltinID()) &&
10516 BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
10517 return true;
10518 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
10519}
10520
10522 assert(ObjCConstantStringType.isNull() &&
10523 "'NSConstantString' type already set!");
10524
10525 ObjCConstantStringType = getObjCInterfaceType(Decl);
10526}
10527
10528/// Retrieve the template name that corresponds to a non-empty
10529/// lookup.
10532 UnresolvedSetIterator End) const {
10533 unsigned size = End - Begin;
10534 assert(size > 1 && "set is not overloaded!");
10535
10536 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
10537 size * sizeof(FunctionTemplateDecl*));
10538 auto *OT = new (memory) OverloadedTemplateStorage(size);
10539
10540 NamedDecl **Storage = OT->getStorage();
10541 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
10542 NamedDecl *D = *I;
10543 assert(isa<FunctionTemplateDecl>(D) ||
10547 *Storage++ = D;
10548 }
10549
10550 return TemplateName(OT);
10551}
10552
10553/// Retrieve a template name representing an unqualified-id that has been
10554/// assumed to name a template for ADL purposes.
10556 auto *OT = new (*this) AssumedTemplateStorage(Name);
10557 return TemplateName(OT);
10558}
10559
10560/// Retrieve the template name that represents a qualified
10561/// template name such as \c std::vector.
10563 bool TemplateKeyword,
10564 TemplateName Template) const {
10565 assert(Template.getKind() == TemplateName::Template ||
10567
10568 if (Template.getAsTemplateDecl()->getKind() == Decl::TemplateTemplateParm) {
10569 assert(!Qualifier && "unexpected qualified template template parameter");
10570 assert(TemplateKeyword == false);
10571 return Template;
10572 }
10573
10574 // FIXME: Canonicalization?
10575 llvm::FoldingSetNodeID ID;
10576 QualifiedTemplateName::Profile(ID, Qualifier, TemplateKeyword, Template);
10577
10578 llvm::FoldingSetInsertToken Token;
10579 QualifiedTemplateName *QTN = QualifiedTemplateNames.lookup(ID, Token);
10580 if (!QTN) {
10581 QTN = new (*this, alignof(QualifiedTemplateName))
10582 QualifiedTemplateName(Qualifier, TemplateKeyword, Template);
10583 QualifiedTemplateNames.insert(QTN, Token);
10584 }
10585
10586 return TemplateName(QTN);
10587}
10588
10589/// Retrieve the template name that represents a dependent
10590/// template name such as \c MetaFun::template operator+.
10593 llvm::FoldingSetNodeID ID;
10594 S.Profile(ID);
10595
10596 llvm::FoldingSetInsertToken Token;
10597 if (DependentTemplateName *QTN = DependentTemplateNames.lookup(ID, Token))
10598 return TemplateName(QTN);
10599
10601 new (*this, alignof(DependentTemplateName)) DependentTemplateName(S);
10602 DependentTemplateNames.insert(QTN, Token);
10603 return TemplateName(QTN);
10604}
10605
10607 Decl *AssociatedDecl,
10608 unsigned Index,
10610 bool Final) const {
10611 llvm::FoldingSetNodeID ID;
10612 SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
10613 Index, PackIndex, Final);
10614
10615 llvm::FoldingSetInsertToken Token;
10617 SubstTemplateTemplateParms.lookup(ID, Token);
10618
10619 if (!subst) {
10620 subst = new (*this) SubstTemplateTemplateParmStorage(
10621 Replacement, AssociatedDecl, Index, PackIndex, Final);
10622 SubstTemplateTemplateParms.insert(subst, Token);
10623 }
10624
10625 return TemplateName(subst);
10626}
10627
10630 Decl *AssociatedDecl,
10631 unsigned Index, bool Final) const {
10632 auto &Self = const_cast<ASTContext &>(*this);
10633 llvm::FoldingSetNodeID ID;
10635 AssociatedDecl, Index, Final);
10636
10637 llvm::FoldingSetInsertToken Token;
10639 SubstTemplateTemplateParmPacks.lookup(ID, Token);
10640
10641 if (!Subst) {
10642 Subst = new (*this) SubstTemplateTemplateParmPackStorage(
10643 ArgPack.pack_elements(), AssociatedDecl, Index, Final);
10644 SubstTemplateTemplateParmPacks.insert(Subst, Token);
10645 }
10646
10647 return TemplateName(Subst);
10648}
10649
10650/// Retrieve the template name that represents a template name
10651/// deduced from a specialization.
10654 DefaultArguments DefaultArgs) const {
10655 if (!DefaultArgs)
10656 return Underlying;
10657
10658 llvm::FoldingSetNodeID ID;
10659 DeducedTemplateStorage::Profile(ID, *this, Underlying, DefaultArgs);
10660
10661 llvm::FoldingSetInsertToken Token;
10662 DeducedTemplateStorage *DTS = DeducedTemplates.lookup(ID, Token);
10663 if (!DTS) {
10664 void *Mem = Allocate(sizeof(DeducedTemplateStorage) +
10665 sizeof(TemplateArgument) * DefaultArgs.Args.size(),
10666 alignof(DeducedTemplateStorage));
10667 DTS = new (Mem) DeducedTemplateStorage(Underlying, DefaultArgs);
10668 DeducedTemplates.insert(DTS, Token);
10669 }
10670 return TemplateName(DTS);
10671}
10672
10674 TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted,
10675 ArrayRef<TemplateName> Expansions) const {
10676 auto &Self = const_cast<ASTContext &>(*this);
10677 llvm::FoldingSetNodeID ID;
10678 PackIndexingTemplateStorage::Profile(ID, Self, Pattern, IndexExpr,
10679 FullySubstituted, Expansions);
10680
10681 llvm::FoldingSetInsertToken Token;
10682 PackIndexingTemplateStorage *PI = PackIndexingTemplates.lookup(ID, Token);
10683 if (!PI) {
10684 void *Mem =
10685 Allocate(PackIndexingTemplateStorage::totalSizeToAlloc<TemplateName>(
10686 Expansions.size()),
10688 PI = new (Mem) PackIndexingTemplateStorage(Pattern, IndexExpr,
10689 FullySubstituted, Expansions);
10690 PackIndexingTemplates.insert(PI, Token);
10691 }
10692 return TemplateName(PI);
10693}
10694
10695/// getFromTargetType - Given one of the integer types provided by
10696/// TargetInfo, produce the corresponding type. The unsigned @p Type
10697/// is actually a value of type @c TargetInfo::IntType.
10698CanQualType ASTContext::getFromTargetType(unsigned Type) const {
10699 switch (Type) {
10700 case TargetInfo::NoInt: return {};
10703 case TargetInfo::SignedShort: return ShortTy;
10705 case TargetInfo::SignedInt: return IntTy;
10707 case TargetInfo::SignedLong: return LongTy;
10711 }
10712
10713 llvm_unreachable("Unhandled TargetInfo::IntType value");
10714}
10715
10716//===----------------------------------------------------------------------===//
10717// Type Predicates.
10718//===----------------------------------------------------------------------===//
10719
10720/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
10721/// garbage collection attribute.
10722///
10724 if (getLangOpts().getGC() == LangOptions::NonGC)
10725 return Qualifiers::GCNone;
10726
10727 assert(getLangOpts().ObjC);
10728 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
10729
10730 // Default behaviour under objective-C's gc is for ObjC pointers
10731 // (or pointers to them) be treated as though they were declared
10732 // as __strong.
10733 if (GCAttrs == Qualifiers::GCNone) {
10735 return Qualifiers::Strong;
10736 else if (Ty->isPointerType())
10738 } else {
10739 // It's not valid to set GC attributes on anything that isn't a
10740 // pointer.
10741#ifndef NDEBUG
10743 while (const auto *AT = dyn_cast<ArrayType>(CT))
10744 CT = AT->getElementType();
10745 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
10746#endif
10747 }
10748 return GCAttrs;
10749}
10750
10751//===----------------------------------------------------------------------===//
10752// Type Compatibility Testing
10753//===----------------------------------------------------------------------===//
10754
10755/// areCompatVectorTypes - Return true if the two specified vector types are
10756/// compatible.
10757static bool areCompatVectorTypes(const VectorType *LHS,
10758 const VectorType *RHS) {
10759 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10760 return LHS->getElementType() == RHS->getElementType() &&
10761 LHS->getNumElements() == RHS->getNumElements();
10762}
10763
10764/// areCompatMatrixTypes - Return true if the two specified matrix types are
10765/// compatible.
10767 const ConstantMatrixType *RHS) {
10768 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
10769 return LHS->getElementType() == RHS->getElementType() &&
10770 LHS->getNumRows() == RHS->getNumRows() &&
10771 LHS->getNumColumns() == RHS->getNumColumns();
10772}
10773
10775 QualType SecondVec) {
10776 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
10777 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
10778
10779 if (hasSameUnqualifiedType(FirstVec, SecondVec))
10780 return true;
10781
10782 // Treat Neon vector types and most AltiVec vector types as if they are the
10783 // equivalent GCC vector types.
10784 const auto *First = FirstVec->castAs<VectorType>();
10785 const auto *Second = SecondVec->castAs<VectorType>();
10786 if (First->getNumElements() == Second->getNumElements() &&
10787 hasSameType(First->getElementType(), Second->getElementType()) &&
10788 First->getVectorKind() != VectorKind::AltiVecPixel &&
10789 First->getVectorKind() != VectorKind::AltiVecBool &&
10792 First->getVectorKind() != VectorKind::SveFixedLengthData &&
10793 First->getVectorKind() != VectorKind::SveFixedLengthPredicate &&
10796 First->getVectorKind() != VectorKind::RVVFixedLengthData &&
10798 First->getVectorKind() != VectorKind::RVVFixedLengthMask &&
10800 First->getVectorKind() != VectorKind::RVVFixedLengthMask_1 &&
10802 First->getVectorKind() != VectorKind::RVVFixedLengthMask_2 &&
10804 First->getVectorKind() != VectorKind::RVVFixedLengthMask_4 &&
10806 return true;
10807
10808 // In OpenCL, treat half and _Float16 vector types as compatible.
10809 if (getLangOpts().OpenCL &&
10810 First->getNumElements() == Second->getNumElements()) {
10811 QualType FirstElt = First->getElementType();
10812 QualType SecondElt = Second->getElementType();
10813
10814 if ((FirstElt->isFloat16Type() && SecondElt->isHalfType()) ||
10815 (FirstElt->isHalfType() && SecondElt->isFloat16Type())) {
10816 if (First->getVectorKind() != VectorKind::AltiVecPixel &&
10817 First->getVectorKind() != VectorKind::AltiVecBool &&
10820 return true;
10821 }
10822 }
10823 return false;
10824}
10825
10831
10834 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
10835 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
10836
10837 if (!LHSOBT && !RHSOBT)
10839
10840 if (LHSOBT && RHSOBT) {
10841 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
10844 }
10845
10846 QualType LHSUnderlying = LHSOBT ? LHSOBT->desugar() : LHS;
10847 QualType RHSUnderlying = RHSOBT ? RHSOBT->desugar() : RHS;
10848
10849 if (RHSOBT && !LHSOBT) {
10850 if (LHSUnderlying->isIntegerType() && RHSUnderlying->isIntegerType())
10852 }
10853
10855}
10856
10857/// getRVVTypeSize - Return RVV vector register size.
10858static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty) {
10859 assert(Ty->isRVVVLSBuiltinType() && "Invalid RVV Type");
10860 auto VScale = Context.getTargetInfo().getVScaleRange(
10861 Context.getLangOpts(), TargetInfo::ArmStreamingKind::NotStreaming);
10862 if (!VScale)
10863 return 0;
10864
10865 ASTContext::BuiltinVectorTypeInfo Info = Context.getBuiltinVectorTypeInfo(Ty);
10866
10867 uint64_t EltSize = Context.getTypeSize(Info.ElementType);
10868 if (Info.ElementType == Context.BoolTy)
10869 EltSize = 1;
10870
10871 uint64_t MinElts = Info.EC.getKnownMinValue();
10872 return VScale->first * MinElts * EltSize;
10873}
10874
10876 QualType SecondType) {
10877 assert(
10878 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10879 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10880 "Expected RVV builtin type and vector type!");
10881
10882 auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
10883 if (const auto *BT = FirstType->getAs<BuiltinType>()) {
10884 if (const auto *VT = SecondType->getAs<VectorType>()) {
10885 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10887 return FirstType->isRVVVLSBuiltinType() &&
10888 Info.ElementType == BoolTy &&
10889 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)));
10890 }
10891 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_1) {
10893 return FirstType->isRVVVLSBuiltinType() &&
10894 Info.ElementType == BoolTy &&
10895 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT) * 8));
10896 }
10897 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_2) {
10899 return FirstType->isRVVVLSBuiltinType() &&
10900 Info.ElementType == BoolTy &&
10901 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 4);
10902 }
10903 if (VT->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {
10905 return FirstType->isRVVVLSBuiltinType() &&
10906 Info.ElementType == BoolTy &&
10907 getTypeSize(SecondType) == ((getRVVTypeSize(*this, BT)) * 2);
10908 }
10909 if (VT->getVectorKind() == VectorKind::RVVFixedLengthData ||
10910 VT->getVectorKind() == VectorKind::Generic)
10911 return FirstType->isRVVVLSBuiltinType() &&
10912 getTypeSize(SecondType) == getRVVTypeSize(*this, BT) &&
10913 hasSameType(VT->getElementType(),
10914 getBuiltinVectorTypeInfo(BT).ElementType);
10915 }
10916 }
10917 return false;
10918 };
10919
10920 return IsValidCast(FirstType, SecondType) ||
10921 IsValidCast(SecondType, FirstType);
10922}
10923
10925 QualType SecondType) {
10926 assert(
10927 ((FirstType->isRVVSizelessBuiltinType() && SecondType->isVectorType()) ||
10928 (FirstType->isVectorType() && SecondType->isRVVSizelessBuiltinType())) &&
10929 "Expected RVV builtin type and vector type!");
10930
10931 auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
10932 const auto *BT = FirstType->getAs<BuiltinType>();
10933 if (!BT)
10934 return false;
10935
10936 if (!BT->isRVVVLSBuiltinType())
10937 return false;
10938
10939 const auto *VecTy = SecondType->getAs<VectorType>();
10940 if (VecTy && VecTy->getVectorKind() == VectorKind::Generic) {
10942 getLangOpts().getLaxVectorConversions();
10943
10944 // If __riscv_v_fixed_vlen != N do not allow vector lax conversion.
10945 if (getTypeSize(SecondType) != getRVVTypeSize(*this, BT))
10946 return false;
10947
10948 // If -flax-vector-conversions=all is specified, the types are
10949 // certainly compatible.
10951 return true;
10952
10953 // If -flax-vector-conversions=integer is specified, the types are
10954 // compatible if the elements are integer types.
10956 return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
10957 FirstType->getRVVEltType(*this)->isIntegerType();
10958 }
10959
10960 return false;
10961 };
10962
10963 return IsLaxCompatible(FirstType, SecondType) ||
10964 IsLaxCompatible(SecondType, FirstType);
10965}
10966
10968 while (true) {
10969 // __strong id
10970 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
10971 if (Attr->getAttrKind() == attr::ObjCOwnership)
10972 return true;
10973
10974 Ty = Attr->getModifiedType();
10975
10976 // X *__strong (...)
10977 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
10978 Ty = Paren->getInnerType();
10979
10980 // We do not want to look through typedefs, typeof(expr),
10981 // typeof(type), or any other way that the type is somehow
10982 // abstracted.
10983 } else {
10984 return false;
10985 }
10986 }
10987}
10988
10989//===----------------------------------------------------------------------===//
10990// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
10991//===----------------------------------------------------------------------===//
10992
10993/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
10994/// inheritance hierarchy of 'rProto'.
10995bool
10997 ObjCProtocolDecl *rProto) const {
10998 if (declaresSameEntity(lProto, rProto))
10999 return true;
11000 for (auto *PI : rProto->protocols())
11001 if (ProtocolCompatibleWithProtocol(lProto, PI))
11002 return true;
11003 return false;
11004}
11005
11006/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
11007/// Class<pr1, ...>.
11009 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
11010 for (auto *lhsProto : lhs->quals()) {
11011 bool match = false;
11012 for (auto *rhsProto : rhs->quals()) {
11013 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
11014 match = true;
11015 break;
11016 }
11017 }
11018 if (!match)
11019 return false;
11020 }
11021 return true;
11022}
11023
11024/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
11025/// ObjCQualifiedIDType.
11027 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
11028 bool compare) {
11029 // Allow id<P..> and an 'id' in all cases.
11030 if (lhs->isObjCIdType() || rhs->isObjCIdType())
11031 return true;
11032
11033 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
11034 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
11036 return false;
11037
11038 if (lhs->isObjCQualifiedIdType()) {
11039 if (rhs->qual_empty()) {
11040 // If the RHS is a unqualified interface pointer "NSString*",
11041 // make sure we check the class hierarchy.
11042 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11043 for (auto *I : lhs->quals()) {
11044 // when comparing an id<P> on lhs with a static type on rhs,
11045 // see if static class implements all of id's protocols, directly or
11046 // through its super class and categories.
11047 if (!rhsID->ClassImplementsProtocol(I, true))
11048 return false;
11049 }
11050 }
11051 // If there are no qualifiers and no interface, we have an 'id'.
11052 return true;
11053 }
11054 // Both the right and left sides have qualifiers.
11055 for (auto *lhsProto : lhs->quals()) {
11056 bool match = false;
11057
11058 // when comparing an id<P> on lhs with a static type on rhs,
11059 // see if static class implements all of id's protocols, directly or
11060 // through its super class and categories.
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 the RHS is a qualified interface pointer "NSString<P>*",
11069 // make sure we check the class hierarchy.
11070 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
11071 for (auto *I : lhs->quals()) {
11072 // when comparing an id<P> on lhs with a static type on rhs,
11073 // see if static class implements all of id's protocols, directly or
11074 // through its super class and categories.
11075 if (rhsID->ClassImplementsProtocol(I, true)) {
11076 match = true;
11077 break;
11078 }
11079 }
11080 }
11081 if (!match)
11082 return false;
11083 }
11084
11085 return true;
11086 }
11087
11088 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
11089
11090 if (lhs->getInterfaceType()) {
11091 // If both the right and left sides have qualifiers.
11092 for (auto *lhsProto : lhs->quals()) {
11093 bool match = false;
11094
11095 // when comparing an id<P> on rhs with a static type on lhs,
11096 // see if static class implements all of id's protocols, directly or
11097 // through its super class and categories.
11098 // First, lhs protocols in the qualifier list must be found, direct
11099 // or indirect in rhs's qualifier list or it is a mismatch.
11100 for (auto *rhsProto : rhs->quals()) {
11101 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11102 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11103 match = true;
11104 break;
11105 }
11106 }
11107 if (!match)
11108 return false;
11109 }
11110
11111 // Static class's protocols, or its super class or category protocols
11112 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
11113 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
11114 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
11115 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
11116 // This is rather dubious but matches gcc's behavior. If lhs has
11117 // no type qualifier and its class has no static protocol(s)
11118 // assume that it is mismatch.
11119 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
11120 return false;
11121 for (auto *lhsProto : LHSInheritedProtocols) {
11122 bool match = false;
11123 for (auto *rhsProto : rhs->quals()) {
11124 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
11125 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
11126 match = true;
11127 break;
11128 }
11129 }
11130 if (!match)
11131 return false;
11132 }
11133 }
11134 return true;
11135 }
11136 return false;
11137}
11138
11139/// canAssignObjCInterfaces - Return true if the two interface types are
11140/// compatible for assignment from RHS to LHS. This handles validation of any
11141/// protocol qualifiers on the LHS or RHS.
11143 const ObjCObjectPointerType *RHSOPT) {
11144 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11145 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11146
11147 // If either type represents the built-in 'id' type, return true.
11148 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
11149 return true;
11150
11151 // Function object that propagates a successful result or handles
11152 // __kindof types.
11153 auto finish = [&](bool succeeded) -> bool {
11154 if (succeeded)
11155 return true;
11156
11157 if (!RHS->isKindOfType())
11158 return false;
11159
11160 // Strip off __kindof and protocol qualifiers, then check whether
11161 // we can assign the other way.
11163 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
11164 };
11165
11166 // Casts from or to id<P> are allowed when the other side has compatible
11167 // protocols.
11168 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
11169 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
11170 }
11171
11172 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
11173 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
11174 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
11175 }
11176
11177 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
11178 if (LHS->isObjCClass() && RHS->isObjCClass()) {
11179 return true;
11180 }
11181
11182 // If we have 2 user-defined types, fall into that path.
11183 if (LHS->getInterface() && RHS->getInterface()) {
11184 return finish(canAssignObjCInterfaces(LHS, RHS));
11185 }
11186
11187 return false;
11188}
11189
11190/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
11191/// for providing type-safety for objective-c pointers used to pass/return
11192/// arguments in block literals. When passed as arguments, passing 'A*' where
11193/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
11194/// not OK. For the return type, the opposite is not OK.
11196 const ObjCObjectPointerType *LHSOPT,
11197 const ObjCObjectPointerType *RHSOPT,
11198 bool BlockReturnType) {
11199
11200 // Function object that propagates a successful result or handles
11201 // __kindof types.
11202 auto finish = [&](bool succeeded) -> bool {
11203 if (succeeded)
11204 return true;
11205
11206 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
11207 if (!Expected->isKindOfType())
11208 return false;
11209
11210 // Strip off __kindof and protocol qualifiers, then check whether
11211 // we can assign the other way.
11213 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
11214 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
11215 BlockReturnType);
11216 };
11217
11218 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
11219 return true;
11220
11221 if (LHSOPT->isObjCBuiltinType()) {
11222 return finish(RHSOPT->isObjCBuiltinType() ||
11223 RHSOPT->isObjCQualifiedIdType());
11224 }
11225
11226 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
11227 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
11228 // Use for block parameters previous type checking for compatibility.
11229 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
11230 // Or corrected type checking as in non-compat mode.
11231 (!BlockReturnType &&
11232 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
11233 else
11235 (BlockReturnType ? LHSOPT : RHSOPT),
11236 (BlockReturnType ? RHSOPT : LHSOPT), false));
11237 }
11238
11239 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
11240 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
11241 if (LHS && RHS) { // We have 2 user-defined types.
11242 if (LHS != RHS) {
11243 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
11244 return finish(BlockReturnType);
11245 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
11246 return finish(!BlockReturnType);
11247 }
11248 else
11249 return true;
11250 }
11251 return false;
11252}
11253
11254/// Comparison routine for Objective-C protocols to be used with
11255/// llvm::array_pod_sort.
11257 ObjCProtocolDecl * const *rhs) {
11258 return (*lhs)->getName().compare((*rhs)->getName());
11259}
11260
11261/// getIntersectionOfProtocols - This routine finds the intersection of set
11262/// of protocols inherited from two distinct objective-c pointer objects with
11263/// the given common base.
11264/// It is used to build composite qualifier list of the composite type of
11265/// the conditional expression involving two objective-c pointer objects.
11266static
11268 const ObjCInterfaceDecl *CommonBase,
11269 const ObjCObjectPointerType *LHSOPT,
11270 const ObjCObjectPointerType *RHSOPT,
11271 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
11272
11273 const ObjCObjectType* LHS = LHSOPT->getObjectType();
11274 const ObjCObjectType* RHS = RHSOPT->getObjectType();
11275 assert(LHS->getInterface() && "LHS must have an interface base");
11276 assert(RHS->getInterface() && "RHS must have an interface base");
11277
11278 // Add all of the protocols for the LHS.
11280
11281 // Start with the protocol qualifiers.
11282 for (auto *proto : LHS->quals()) {
11283 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
11284 }
11285
11286 // Also add the protocols associated with the LHS interface.
11287 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
11288
11289 // Add all of the protocols for the RHS.
11291
11292 // Start with the protocol qualifiers.
11293 for (auto *proto : RHS->quals()) {
11294 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
11295 }
11296
11297 // Also add the protocols associated with the RHS interface.
11298 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
11299
11300 // Compute the intersection of the collected protocol sets.
11301 for (auto *proto : LHSProtocolSet) {
11302 if (RHSProtocolSet.count(proto))
11303 IntersectionSet.push_back(proto);
11304 }
11305
11306 // Compute the set of protocols that is implied by either the common type or
11307 // the protocols within the intersection.
11309 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
11310
11311 // Remove any implied protocols from the list of inherited protocols.
11312 if (!ImpliedProtocols.empty()) {
11313 llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
11314 return ImpliedProtocols.contains(proto);
11315 });
11316 }
11317
11318 // Sort the remaining protocols by name.
11319 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
11321}
11322
11323/// Determine whether the first type is a subtype of the second.
11325 QualType rhs) {
11326 // Common case: two object pointers.
11327 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
11328 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
11329 if (lhsOPT && rhsOPT)
11330 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
11331
11332 // Two block pointers.
11333 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
11334 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
11335 if (lhsBlock && rhsBlock)
11336 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
11337
11338 // If either is an unqualified 'id' and the other is a block, it's
11339 // acceptable.
11340 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
11341 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
11342 return true;
11343
11344 return false;
11345}
11346
11347// Check that the given Objective-C type argument lists are equivalent.
11349 const ObjCInterfaceDecl *iface,
11350 ArrayRef<QualType> lhsArgs,
11351 ArrayRef<QualType> rhsArgs,
11352 bool stripKindOf) {
11353 if (lhsArgs.size() != rhsArgs.size())
11354 return false;
11355
11356 ObjCTypeParamList *typeParams = iface->getTypeParamList();
11357 if (!typeParams)
11358 return false;
11359
11360 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
11361 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
11362 continue;
11363
11364 switch (typeParams->begin()[i]->getVariance()) {
11366 if (!stripKindOf ||
11367 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
11368 rhsArgs[i].stripObjCKindOfType(ctx))) {
11369 return false;
11370 }
11371 break;
11372
11374 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
11375 return false;
11376 break;
11377
11379 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
11380 return false;
11381 break;
11382 }
11383 }
11384
11385 return true;
11386}
11387
11389 const ObjCObjectPointerType *Lptr,
11390 const ObjCObjectPointerType *Rptr) {
11391 const ObjCObjectType *LHS = Lptr->getObjectType();
11392 const ObjCObjectType *RHS = Rptr->getObjectType();
11393 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
11394 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
11395
11396 if (!LDecl || !RDecl)
11397 return {};
11398
11399 // When either LHS or RHS is a kindof type, we should return a kindof type.
11400 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
11401 // kindof(A).
11402 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
11403
11404 // Follow the left-hand side up the class hierarchy until we either hit a
11405 // root or find the RHS. Record the ancestors in case we don't find it.
11406 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
11407 LHSAncestors;
11408 while (true) {
11409 // Record this ancestor. We'll need this if the common type isn't in the
11410 // path from the LHS to the root.
11411 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
11412
11413 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
11414 // Get the type arguments.
11415 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
11416 bool anyChanges = false;
11417 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11418 // Both have type arguments, compare them.
11419 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11420 LHS->getTypeArgs(), RHS->getTypeArgs(),
11421 /*stripKindOf=*/true))
11422 return {};
11423 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11424 // If only one has type arguments, the result will not have type
11425 // arguments.
11426 LHSTypeArgs = {};
11427 anyChanges = true;
11428 }
11429
11430 // Compute the intersection of protocols.
11432 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
11433 Protocols);
11434 if (!Protocols.empty())
11435 anyChanges = true;
11436
11437 // If anything in the LHS will have changed, build a new result type.
11438 // If we need to return a kindof type but LHS is not a kindof type, we
11439 // build a new result type.
11440 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
11441 QualType Result = getObjCInterfaceType(LHS->getInterface());
11442 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
11443 anyKindOf || LHS->isKindOfType());
11445 }
11446
11447 return getObjCObjectPointerType(QualType(LHS, 0));
11448 }
11449
11450 // Find the superclass.
11451 QualType LHSSuperType = LHS->getSuperClassType();
11452 if (LHSSuperType.isNull())
11453 break;
11454
11455 LHS = LHSSuperType->castAs<ObjCObjectType>();
11456 }
11457
11458 // We didn't find anything by following the LHS to its root; now check
11459 // the RHS against the cached set of ancestors.
11460 while (true) {
11461 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
11462 if (KnownLHS != LHSAncestors.end()) {
11463 LHS = KnownLHS->second;
11464
11465 // Get the type arguments.
11466 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
11467 bool anyChanges = false;
11468 if (LHS->isSpecialized() && RHS->isSpecialized()) {
11469 // Both have type arguments, compare them.
11470 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
11471 LHS->getTypeArgs(), RHS->getTypeArgs(),
11472 /*stripKindOf=*/true))
11473 return {};
11474 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
11475 // If only one has type arguments, the result will not have type
11476 // arguments.
11477 RHSTypeArgs = {};
11478 anyChanges = true;
11479 }
11480
11481 // Compute the intersection of protocols.
11483 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
11484 Protocols);
11485 if (!Protocols.empty())
11486 anyChanges = true;
11487
11488 // If we need to return a kindof type but RHS is not a kindof type, we
11489 // build a new result type.
11490 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
11491 QualType Result = getObjCInterfaceType(RHS->getInterface());
11492 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
11493 anyKindOf || RHS->isKindOfType());
11495 }
11496
11497 return getObjCObjectPointerType(QualType(RHS, 0));
11498 }
11499
11500 // Find the superclass of the RHS.
11501 QualType RHSSuperType = RHS->getSuperClassType();
11502 if (RHSSuperType.isNull())
11503 break;
11504
11505 RHS = RHSSuperType->castAs<ObjCObjectType>();
11506 }
11507
11508 return {};
11509}
11510
11512 const ObjCObjectType *RHS) {
11513 assert(LHS->getInterface() && "LHS is not an interface type");
11514 assert(RHS->getInterface() && "RHS is not an interface type");
11515
11516 // Verify that the base decls are compatible: the RHS must be a subclass of
11517 // the LHS.
11518 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
11519 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
11520 if (!IsSuperClass)
11521 return false;
11522
11523 // If the LHS has protocol qualifiers, determine whether all of them are
11524 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
11525 // LHS).
11526 if (LHS->getNumProtocols() > 0) {
11527 // OK if conversion of LHS to SuperClass results in narrowing of types
11528 // ; i.e., SuperClass may implement at least one of the protocols
11529 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
11530 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
11531 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
11532 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
11533 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
11534 // qualifiers.
11535 for (auto *RHSPI : RHS->quals())
11536 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
11537 // If there is no protocols associated with RHS, it is not a match.
11538 if (SuperClassInheritedProtocols.empty())
11539 return false;
11540
11541 for (const auto *LHSProto : LHS->quals()) {
11542 bool SuperImplementsProtocol = false;
11543 for (auto *SuperClassProto : SuperClassInheritedProtocols)
11544 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
11545 SuperImplementsProtocol = true;
11546 break;
11547 }
11548 if (!SuperImplementsProtocol)
11549 return false;
11550 }
11551 }
11552
11553 // If the LHS is specialized, we may need to check type arguments.
11554 if (LHS->isSpecialized()) {
11555 // Follow the superclass chain until we've matched the LHS class in the
11556 // hierarchy. This substitutes type arguments through.
11557 const ObjCObjectType *RHSSuper = RHS;
11558 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
11559 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
11560
11561 // If the RHS is specializd, compare type arguments.
11562 if (RHSSuper->isSpecialized() &&
11563 !sameObjCTypeArgs(*this, LHS->getInterface(),
11564 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
11565 /*stripKindOf=*/true)) {
11566 return false;
11567 }
11568 }
11569
11570 return true;
11571}
11572
11574 // get the "pointed to" types
11575 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
11576 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
11577
11578 if (!LHSOPT || !RHSOPT)
11579 return false;
11580
11581 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
11582 canAssignObjCInterfaces(RHSOPT, LHSOPT);
11583}
11584
11587 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
11588 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
11589}
11590
11591/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
11592/// both shall have the identically qualified version of a compatible type.
11593/// C99 6.2.7p1: Two types have compatible types if their types are the
11594/// same. See 6.7.[2,3,5] for additional rules.
11596 bool CompareUnqualified) {
11597 if (getLangOpts().CPlusPlus)
11598 return hasSameType(LHS, RHS);
11599
11600 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
11601}
11602
11604 return typesAreCompatible(LHS, RHS);
11605}
11606
11608 return !mergeTypes(LHS, RHS, true).isNull();
11609}
11610
11611/// mergeTransparentUnionType - if T is a transparent union type and a member
11612/// of T is compatible with SubType, return the merged type, else return
11613/// QualType()
11615 bool OfBlockPointer,
11616 bool Unqualified) {
11617 if (const RecordType *UT = T->getAsUnionType()) {
11618 RecordDecl *UD = UT->getDecl()->getMostRecentDecl();
11619 if (UD->hasAttr<TransparentUnionAttr>()) {
11620 for (const auto *I : UD->fields()) {
11621 QualType ET = I->getType().getUnqualifiedType();
11622 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
11623 if (!MT.isNull())
11624 return MT;
11625 }
11626 }
11627 }
11628
11629 return {};
11630}
11631
11632/// mergeFunctionParameterTypes - merge two types which appear as function
11633/// parameter types
11635 bool OfBlockPointer,
11636 bool Unqualified) {
11637 // GNU extension: two types are compatible if they appear as a function
11638 // argument, one of the types is a transparent union type and the other
11639 // type is compatible with a union member
11640 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
11641 Unqualified);
11642 if (!lmerge.isNull())
11643 return lmerge;
11644
11645 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
11646 Unqualified);
11647 if (!rmerge.isNull())
11648 return rmerge;
11649
11650 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
11651}
11652
11654 bool OfBlockPointer, bool Unqualified,
11655 bool AllowCXX,
11656 bool IsConditionalOperator) {
11657 const auto *lbase = lhs->castAs<FunctionType>();
11658 const auto *rbase = rhs->castAs<FunctionType>();
11659 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
11660 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
11661 bool allLTypes = true;
11662 bool allRTypes = true;
11663
11664 // Check return type
11665 QualType retType;
11666 if (OfBlockPointer) {
11667 QualType RHS = rbase->getReturnType();
11668 QualType LHS = lbase->getReturnType();
11669 bool UnqualifiedResult = Unqualified;
11670 if (!UnqualifiedResult)
11671 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
11672 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
11673 }
11674 else
11675 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
11676 Unqualified);
11677 if (retType.isNull())
11678 return {};
11679
11680 if (Unqualified)
11681 retType = retType.getUnqualifiedType();
11682
11683 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
11684 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
11685 if (Unqualified) {
11686 LRetType = LRetType.getUnqualifiedType();
11687 RRetType = RRetType.getUnqualifiedType();
11688 }
11689
11690 if (getCanonicalType(retType) != LRetType)
11691 allLTypes = false;
11692 if (getCanonicalType(retType) != RRetType)
11693 allRTypes = false;
11694
11695 // FIXME: double check this
11696 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
11697 // rbase->getRegParmAttr() != 0 &&
11698 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
11699 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
11700 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
11701
11702 // Compatible functions must have compatible calling conventions
11703 if (lbaseInfo.getCC() != rbaseInfo.getCC())
11704 return {};
11705
11706 // Regparm is part of the calling convention.
11707 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
11708 return {};
11709 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
11710 return {};
11711
11712 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
11713 return {};
11714 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
11715 return {};
11716 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
11717 return {};
11718
11719 // When merging declarations, it's common for supplemental information like
11720 // attributes to only be present in one of the declarations, and we generally
11721 // want type merging to preserve the union of information. So a merged
11722 // function type should be noreturn if it was noreturn in *either* operand
11723 // type.
11724 //
11725 // But for the conditional operator, this is backwards. The result of the
11726 // operator could be either operand, and its type should conservatively
11727 // reflect that. So a function type in a composite type is noreturn only
11728 // if it's noreturn in *both* operand types.
11729 //
11730 // Arguably, noreturn is a kind of subtype, and the conditional operator
11731 // ought to produce the most specific common supertype of its operand types.
11732 // That would differ from this rule in contravariant positions. However,
11733 // neither C nor C++ generally uses this kind of subtype reasoning. Also,
11734 // as a practical matter, it would only affect C code that does abstraction of
11735 // higher-order functions (taking noreturn callbacks!), which is uncommon to
11736 // say the least. So we use the simpler rule.
11737 bool NoReturn = IsConditionalOperator
11738 ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
11739 : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
11740 if (lbaseInfo.getNoReturn() != NoReturn)
11741 allLTypes = false;
11742 if (rbaseInfo.getNoReturn() != NoReturn)
11743 allRTypes = false;
11744
11745 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
11746
11747 std::optional<FunctionEffectSet> MergedFX;
11748
11749 if (lproto && rproto) { // two C99 style function prototypes
11750 assert((AllowCXX ||
11751 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
11752 "C++ shouldn't be here");
11753 // Compatible functions must have the same number of parameters
11754 if (lproto->getNumParams() != rproto->getNumParams())
11755 return {};
11756
11757 // Variadic and non-variadic functions aren't compatible
11758 if (lproto->isVariadic() != rproto->isVariadic())
11759 return {};
11760
11761 if (lproto->getMethodQuals() != rproto->getMethodQuals())
11762 return {};
11763
11764 // Function protos with different 'cfi_salt' values aren't compatible.
11765 if (lproto->getExtraAttributeInfo().CFISalt !=
11766 rproto->getExtraAttributeInfo().CFISalt)
11767 return {};
11768
11769 // Function effects are handled similarly to noreturn, see above.
11770 FunctionEffectsRef LHSFX = lproto->getFunctionEffects();
11771 FunctionEffectsRef RHSFX = rproto->getFunctionEffects();
11772 if (LHSFX != RHSFX) {
11773 if (IsConditionalOperator)
11774 MergedFX = FunctionEffectSet::getIntersection(LHSFX, RHSFX);
11775 else {
11777 MergedFX = FunctionEffectSet::getUnion(LHSFX, RHSFX, Errs);
11778 // Here we're discarding a possible error due to conflicts in the effect
11779 // sets. But we're not in a context where we can report it. The
11780 // operation does however guarantee maintenance of invariants.
11781 }
11782 if (*MergedFX != LHSFX)
11783 allLTypes = false;
11784 if (*MergedFX != RHSFX)
11785 allRTypes = false;
11786 }
11787
11789 bool canUseLeft, canUseRight;
11790 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
11791 newParamInfos))
11792 return {};
11793
11794 if (!canUseLeft)
11795 allLTypes = false;
11796 if (!canUseRight)
11797 allRTypes = false;
11798
11799 // Check parameter type compatibility
11801 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
11802 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
11803 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
11805 lParamType, rParamType, OfBlockPointer, Unqualified);
11806 if (paramType.isNull())
11807 return {};
11808
11809 if (Unqualified)
11810 paramType = paramType.getUnqualifiedType();
11811
11812 types.push_back(paramType);
11813 if (Unqualified) {
11814 lParamType = lParamType.getUnqualifiedType();
11815 rParamType = rParamType.getUnqualifiedType();
11816 }
11817
11818 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
11819 allLTypes = false;
11820 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
11821 allRTypes = false;
11822 }
11823
11824 if (allLTypes) return lhs;
11825 if (allRTypes) return rhs;
11826
11827 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
11828 EPI.ExtInfo = einfo;
11829 EPI.ExtParameterInfos =
11830 newParamInfos.empty() ? nullptr : newParamInfos.data();
11831 if (MergedFX)
11832 EPI.FunctionEffects = *MergedFX;
11833 return getFunctionType(retType, types, EPI);
11834 }
11835
11836 if (lproto) allRTypes = false;
11837 if (rproto) allLTypes = false;
11838
11839 const FunctionProtoType *proto = lproto ? lproto : rproto;
11840 if (proto) {
11841 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
11842 if (proto->isVariadic())
11843 return {};
11844 // Check that the types are compatible with the types that
11845 // would result from default argument promotions (C99 6.7.5.3p15).
11846 // The only types actually affected are promotable integer
11847 // types and floats, which would be passed as a different
11848 // type depending on whether the prototype is visible.
11849 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
11850 QualType paramTy = proto->getParamType(i);
11851
11852 // Look at the converted type of enum types, since that is the type used
11853 // to pass enum values.
11854 if (const auto *ED = paramTy->getAsEnumDecl()) {
11855 paramTy = ED->getIntegerType();
11856 if (paramTy.isNull())
11857 return {};
11858 }
11859
11860 if (isPromotableIntegerType(paramTy) ||
11861 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
11862 return {};
11863 }
11864
11865 if (allLTypes) return lhs;
11866 if (allRTypes) return rhs;
11867
11869 EPI.ExtInfo = einfo;
11870 if (MergedFX)
11871 EPI.FunctionEffects = *MergedFX;
11872 return getFunctionType(retType, proto->getParamTypes(), EPI);
11873 }
11874
11875 if (allLTypes) return lhs;
11876 if (allRTypes) return rhs;
11877 return getFunctionNoProtoType(retType, einfo);
11878}
11879
11880/// Given that we have an enum type and a non-enum type, try to merge them.
11881static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
11882 QualType other, bool isBlockReturnType) {
11883 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
11884 // a signed integer type, or an unsigned integer type.
11885 // Compatibility is based on the underlying type, not the promotion
11886 // type.
11887 QualType underlyingType =
11888 ET->getDecl()->getDefinitionOrSelf()->getIntegerType();
11889 if (underlyingType.isNull())
11890 return {};
11891 if (Context.hasSameType(underlyingType, other))
11892 return other;
11893
11894 // In block return types, we're more permissive and accept any
11895 // integral type of the same size.
11896 if (isBlockReturnType && other->isIntegerType() &&
11897 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
11898 return other;
11899
11900 return {};
11901}
11902
11904 // C17 and earlier and C++ disallow two tag definitions within the same TU
11905 // from being compatible.
11906 if (LangOpts.CPlusPlus || !LangOpts.C23)
11907 return {};
11908
11909 // Nameless tags are comparable only within outer definitions. At the top
11910 // level they are not comparable.
11911 const TagDecl *LTagD = LHS->castAsTagDecl(), *RTagD = RHS->castAsTagDecl();
11912 if (!LTagD->getIdentifier() || !RTagD->getIdentifier())
11913 return {};
11914
11915 // C23, on the other hand, requires the members to be "the same enough", so
11916 // we use a structural equivalence check.
11919 getLangOpts(), *this, *this, NonEquivalentDecls,
11920 StructuralEquivalenceKind::Default, /*StrictTypeSpelling=*/false,
11921 /*Complain=*/false, /*ErrorOnTagTypeMismatch=*/true);
11922 return Ctx.IsEquivalent(LHS, RHS) ? LHS : QualType{};
11923}
11924
11926 QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified,
11927 bool BlockReturnType, bool IsConditionalOperator) {
11928 const auto *LHSOBT = LHS->getAs<OverflowBehaviorType>();
11929 const auto *RHSOBT = RHS->getAs<OverflowBehaviorType>();
11930
11931 if (!LHSOBT && !RHSOBT)
11932 return std::nullopt;
11933
11934 if (LHSOBT) {
11935 if (RHSOBT) {
11936 if (LHSOBT->getBehaviorKind() != RHSOBT->getBehaviorKind())
11937 return QualType();
11938
11939 QualType MergedUnderlying = mergeTypes(
11940 LHSOBT->getUnderlyingType(), RHSOBT->getUnderlyingType(),
11941 OfBlockPointer, Unqualified, BlockReturnType, IsConditionalOperator);
11942
11943 if (MergedUnderlying.isNull())
11944 return QualType();
11945
11946 if (getCanonicalType(LHSOBT) == getCanonicalType(RHSOBT)) {
11947 if (LHSOBT->getUnderlyingType() == RHSOBT->getUnderlyingType())
11948 return getCommonSugaredType(LHS, RHS);
11950 LHSOBT->getBehaviorKind(),
11951 getCanonicalType(LHSOBT->getUnderlyingType()));
11952 }
11953
11954 // For different underlying types that successfully merge, wrap the
11955 // merged underlying type with the common overflow behavior
11956 return getOverflowBehaviorType(LHSOBT->getBehaviorKind(),
11957 MergedUnderlying);
11958 }
11959 return mergeTypes(LHSOBT->getUnderlyingType(), RHS, OfBlockPointer,
11960 Unqualified, BlockReturnType, IsConditionalOperator);
11961 }
11962
11963 return mergeTypes(LHS, RHSOBT->getUnderlyingType(), OfBlockPointer,
11964 Unqualified, BlockReturnType, IsConditionalOperator);
11965}
11966
11967QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
11968 bool Unqualified, bool BlockReturnType,
11969 bool IsConditionalOperator) {
11970 // For C++ we will not reach this code with reference types (see below),
11971 // for OpenMP variant call overloading we might.
11972 //
11973 // C++ [expr]: If an expression initially has the type "reference to T", the
11974 // type is adjusted to "T" prior to any further analysis, the expression
11975 // designates the object or function denoted by the reference, and the
11976 // expression is an lvalue unless the reference is an rvalue reference and
11977 // the expression is a function call (possibly inside parentheses).
11978 auto *LHSRefTy = LHS->getAs<ReferenceType>();
11979 auto *RHSRefTy = RHS->getAs<ReferenceType>();
11980 if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
11981 LHS->getTypeClass() == RHS->getTypeClass())
11982 return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
11983 OfBlockPointer, Unqualified, BlockReturnType);
11984 if (LHSRefTy || RHSRefTy)
11985 return {};
11986
11987 if (std::optional<QualType> MergedOBT =
11988 tryMergeOverflowBehaviorTypes(LHS, RHS, OfBlockPointer, Unqualified,
11989 BlockReturnType, IsConditionalOperator))
11990 return *MergedOBT;
11991
11992 if (Unqualified) {
11993 LHS = LHS.getUnqualifiedType();
11994 RHS = RHS.getUnqualifiedType();
11995 }
11996
11997 QualType LHSCan = getCanonicalType(LHS),
11998 RHSCan = getCanonicalType(RHS);
11999
12000 // If two types are identical, they are compatible.
12001 if (LHSCan == RHSCan)
12002 return LHS;
12003
12004 // If the qualifiers are different, the types aren't compatible... mostly.
12005 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12006 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12007 if (LQuals != RQuals) {
12008 // If any of these qualifiers are different, we have a type
12009 // mismatch.
12010 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
12011 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
12012 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
12013 !LQuals.getPointerAuth().isEquivalent(RQuals.getPointerAuth()) ||
12014 LQuals.hasUnaligned() != RQuals.hasUnaligned())
12015 return {};
12016
12017 // Exactly one GC qualifier difference is allowed: __strong is
12018 // okay if the other type has no GC qualifier but is an Objective
12019 // C object pointer (i.e. implicitly strong by default). We fix
12020 // this by pretending that the unqualified type was actually
12021 // qualified __strong.
12022 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12023 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12024 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12025
12026 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12027 return {};
12028
12029 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
12031 }
12032 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
12034 }
12035 return {};
12036 }
12037
12038 // Okay, qualifiers are equal.
12039
12040 Type::TypeClass LHSClass = LHSCan->getTypeClass();
12041 Type::TypeClass RHSClass = RHSCan->getTypeClass();
12042
12043 // We want to consider the two function types to be the same for these
12044 // comparisons, just force one to the other.
12045 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
12046 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
12047
12048 // Same as above for arrays
12049 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
12050 LHSClass = Type::ConstantArray;
12051 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
12052 RHSClass = Type::ConstantArray;
12053
12054 // ObjCInterfaces are just specialized ObjCObjects.
12055 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
12056 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
12057
12058 // Canonicalize ExtVector -> Vector.
12059 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
12060 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
12061
12062 // If the canonical type classes don't match.
12063 if (LHSClass != RHSClass) {
12064 // Note that we only have special rules for turning block enum
12065 // returns into block int returns, not vice-versa.
12066 if (const auto *ETy = LHS->getAsCanonical<EnumType>()) {
12067 return mergeEnumWithInteger(*this, ETy, RHS, false);
12068 }
12069 if (const EnumType *ETy = RHS->getAsCanonical<EnumType>()) {
12070 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
12071 }
12072 // allow block pointer type to match an 'id' type.
12073 if (OfBlockPointer && !BlockReturnType) {
12074 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
12075 return LHS;
12076 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
12077 return RHS;
12078 }
12079 // Allow __auto_type to match anything; it merges to the type with more
12080 // information.
12081 if (const auto *AT = LHS->getAs<AutoType>()) {
12082 if (!AT->isDeduced() && AT->isGNUAutoType())
12083 return RHS;
12084 }
12085 if (const auto *AT = RHS->getAs<AutoType>()) {
12086 if (!AT->isDeduced() && AT->isGNUAutoType())
12087 return LHS;
12088 }
12089 return {};
12090 }
12091
12092 // The canonical type classes match.
12093 switch (LHSClass) {
12094#define TYPE(Class, Base)
12095#define ABSTRACT_TYPE(Class, Base)
12096#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
12097#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
12098#define DEPENDENT_TYPE(Class, Base) case Type::Class:
12099#include "clang/AST/TypeNodes.inc"
12100 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
12101
12102 case Type::Auto:
12103 case Type::DeducedTemplateSpecialization:
12104 case Type::LValueReference:
12105 case Type::RValueReference:
12106 case Type::MemberPointer:
12107 llvm_unreachable("C++ should never be in mergeTypes");
12108
12109 case Type::ObjCInterface:
12110 case Type::IncompleteArray:
12111 case Type::VariableArray:
12112 case Type::FunctionProto:
12113 case Type::ExtVector:
12114 case Type::OverflowBehavior:
12115 llvm_unreachable("Types are eliminated above");
12116
12117 case Type::Pointer:
12118 {
12119 // Merge two pointer types, while trying to preserve typedef info
12120 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
12121 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
12122 if (Unqualified) {
12123 LHSPointee = LHSPointee.getUnqualifiedType();
12124 RHSPointee = RHSPointee.getUnqualifiedType();
12125 }
12126 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
12127 Unqualified);
12128 if (ResultType.isNull())
12129 return {};
12130 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12131 return LHS;
12132 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12133 return RHS;
12134 return getPointerType(ResultType);
12135 }
12136 case Type::BlockPointer:
12137 {
12138 // Merge two block pointer types, while trying to preserve typedef info
12139 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
12140 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
12141 if (Unqualified) {
12142 LHSPointee = LHSPointee.getUnqualifiedType();
12143 RHSPointee = RHSPointee.getUnqualifiedType();
12144 }
12145 if (getLangOpts().OpenCL) {
12146 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
12147 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
12148 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
12149 // 6.12.5) thus the following check is asymmetric.
12150 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual, *this))
12151 return {};
12152 LHSPteeQual.removeAddressSpace();
12153 RHSPteeQual.removeAddressSpace();
12154 LHSPointee =
12155 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
12156 RHSPointee =
12157 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
12158 }
12159 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
12160 Unqualified);
12161 if (ResultType.isNull())
12162 return {};
12163 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
12164 return LHS;
12165 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
12166 return RHS;
12167 return getBlockPointerType(ResultType);
12168 }
12169 case Type::Atomic:
12170 {
12171 // Merge two pointer types, while trying to preserve typedef info
12172 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
12173 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
12174 if (Unqualified) {
12175 LHSValue = LHSValue.getUnqualifiedType();
12176 RHSValue = RHSValue.getUnqualifiedType();
12177 }
12178 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
12179 Unqualified);
12180 if (ResultType.isNull())
12181 return {};
12182 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
12183 return LHS;
12184 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
12185 return RHS;
12186 return getAtomicType(ResultType);
12187 }
12188 case Type::ConstantArray:
12189 {
12190 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
12191 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
12192 if (LCAT && RCAT && RCAT->getZExtSize() != LCAT->getZExtSize())
12193 return {};
12194
12195 QualType LHSElem = getAsArrayType(LHS)->getElementType();
12196 QualType RHSElem = getAsArrayType(RHS)->getElementType();
12197 if (Unqualified) {
12198 LHSElem = LHSElem.getUnqualifiedType();
12199 RHSElem = RHSElem.getUnqualifiedType();
12200 }
12201
12202 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
12203 if (ResultType.isNull())
12204 return {};
12205
12206 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
12207 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
12208
12209 // If either side is a variable array, and both are complete, check whether
12210 // the current dimension is definite.
12211 if (LVAT || RVAT) {
12212 auto SizeFetch = [this](const VariableArrayType* VAT,
12213 const ConstantArrayType* CAT)
12214 -> std::pair<bool,llvm::APInt> {
12215 if (VAT) {
12216 std::optional<llvm::APSInt> TheInt;
12217 Expr *E = VAT->getSizeExpr();
12218 if (E && (TheInt = E->getIntegerConstantExpr(*this)))
12219 return std::make_pair(true, *TheInt);
12220 return std::make_pair(false, llvm::APSInt());
12221 }
12222 if (CAT)
12223 return std::make_pair(true, CAT->getSize());
12224 return std::make_pair(false, llvm::APInt());
12225 };
12226
12227 bool HaveLSize, HaveRSize;
12228 llvm::APInt LSize, RSize;
12229 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
12230 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
12231 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
12232 return {}; // Definite, but unequal, array dimension
12233 }
12234
12235 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12236 return LHS;
12237 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12238 return RHS;
12239 if (LCAT)
12240 return getConstantArrayType(ResultType, LCAT->getSize(),
12241 LCAT->getSizeExpr(), ArraySizeModifier(), 0);
12242 if (RCAT)
12243 return getConstantArrayType(ResultType, RCAT->getSize(),
12244 RCAT->getSizeExpr(), ArraySizeModifier(), 0);
12245 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
12246 return LHS;
12247 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
12248 return RHS;
12249 if (LVAT) {
12250 // FIXME: This isn't correct! But tricky to implement because
12251 // the array's size has to be the size of LHS, but the type
12252 // has to be different.
12253 return LHS;
12254 }
12255 if (RVAT) {
12256 // FIXME: This isn't correct! But tricky to implement because
12257 // the array's size has to be the size of RHS, but the type
12258 // has to be different.
12259 return RHS;
12260 }
12261 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
12262 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
12263 return getIncompleteArrayType(ResultType, ArraySizeModifier(), 0);
12264 }
12265 case Type::FunctionNoProto:
12266 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
12267 /*AllowCXX=*/false, IsConditionalOperator);
12268 case Type::Record:
12269 case Type::Enum:
12270 return mergeTagDefinitions(LHS, RHS);
12271 case Type::Builtin:
12272 // Only exactly equal builtin types are compatible, which is tested above.
12273 return {};
12274 case Type::Complex:
12275 // Distinct complex types are incompatible.
12276 return {};
12277 case Type::Vector:
12278 // FIXME: The merged type should be an ExtVector!
12279 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
12280 RHSCan->castAs<VectorType>()))
12281 return LHS;
12282 return {};
12283 case Type::ConstantMatrix:
12285 RHSCan->castAs<ConstantMatrixType>()))
12286 return LHS;
12287 return {};
12288 case Type::ObjCObject: {
12289 // Check if the types are assignment compatible.
12290 // FIXME: This should be type compatibility, e.g. whether
12291 // "LHS x; RHS x;" at global scope is legal.
12293 RHS->castAs<ObjCObjectType>()))
12294 return LHS;
12295 return {};
12296 }
12297 case Type::ObjCObjectPointer:
12298 if (OfBlockPointer) {
12301 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
12302 return LHS;
12303 return {};
12304 }
12307 return LHS;
12308 return {};
12309 case Type::Pipe:
12310 assert(LHS != RHS &&
12311 "Equivalent pipe types should have already been handled!");
12312 return {};
12313 case Type::ArrayParameter:
12314 assert(LHS != RHS &&
12315 "Equivalent ArrayParameter types should have already been handled!");
12316 return {};
12317 case Type::BitInt: {
12318 // Merge two bit-precise int types, while trying to preserve typedef info.
12319 bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
12320 bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
12321 unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
12322 unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
12323
12324 // Like unsigned/int, shouldn't have a type if they don't match.
12325 if (LHSUnsigned != RHSUnsigned)
12326 return {};
12327
12328 if (LHSBits != RHSBits)
12329 return {};
12330 return LHS;
12331 }
12332 case Type::HLSLAttributedResource: {
12333 const HLSLAttributedResourceType *LHSTy =
12334 LHS->castAs<HLSLAttributedResourceType>();
12335 const HLSLAttributedResourceType *RHSTy =
12336 RHS->castAs<HLSLAttributedResourceType>();
12337 assert(LHSTy->getWrappedType() == RHSTy->getWrappedType() &&
12338 LHSTy->getWrappedType()->isHLSLResourceType() &&
12339 "HLSLAttributedResourceType should always wrap __hlsl_resource_t");
12340
12341 if (LHSTy->getAttrs() == RHSTy->getAttrs() &&
12342 LHSTy->getContainedType() == RHSTy->getContainedType())
12343 return LHS;
12344 return {};
12345 }
12346 case Type::HLSLInlineSpirv:
12347 const HLSLInlineSpirvType *LHSTy = LHS->castAs<HLSLInlineSpirvType>();
12348 const HLSLInlineSpirvType *RHSTy = RHS->castAs<HLSLInlineSpirvType>();
12349
12350 if (LHSTy->getOpcode() == RHSTy->getOpcode() &&
12351 LHSTy->getSize() == RHSTy->getSize() &&
12352 LHSTy->getAlignment() == RHSTy->getAlignment()) {
12353 for (size_t I = 0; I < LHSTy->getOperands().size(); I++)
12354 if (LHSTy->getOperands()[I] != RHSTy->getOperands()[I])
12355 return {};
12356
12357 return LHS;
12358 }
12359 return {};
12360 }
12361
12362 llvm_unreachable("Invalid Type::Class!");
12363}
12364
12366 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
12367 bool &CanUseFirst, bool &CanUseSecond,
12369 assert(NewParamInfos.empty() && "param info list not empty");
12370 CanUseFirst = CanUseSecond = true;
12371 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
12372 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
12373
12374 // Fast path: if the first type doesn't have ext parameter infos,
12375 // we match if and only if the second type also doesn't have them.
12376 if (!FirstHasInfo && !SecondHasInfo)
12377 return true;
12378
12379 bool NeedParamInfo = false;
12380 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
12381 : SecondFnType->getExtParameterInfos().size();
12382
12383 for (size_t I = 0; I < E; ++I) {
12384 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
12385 if (FirstHasInfo)
12386 FirstParam = FirstFnType->getExtParameterInfo(I);
12387 if (SecondHasInfo)
12388 SecondParam = SecondFnType->getExtParameterInfo(I);
12389
12390 // Cannot merge unless everything except the noescape flag matches.
12391 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
12392 return false;
12393
12394 bool FirstNoEscape = FirstParam.isNoEscape();
12395 bool SecondNoEscape = SecondParam.isNoEscape();
12396 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
12397 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
12398 if (NewParamInfos.back().getOpaqueValue())
12399 NeedParamInfo = true;
12400 if (FirstNoEscape != IsNoEscape)
12401 CanUseFirst = false;
12402 if (SecondNoEscape != IsNoEscape)
12403 CanUseSecond = false;
12404 }
12405
12406 if (!NeedParamInfo)
12407 NewParamInfos.clear();
12408
12409 return true;
12410}
12411
12413 if (auto It = ObjCLayouts.find(D); It != ObjCLayouts.end()) {
12414 It->second = nullptr;
12415 for (auto *SubClass : ObjCSubClasses.lookup(D))
12416 ResetObjCLayout(SubClass);
12417 }
12418}
12419
12420/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
12421/// 'RHS' attributes and returns the merged version; including for function
12422/// return types.
12424 QualType LHSCan = getCanonicalType(LHS),
12425 RHSCan = getCanonicalType(RHS);
12426 // If two types are identical, they are compatible.
12427 if (LHSCan == RHSCan)
12428 return LHS;
12429 if (RHSCan->isFunctionType()) {
12430 if (!LHSCan->isFunctionType())
12431 return {};
12432 QualType OldReturnType =
12433 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
12434 QualType NewReturnType =
12435 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
12436 QualType ResReturnType =
12437 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
12438 if (ResReturnType.isNull())
12439 return {};
12440 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
12441 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
12442 // In either case, use OldReturnType to build the new function type.
12443 const auto *F = LHS->castAs<FunctionType>();
12444 if (const auto *FPT = cast<FunctionProtoType>(F)) {
12445 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12446 EPI.ExtInfo = getFunctionExtInfo(LHS);
12447 QualType ResultType =
12448 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
12449 return ResultType;
12450 }
12451 }
12452 return {};
12453 }
12454
12455 // If the qualifiers are different, the types can still be merged.
12456 Qualifiers LQuals = LHSCan.getLocalQualifiers();
12457 Qualifiers RQuals = RHSCan.getLocalQualifiers();
12458
12459 if (LQuals.withoutObjCGCAttr() != RQuals.withoutObjCGCAttr()) {
12460 // Reject immediately, if anything but the GC qualifiers is different.
12461 return {};
12462 }
12463
12464 if (LQuals != RQuals) {
12465 // Exactly one GC qualifier difference is allowed: __strong is
12466 // okay if the other type has no GC qualifier but is an Objective
12467 // C object pointer (i.e. implicitly strong by default). We fix
12468 // this by pretending that the unqualified type was actually
12469 // qualified __strong.
12470 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
12471 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
12472 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
12473
12474 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
12475 return {};
12476
12477 if (GC_L == Qualifiers::Strong)
12478 return LHS;
12479 if (GC_R == Qualifiers::Strong)
12480 return RHS;
12481 return {};
12482 }
12483
12484 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
12485 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12486 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
12487 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
12488 if (ResQT == LHSBaseQT)
12489 return LHS;
12490 if (ResQT == RHSBaseQT)
12491 return RHS;
12492 }
12493 return {};
12494}
12495
12496//===----------------------------------------------------------------------===//
12497// Integer Predicates
12498//===----------------------------------------------------------------------===//
12499
12501 if (const auto *ED = T->getAsEnumDecl())
12502 T = ED->getIntegerType();
12503 if (T->isBooleanType())
12504 return 1;
12505 if (const auto *EIT = T->getAs<BitIntType>())
12506 return EIT->getNumBits();
12507 // For builtin types, just use the standard type sizing method
12508 return (unsigned)getTypeSize(T);
12509}
12510
12512 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12513 T->isFixedPointType()) &&
12514 "Unexpected type");
12515
12516 // Turn <4 x signed int> -> <4 x unsigned int>
12517 if (const auto *VTy = T->getAs<VectorType>())
12518 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
12519 VTy->getNumElements(), VTy->getVectorKind());
12520
12521 // For _BitInt, return an unsigned _BitInt with same width.
12522 if (const auto *EITy = T->getAs<BitIntType>())
12523 return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
12524
12525 // For the overflow behavior types, construct a new unsigned variant
12526 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
12528 OBT->getBehaviorKind(),
12529 getCorrespondingUnsignedType(OBT->getUnderlyingType()));
12530
12531 // For enums, get the underlying integer type of the enum, and let the general
12532 // integer type signchanging code handle it.
12533 if (const auto *ED = T->getAsEnumDecl())
12534 T = ED->getIntegerType();
12535
12536 switch (T->castAs<BuiltinType>()->getKind()) {
12537 case BuiltinType::Char_U:
12538 // Plain `char` is mapped to `unsigned char` even if it's already unsigned
12539 case BuiltinType::Char_S:
12540 case BuiltinType::SChar:
12541 case BuiltinType::Char8:
12542 return UnsignedCharTy;
12543 case BuiltinType::Short:
12544 return UnsignedShortTy;
12545 case BuiltinType::Int:
12546 return UnsignedIntTy;
12547 case BuiltinType::Long:
12548 return UnsignedLongTy;
12549 case BuiltinType::LongLong:
12550 return UnsignedLongLongTy;
12551 case BuiltinType::Int128:
12552 return UnsignedInt128Ty;
12553 // wchar_t is special. It is either signed or not, but when it's signed,
12554 // there's no matching "unsigned wchar_t". Therefore we return the unsigned
12555 // version of its underlying type instead.
12556 case BuiltinType::WChar_S:
12557 return getUnsignedWCharType();
12558
12559 case BuiltinType::ShortAccum:
12560 return UnsignedShortAccumTy;
12561 case BuiltinType::Accum:
12562 return UnsignedAccumTy;
12563 case BuiltinType::LongAccum:
12564 return UnsignedLongAccumTy;
12565 case BuiltinType::SatShortAccum:
12567 case BuiltinType::SatAccum:
12568 return SatUnsignedAccumTy;
12569 case BuiltinType::SatLongAccum:
12571 case BuiltinType::ShortFract:
12572 return UnsignedShortFractTy;
12573 case BuiltinType::Fract:
12574 return UnsignedFractTy;
12575 case BuiltinType::LongFract:
12576 return UnsignedLongFractTy;
12577 case BuiltinType::SatShortFract:
12579 case BuiltinType::SatFract:
12580 return SatUnsignedFractTy;
12581 case BuiltinType::SatLongFract:
12583 default:
12584 assert((T->hasUnsignedIntegerRepresentation() ||
12585 T->isUnsignedFixedPointType()) &&
12586 "Unexpected signed integer or fixed point type");
12587 return T;
12588 }
12589}
12590
12592 assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
12593 T->isFixedPointType()) &&
12594 "Unexpected type");
12595
12596 // Turn <4 x unsigned int> -> <4 x signed int>
12597 if (const auto *VTy = T->getAs<VectorType>())
12598 return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
12599 VTy->getNumElements(), VTy->getVectorKind());
12600
12601 // For _BitInt, return a signed _BitInt with same width.
12602 if (const auto *EITy = T->getAs<BitIntType>())
12603 return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
12604
12605 // For enums, get the underlying integer type of the enum, and let the general
12606 // integer type signchanging code handle it.
12607 if (const auto *ED = T->getAsEnumDecl())
12608 T = ED->getIntegerType();
12609
12610 switch (T->castAs<BuiltinType>()->getKind()) {
12611 case BuiltinType::Char_S:
12612 // Plain `char` is mapped to `signed char` even if it's already signed
12613 case BuiltinType::Char_U:
12614 case BuiltinType::UChar:
12615 case BuiltinType::Char8:
12616 return SignedCharTy;
12617 case BuiltinType::UShort:
12618 return ShortTy;
12619 case BuiltinType::UInt:
12620 return IntTy;
12621 case BuiltinType::ULong:
12622 return LongTy;
12623 case BuiltinType::ULongLong:
12624 return LongLongTy;
12625 case BuiltinType::UInt128:
12626 return Int128Ty;
12627 // wchar_t is special. It is either unsigned or not, but when it's unsigned,
12628 // there's no matching "signed wchar_t". Therefore we return the signed
12629 // version of its underlying type instead.
12630 case BuiltinType::WChar_U:
12631 return getSignedWCharType();
12632
12633 case BuiltinType::UShortAccum:
12634 return ShortAccumTy;
12635 case BuiltinType::UAccum:
12636 return AccumTy;
12637 case BuiltinType::ULongAccum:
12638 return LongAccumTy;
12639 case BuiltinType::SatUShortAccum:
12640 return SatShortAccumTy;
12641 case BuiltinType::SatUAccum:
12642 return SatAccumTy;
12643 case BuiltinType::SatULongAccum:
12644 return SatLongAccumTy;
12645 case BuiltinType::UShortFract:
12646 return ShortFractTy;
12647 case BuiltinType::UFract:
12648 return FractTy;
12649 case BuiltinType::ULongFract:
12650 return LongFractTy;
12651 case BuiltinType::SatUShortFract:
12652 return SatShortFractTy;
12653 case BuiltinType::SatUFract:
12654 return SatFractTy;
12655 case BuiltinType::SatULongFract:
12656 return SatLongFractTy;
12657 default:
12658 assert(
12659 (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
12660 "Unexpected signed integer or fixed point type");
12661 return T;
12662 }
12663}
12664
12666
12669
12670//===----------------------------------------------------------------------===//
12671// Builtin Type Computation
12672//===----------------------------------------------------------------------===//
12673
12674/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
12675/// pointer over the consumed characters. This returns the resultant type. If
12676/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
12677/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
12678/// a vector of "i*".
12679///
12680/// RequiresICE is filled in on return to indicate whether the value is required
12681/// to be an Integer Constant Expression.
12682static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
12684 bool &RequiresICE,
12685 bool AllowTypeModifiers) {
12686 // Modifiers.
12687 int HowLong = 0;
12688 bool Signed = false, Unsigned = false;
12689 bool IsChar = false, IsShort = false;
12690 RequiresICE = false;
12691
12692 // Read the prefixed modifiers first.
12693 bool Done = false;
12694 #ifndef NDEBUG
12695 bool IsSpecial = false;
12696 #endif
12697 while (!Done) {
12698 switch (*Str++) {
12699 default: Done = true; --Str; break;
12700 case 'I':
12701 RequiresICE = true;
12702 break;
12703 case 'S':
12704 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
12705 assert(!Signed && "Can't use 'S' modifier multiple times!");
12706 Signed = true;
12707 break;
12708 case 'U':
12709 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
12710 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
12711 Unsigned = true;
12712 break;
12713 case 'B':
12714 // This modifier represents int8 type (byte-width).
12715 assert(!IsSpecial &&
12716 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12717 assert(HowLong == 0 && "Can't use both 'L' and 'B' modifiers!");
12718#ifndef NDEBUG
12719 IsSpecial = true;
12720#endif
12721 IsChar = true;
12722 break;
12723 case 'T':
12724 // This modifier represents int16 type (short-width).
12725 assert(!IsSpecial &&
12726 "Can't use two 'N', 'W', 'Z', 'O', 'B', or 'T' modifiers!");
12727 assert(HowLong == 0 && "Can't use both 'L' and 'T' modifiers!");
12728#ifndef NDEBUG
12729 IsSpecial = true;
12730#endif
12731 IsShort = true;
12732 break;
12733 case 'L':
12734 assert(!IsSpecial &&
12735 "Can't use 'L' with 'W', 'N', 'Z', 'O', 'B', or 'T' modifiers");
12736 assert(HowLong <= 2 && "Can't have LLLL modifier");
12737 ++HowLong;
12738 break;
12739 case 'N':
12740 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
12741 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12742 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
12743 #ifndef NDEBUG
12744 IsSpecial = true;
12745 #endif
12746 if (Context.getTargetInfo().getLongWidth() == 32)
12747 ++HowLong;
12748 break;
12749 case 'W':
12750 // This modifier represents int64 type.
12751 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12752 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
12753 #ifndef NDEBUG
12754 IsSpecial = true;
12755 #endif
12756 switch (Context.getTargetInfo().getInt64Type()) {
12757 default:
12758 llvm_unreachable("Unexpected integer type");
12760 HowLong = 1;
12761 break;
12763 HowLong = 2;
12764 break;
12765 }
12766 break;
12767 case 'Z':
12768 // This modifier represents int32 type.
12769 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12770 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
12771 #ifndef NDEBUG
12772 IsSpecial = true;
12773 #endif
12774 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
12775 default:
12776 llvm_unreachable("Unexpected integer type");
12778 HowLong = 0;
12779 break;
12781 HowLong = 1;
12782 break;
12784 HowLong = 2;
12785 break;
12786 }
12787 break;
12788 case 'O':
12789 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
12790 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
12791 #ifndef NDEBUG
12792 IsSpecial = true;
12793 #endif
12794 if (Context.getLangOpts().OpenCL)
12795 HowLong = 1;
12796 else
12797 HowLong = 2;
12798 break;
12799 }
12800 }
12801
12802 QualType Type;
12803
12804 // Read the base type.
12805 switch (*Str++) {
12806 default:
12807 llvm_unreachable("Unknown builtin type letter!");
12808 case 'x':
12809 assert(HowLong == 0 && !Signed && !Unsigned &&
12810 "Bad modifiers used with 'x'!");
12811 Type = Context.Float16Ty;
12812 break;
12813 case 'y':
12814 assert(HowLong == 0 && !Signed && !Unsigned &&
12815 "Bad modifiers used with 'y'!");
12816 Type = Context.BFloat16Ty;
12817 break;
12818 case 'v':
12819 assert(HowLong == 0 && !Signed && !Unsigned &&
12820 "Bad modifiers used with 'v'!");
12821 Type = Context.VoidTy;
12822 break;
12823 case 'h':
12824 assert(HowLong == 0 && !Signed && !Unsigned &&
12825 "Bad modifiers used with 'h'!");
12826 Type = Context.HalfTy;
12827 break;
12828 case 'f':
12829 assert(HowLong == 0 && !Signed && !Unsigned &&
12830 "Bad modifiers used with 'f'!");
12831 Type = Context.FloatTy;
12832 break;
12833 case 'd':
12834 assert(HowLong < 3 && !Signed && !Unsigned &&
12835 "Bad modifiers used with 'd'!");
12836 if (HowLong == 1)
12837 Type = Context.LongDoubleTy;
12838 else if (HowLong == 2)
12839 Type = Context.Float128Ty;
12840 else
12841 Type = Context.DoubleTy;
12842 break;
12843 case 's':
12844 assert(HowLong == 0 && "Bad modifiers used with 's'!");
12845 if (Unsigned)
12846 Type = Context.UnsignedShortTy;
12847 else
12848 Type = Context.ShortTy;
12849 break;
12850 case 'i':
12851 if (IsChar)
12852 Type = Unsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
12853 else if (IsShort)
12854 Type = Unsigned ? Context.UnsignedShortTy : Context.ShortTy;
12855 else if (HowLong == 3)
12856 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
12857 else if (HowLong == 2)
12858 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
12859 else if (HowLong == 1)
12860 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
12861 else
12862 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
12863 break;
12864 case 'c':
12865 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
12866 if (Signed)
12867 Type = Context.SignedCharTy;
12868 else if (Unsigned)
12869 Type = Context.UnsignedCharTy;
12870 else
12871 Type = Context.CharTy;
12872 break;
12873 case 'b': // boolean
12874 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
12875 Type = Context.BoolTy;
12876 break;
12877 case 'z': // size_t.
12878 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
12879 Type = Context.getSizeType();
12880 break;
12881 case 'w': // wchar_t.
12882 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
12883 Type = Context.getWideCharType();
12884 break;
12885 case 'F':
12886 Type = Context.getCFConstantStringType();
12887 break;
12888 case 'G':
12889 Type = Context.getObjCIdType();
12890 break;
12891 case 'H':
12892 Type = Context.getObjCSelType();
12893 break;
12894 case 'M':
12895 Type = Context.getObjCSuperType();
12896 break;
12897 case 'a':
12898 Type = Context.getBuiltinVaListType();
12899 assert(!Type.isNull() && "builtin va list type not initialized!");
12900 break;
12901 case 'A':
12902 // This is a "reference" to a va_list; however, what exactly
12903 // this means depends on how va_list is defined. There are two
12904 // different kinds of va_list: ones passed by value, and ones
12905 // passed by reference. An example of a by-value va_list is
12906 // x86, where va_list is a char*. An example of by-ref va_list
12907 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
12908 // we want this argument to be a char*&; for x86-64, we want
12909 // it to be a __va_list_tag*.
12910 Type = Context.getBuiltinVaListType();
12911 assert(!Type.isNull() && "builtin va list type not initialized!");
12912 if (Type->isArrayType())
12913 Type = Context.getArrayDecayedType(Type);
12914 else
12915 Type = Context.getLValueReferenceType(Type);
12916 break;
12917 case 'q': {
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 Type = Context.getScalableVectorType(ElementType, NumElements);
12928 break;
12929 }
12930 case 'Q': {
12931 switch (*Str++) {
12932 case 'a': {
12933 Type = Context.SveCountTy;
12934 break;
12935 }
12936 case 'b': {
12937 Type = Context.AMDGPUBufferRsrcTy;
12938 break;
12939 }
12940 case 'c': {
12941 Type = Context.AMDGPUFeaturePredicateTy;
12942 break;
12943 }
12944 case 't': {
12945 Type = Context.AMDGPUTextureTy;
12946 break;
12947 }
12948 case 'r': {
12949 Type = Context.HLSLResourceTy;
12950 break;
12951 }
12952 default:
12953 llvm_unreachable("Unexpected target builtin type");
12954 }
12955 break;
12956 }
12957 case 'V': {
12958 char *End;
12959 unsigned NumElements = strtoul(Str, &End, 10);
12960 assert(End != Str && "Missing vector size");
12961 Str = End;
12962
12963 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
12964 RequiresICE, false);
12965 assert(!RequiresICE && "Can't require vector ICE");
12966
12967 // TODO: No way to make AltiVec vectors in builtins yet.
12968 Type = Context.getVectorType(ElementType, NumElements, VectorKind::Generic);
12969 break;
12970 }
12971 case 'E': {
12972 char *End;
12973
12974 unsigned NumElements = strtoul(Str, &End, 10);
12975 assert(End != Str && "Missing vector size");
12976
12977 Str = End;
12978
12979 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12980 false);
12981 Type = Context.getExtVectorType(ElementType, NumElements);
12982 break;
12983 }
12984 case 'X': {
12985 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
12986 false);
12987 assert(!RequiresICE && "Can't require complex ICE");
12988 Type = Context.getComplexType(ElementType);
12989 break;
12990 }
12991 case 'Y':
12992 Type = Context.getPointerDiffType();
12993 break;
12994 case 'P':
12995 Type = Context.getFILEType();
12996 if (Type.isNull()) {
12998 return {};
12999 }
13000 break;
13001 case 'J':
13002 if (Signed)
13003 Type = Context.getsigjmp_bufType();
13004 else
13005 Type = Context.getjmp_bufType();
13006
13007 if (Type.isNull()) {
13009 return {};
13010 }
13011 break;
13012 case 'K':
13013 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
13014 Type = Context.getucontext_tType();
13015
13016 if (Type.isNull()) {
13018 return {};
13019 }
13020 break;
13021 case 'p':
13022 Type = Context.getProcessIDType();
13023 break;
13024 case 'm':
13025 Type = Context.MFloat8Ty;
13026 break;
13027 }
13028
13029 // If there are modifiers and if we're allowed to parse them, go for it.
13030 Done = !AllowTypeModifiers;
13031 while (!Done) {
13032 switch (char c = *Str++) {
13033 default: Done = true; --Str; break;
13034 case '*':
13035 case '&': {
13036 // Both pointers and references can have their pointee types
13037 // qualified with an address space.
13038 char *End;
13039 unsigned AddrSpace = strtoul(Str, &End, 10);
13040 if (End != Str) {
13041 // Note AddrSpace == 0 is not the same as an unspecified address space.
13042 Type = Context.getAddrSpaceQualType(
13043 Type,
13044 Context.getLangASForBuiltinAddressSpace(AddrSpace));
13045 Str = End;
13046 }
13047 if (c == '*')
13048 Type = Context.getPointerType(Type);
13049 else
13050 Type = Context.getLValueReferenceType(Type);
13051 break;
13052 }
13053 // FIXME: There's no way to have a built-in with an rvalue ref arg.
13054 case 'C':
13055 Type = Type.withConst();
13056 break;
13057 case 'D':
13058 Type = Context.getVolatileType(Type);
13059 break;
13060 case 'R':
13061 Type = Type.withRestrict();
13062 break;
13063 }
13064 }
13065
13066 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
13067 "Integer constant 'I' type must be an integer");
13068
13069 return Type;
13070}
13071
13072// On some targets such as PowerPC, some of the builtins are defined with custom
13073// type descriptors for target-dependent types. These descriptors are decoded in
13074// other functions, but it may be useful to be able to fall back to default
13075// descriptor decoding to define builtins mixing target-dependent and target-
13076// independent types. This function allows decoding one type descriptor with
13077// default decoding.
13078QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
13079 GetBuiltinTypeError &Error, bool &RequireICE,
13080 bool AllowTypeModifiers) const {
13081 return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
13082}
13083
13084/// GetBuiltinType - Return the type for the specified builtin.
13087 unsigned *IntegerConstantArgs) const {
13088 const char *TypeStr = BuiltinInfo.getTypeString(Id);
13089 if (TypeStr[0] == '\0') {
13091 return {};
13092 }
13093
13094 SmallVector<QualType, 8> ArgTypes;
13095
13096 bool RequiresICE = false;
13097 Error = GE_None;
13098 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
13099 RequiresICE, true);
13100 if (Error != GE_None)
13101 return {};
13102
13103 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
13104
13105 while (TypeStr[0] && TypeStr[0] != '.') {
13106 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
13107 if (Error != GE_None)
13108 return {};
13109
13110 // If this argument is required to be an IntegerConstantExpression and the
13111 // caller cares, fill in the bitmask we return.
13112 if (RequiresICE && IntegerConstantArgs)
13113 *IntegerConstantArgs |= 1 << ArgTypes.size();
13114
13115 // Do array -> pointer decay. The builtin should use the decayed type.
13116 if (Ty->isArrayType())
13117 Ty = getArrayDecayedType(Ty);
13118
13119 ArgTypes.push_back(Ty);
13120 }
13121
13122 if (Id == Builtin::BI__GetExceptionInfo)
13123 return {};
13124
13125 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
13126 "'.' should only occur at end of builtin type list!");
13127
13128 bool Variadic = (TypeStr[0] == '.');
13129
13130 FunctionType::ExtInfo EI(Target->getDefaultCallingConv());
13131 if (BuiltinInfo.isNoReturn(Id))
13132 EI = EI.withNoReturn(true);
13133
13134 // We really shouldn't be making a no-proto type here.
13135 if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
13136 return getFunctionNoProtoType(ResType, EI);
13137
13139 EPI.ExtInfo = EI;
13140 EPI.Variadic = Variadic;
13141 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
13142 EPI.ExceptionSpec.Type =
13144
13145 return getFunctionType(ResType, ArgTypes, EPI);
13146}
13147
13149 const FunctionDecl *FD) {
13150 if (!FD->isExternallyVisible())
13151 return GVA_Internal;
13152
13153 // Non-user-provided functions get emitted as weak definitions with every
13154 // use, no matter whether they've been explicitly instantiated etc.
13155 if (!FD->isUserProvided())
13156 return GVA_DiscardableODR;
13157
13159 switch (FD->getTemplateSpecializationKind()) {
13160 case TSK_Undeclared:
13163 break;
13164
13166 return GVA_StrongODR;
13167
13168 // C++11 [temp.explicit]p10:
13169 // [ Note: The intent is that an inline function that is the subject of
13170 // an explicit instantiation declaration will still be implicitly
13171 // instantiated when used so that the body can be considered for
13172 // inlining, but that no out-of-line copy of the inline function would be
13173 // generated in the translation unit. -- end note ]
13176
13179 break;
13180 }
13181
13182 if (!FD->isInlined())
13183 return External;
13184
13185 if ((!Context.getLangOpts().CPlusPlus &&
13186 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13187 !FD->hasAttr<DLLExportAttr>()) ||
13188 FD->hasAttr<GNUInlineAttr>()) {
13189 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
13190
13191 // GNU or C99 inline semantics. Determine whether this symbol should be
13192 // externally visible.
13193 if (auto *Def = FD->getDefinition();
13195 return External;
13196
13197 // C99 inline semantics, where the symbol is not externally visible.
13199 }
13200
13201 // Functions specified with extern and inline in -fms-compatibility mode
13202 // forcibly get emitted. While the body of the function cannot be later
13203 // replaced, the function definition cannot be discarded.
13204 if (FD->isMSExternInline())
13205 return GVA_StrongODR;
13206
13207 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13209 cast<CXXConstructorDecl>(FD)->isInheritingConstructor() &&
13210 !FD->hasAttr<DLLExportAttr>()) {
13211 // Both Clang and MSVC implement inherited constructors as forwarding
13212 // thunks that delegate to the base constructor. Keep non-dllexport
13213 // inheriting constructor thunks internal since they are not needed
13214 // outside the translation unit.
13215 //
13216 // dllexport inherited constructors are exempted so they are externally
13217 // visible, matching MSVC's export behavior. Inherited constructors
13218 // whose parameters prevent ABI-compatible forwarding (e.g. callee-
13219 // cleanup types) are excluded from export in Sema to avoid silent
13220 // runtime mismatches.
13221 return GVA_Internal;
13222 }
13223
13224 return GVA_DiscardableODR;
13225}
13226
13228 const Decl *D, GVALinkage L) {
13229 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
13230 // dllexport/dllimport on inline functions.
13231 if (D->hasAttr<DLLImportAttr>()) {
13232 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
13234 } else if (D->hasAttr<DLLExportAttr>()) {
13235 if (L == GVA_DiscardableODR)
13236 return GVA_StrongODR;
13237 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
13238 // Device-side functions with __global__ attribute must always be
13239 // visible externally so they can be launched from host.
13240 if (D->hasAttr<CUDAGlobalAttr>() &&
13241 (L == GVA_DiscardableODR || L == GVA_Internal))
13242 return GVA_StrongODR;
13243 // Single source offloading languages like CUDA/HIP need to be able to
13244 // access static device variables from host code of the same compilation
13245 // unit. This is done by externalizing the static variable with a shared
13246 // name between the host and device compilation which is the same for the
13247 // same compilation unit whereas different among different compilation
13248 // units.
13249 if (Context.shouldExternalize(D))
13250 return GVA_StrongExternal;
13251 }
13252 return L;
13253}
13254
13255/// Adjust the GVALinkage for a declaration based on what an external AST source
13256/// knows about whether there can be other definitions of this declaration.
13257static GVALinkage
13259 GVALinkage L) {
13260 ExternalASTSource *Source = Ctx.getExternalSource();
13261 if (!Source)
13262 return L;
13263
13264 switch (Source->hasExternalDefinitions(D)) {
13266 // Other translation units rely on us to provide the definition.
13267 if (L == GVA_DiscardableODR)
13268 return GVA_StrongODR;
13269 break;
13270
13273
13275 break;
13276 }
13277 return L;
13278}
13279
13285
13287 const VarDecl *VD) {
13288 // As an extension for interactive REPLs, make sure constant variables are
13289 // only emitted once instead of LinkageComputer::getLVForNamespaceScopeDecl
13290 // marking them as internal.
13291 if (Context.getLangOpts().CPlusPlus &&
13292 Context.getLangOpts().IncrementalExtensions &&
13293 VD->getType().isConstQualified() &&
13294 !VD->getType().isVolatileQualified() && !VD->isInline() &&
13296 return GVA_DiscardableODR;
13297
13298 if (!VD->isExternallyVisible())
13299 return GVA_Internal;
13300
13301 if (VD->isStaticLocal()) {
13302 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
13303 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
13304 LexicalContext = LexicalContext->getLexicalParent();
13305
13306 // ObjC Blocks can create local variables that don't have a FunctionDecl
13307 // LexicalContext.
13308 if (!LexicalContext)
13309 return GVA_DiscardableODR;
13310
13311 // Otherwise, let the static local variable inherit its linkage from the
13312 // nearest enclosing function.
13313 auto StaticLocalLinkage =
13314 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
13315
13316 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
13317 // be emitted in any object with references to the symbol for the object it
13318 // contains, whether inline or out-of-line."
13319 // Similar behavior is observed with MSVC. An alternative ABI could use
13320 // StrongODR/AvailableExternally to match the function, but none are
13321 // known/supported currently.
13322 if (StaticLocalLinkage == GVA_StrongODR ||
13323 StaticLocalLinkage == GVA_AvailableExternally)
13324 return GVA_DiscardableODR;
13325 return StaticLocalLinkage;
13326 }
13327
13328 // MSVC treats in-class initialized static data members as definitions.
13329 // By giving them non-strong linkage, out-of-line definitions won't
13330 // cause link errors.
13331 if (Context.isMSStaticDataMemberInlineDefinition(VD))
13332 return GVA_DiscardableODR;
13333
13334 // Most non-template variables have strong linkage; inline variables are
13335 // linkonce_odr or (occasionally, for compatibility) weak_odr.
13336 GVALinkage StrongLinkage;
13337 switch (Context.getInlineVariableDefinitionKind(VD)) {
13339 StrongLinkage = GVA_StrongExternal;
13340 break;
13343 StrongLinkage = GVA_DiscardableODR;
13344 break;
13346 StrongLinkage = GVA_StrongODR;
13347 break;
13348 }
13349
13350 switch (VD->getTemplateSpecializationKind()) {
13351 case TSK_Undeclared:
13352 return StrongLinkage;
13353
13355 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13356 VD->isStaticDataMember()
13358 : StrongLinkage;
13359
13361 return GVA_StrongODR;
13362
13365
13367 return GVA_DiscardableODR;
13368 }
13369
13370 llvm_unreachable("Invalid Linkage!");
13371}
13372
13378
13380 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13381 if (!VD->isFileVarDecl())
13382 return false;
13383 // Global named register variables (GNU extension) are never emitted.
13384 if (VD->getStorageClass() == SC_Register)
13385 return false;
13386 if (VD->getDescribedVarTemplate() ||
13388 return false;
13389 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13390 // We never need to emit an uninstantiated function template.
13391 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13392 return false;
13393 } else if (isa<PragmaCommentDecl>(D))
13394 return true;
13396 return true;
13397 else if (isa<OMPRequiresDecl>(D))
13398 return true;
13399 else if (isa<OMPThreadPrivateDecl>(D))
13400 return !D->getDeclContext()->isDependentContext();
13401 else if (isa<OMPAllocateDecl>(D))
13402 return !D->getDeclContext()->isDependentContext();
13404 return !D->getDeclContext()->isDependentContext();
13405 else if (isa<ImportDecl>(D))
13406 return true;
13407 else
13408 return false;
13409
13410 // If this is a member of a class template, we do not need to emit it.
13412 return false;
13413
13414 // Weak references don't produce any output by themselves.
13415 if (D->hasAttr<WeakRefAttr>())
13416 return false;
13417
13418 // SYCL device compilation requires that functions defined with the
13419 // sycl_kernel_entry_point or sycl_external attributes be emitted. All
13420 // other entities are emitted only if they are used by a function
13421 // defined with one of those attributes.
13422 if (LangOpts.SYCLIsDevice)
13423 return isa<FunctionDecl>(D) && (D->hasAttr<SYCLKernelEntryPointAttr>() ||
13424 D->hasAttr<SYCLExternalAttr>());
13425
13426 // Aliases and used decls are required.
13427 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
13428 return true;
13429
13430 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13431 // Forward declarations aren't required.
13432 if (!FD->doesThisDeclarationHaveABody())
13433 return FD->doesDeclarationForceExternallyVisibleDefinition();
13434
13435 // Constructors and destructors are required.
13436 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
13437 return true;
13438
13439 // The key function for a class is required. This rule only comes
13440 // into play when inline functions can be key functions, though.
13441 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13442 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13443 const CXXRecordDecl *RD = MD->getParent();
13444 if (MD->isOutOfLine() && RD->isDynamicClass()) {
13445 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
13446 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
13447 return true;
13448 }
13449 }
13450 }
13451
13453
13454 // static, static inline, always_inline, and extern inline functions can
13455 // always be deferred. Normal inline functions can be deferred in C99/C++.
13456 // Implicit template instantiations can also be deferred in C++.
13458 }
13459
13460 const auto *VD = cast<VarDecl>(D);
13461 assert(VD->isFileVarDecl() && "Expected file scoped var");
13462
13463 // If the decl is marked as `declare target to`, it should be emitted for the
13464 // host and for the device.
13465 if (LangOpts.OpenMP &&
13466 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13467 return true;
13468
13469 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
13471 return false;
13472
13473 if (VD->shouldEmitInExternalSource())
13474 return false;
13475
13476 // Variables that can be needed in other TUs are required.
13479 return true;
13480
13481 // We never need to emit a variable that is available in another TU.
13483 return false;
13484
13485 // Variables that have destruction with side-effects are required.
13486 if (VD->needsDestruction(*this))
13487 return true;
13488
13489 // Variables that have initialization with side-effects are required.
13490 if (VD->hasInitWithSideEffects())
13491 return true;
13492
13493 // Likewise, variables with tuple-like bindings are required if their
13494 // bindings have side-effects.
13495 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
13496 for (const auto *BD : DD->flat_bindings())
13497 if (const auto *BindingVD = BD->getHoldingVar())
13498 if (DeclMustBeEmitted(BindingVD))
13499 return true;
13500 }
13501
13502 return false;
13503}
13504
13505template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) {
13506 if (auto *A = D->getAttr<AttrT>())
13507 return A->isImplicit();
13508 return D->isImplicit();
13509}
13510
13512 assert(LangOpts.CUDA && "Should not be called by non-CUDA languages");
13513 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
13514 "Expected Variable or Function");
13515
13516 if (const auto *VD = dyn_cast<VarDecl>(D)) {
13517 // We need to emit host-side 'shadows' for all global device-side variables
13518 // because the CUDA runtime needs their size and host-side address in order
13519 // to provide access to their device-side incarnations.
13520 return !LangOpts.CUDAIsDevice || VD->hasAttr<CUDADeviceAttr>() ||
13521 VD->hasAttr<CUDAConstantAttr>() || VD->hasAttr<CUDASharedAttr>() ||
13522 VD->getType()->isCUDADeviceBuiltinSurfaceType() ||
13523 VD->getType()->isCUDADeviceBuiltinTextureType();
13524 }
13525
13526 const auto *FD = cast<FunctionDecl>(D);
13527 // Device-only functions are the only things we skip on the host.
13528 if (!LangOpts.CUDAIsDevice)
13529 return FD->hasAttr<CUDAHostAttr>() || !FD->hasAttr<CUDADeviceAttr>();
13530
13531 // Non-constexpr non-lambda implicit host device functions are not emitted
13532 // unless they are used on device side.
13533 return (FD->hasAttr<CUDADeviceAttr>() &&
13534 !(LangOpts.OffloadImplicitHostDeviceTemplates &&
13536 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() &&
13537 !isLambdaCallOperator(FD) &&
13539 FD->hasAttr<CUDAGlobalAttr>() ||
13540 (LangOpts.HIPStdPar && !FD->hasAttr<CUDAHostAttr>());
13541}
13542
13544 const FunctionDecl *FD,
13545 llvm::function_ref<void(FunctionDecl *)> Pred) const {
13546 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
13547 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
13548 FD = FD->getMostRecentDecl();
13549 // FIXME: The order of traversal here matters and depends on the order of
13550 // lookup results, which happens to be (mostly) oldest-to-newest, but we
13551 // shouldn't rely on that.
13552 for (auto *CurDecl :
13554 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
13555 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
13556 SeenDecls.insert(CurFD).second) {
13557 Pred(CurFD);
13558 }
13559 }
13560}
13561
13563 bool IsCXXMethod) const {
13564 // Pass through to the C++ ABI object
13565 if (IsCXXMethod)
13566 return ABI->getDefaultMethodCallConv(IsVariadic);
13567
13568 switch (LangOpts.getDefaultCallingConv()) {
13570 break;
13572 return CC_C;
13574 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
13575 return CC_X86FastCall;
13576 break;
13578 if (!IsVariadic)
13579 return CC_X86StdCall;
13580 break;
13582 // __vectorcall cannot be applied to variadic functions.
13583 if (!IsVariadic)
13584 return CC_X86VectorCall;
13585 break;
13587 // __regcall cannot be applied to variadic functions.
13588 if (!IsVariadic)
13589 return CC_X86RegCall;
13590 break;
13592 if (!IsVariadic)
13593 return CC_M68kRTD;
13594 break;
13595 }
13596 return Target->getDefaultCallingConv();
13597}
13598
13600 // Pass through to the C++ ABI object
13601 return ABI->isNearlyEmpty(RD);
13602}
13603
13605 if (!VTContext) {
13606 auto ABI = Target->getCXXABI();
13607 if (ABI.isMicrosoft())
13608 VTContext.reset(new MicrosoftVTableContext(*this));
13609 else {
13610 VTContext.reset(new ItaniumVTableContext(*this));
13611 }
13612 }
13613 return VTContext.get();
13614}
13615
13617 if (!T)
13618 T = Target;
13619 switch (T->getCXXABI().getKind()) {
13620 case TargetCXXABI::AppleARM64:
13621 case TargetCXXABI::Fuchsia:
13622 case TargetCXXABI::GenericAArch64:
13623 case TargetCXXABI::GenericItanium:
13624 case TargetCXXABI::GenericARM:
13625 case TargetCXXABI::GenericMIPS:
13626 case TargetCXXABI::iOS:
13627 case TargetCXXABI::WebAssembly:
13628 case TargetCXXABI::WatchOS:
13629 case TargetCXXABI::XL:
13631 case TargetCXXABI::Microsoft:
13633 }
13634 llvm_unreachable("Unsupported ABI");
13635}
13636
13638 assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
13639 "Device mangle context does not support Microsoft mangling.");
13640 switch (T.getCXXABI().getKind()) {
13641 case TargetCXXABI::AppleARM64:
13642 case TargetCXXABI::Fuchsia:
13643 case TargetCXXABI::GenericAArch64:
13644 case TargetCXXABI::GenericItanium:
13645 case TargetCXXABI::GenericARM:
13646 case TargetCXXABI::GenericMIPS:
13647 case TargetCXXABI::iOS:
13648 case TargetCXXABI::WebAssembly:
13649 case TargetCXXABI::WatchOS:
13650 case TargetCXXABI::XL:
13652 *this, getDiagnostics(),
13653 [](ASTContext &, const NamedDecl *ND) -> UnsignedOrNone {
13654 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
13655 return RD->getDeviceLambdaManglingNumber();
13656 return std::nullopt;
13657 },
13658 /*IsAux=*/true);
13659 case TargetCXXABI::Microsoft:
13661 /*IsAux=*/true);
13662 }
13663 llvm_unreachable("Unsupported ABI");
13664}
13665
13667 // If the host and device have different C++ ABIs, mark it as the device
13668 // mangle context so that the mangling needs to retrieve the additional
13669 // device lambda mangling number instead of the regular host one.
13670 if (getAuxTargetInfo() && getTargetInfo().getCXXABI().isMicrosoft() &&
13671 getAuxTargetInfo()->getCXXABI().isItaniumFamily()) {
13673 }
13674
13676}
13677
13678CXXABI::~CXXABI() = default;
13679
13681 return ASTRecordLayouts.getMemorySize() +
13682 llvm::capacity_in_bytes(ObjCLayouts) +
13683 llvm::capacity_in_bytes(KeyFunctions) +
13684 llvm::capacity_in_bytes(ObjCImpls) +
13685 llvm::capacity_in_bytes(BlockVarCopyInits) +
13686 llvm::capacity_in_bytes(DeclAttrs) +
13687 llvm::capacity_in_bytes(TemplateOrInstantiation) +
13688 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
13689 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
13690 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
13691 llvm::capacity_in_bytes(OverriddenMethods) +
13692 llvm::capacity_in_bytes(Types) +
13693 llvm::capacity_in_bytes(VariableArrayTypes);
13694}
13695
13696/// getIntTypeForBitwidth -
13697/// sets integer QualTy according to specified details:
13698/// bitwidth, signed/unsigned.
13699/// Returns empty type if there is no appropriate target types.
13701 unsigned Signed) const {
13703 CanQualType QualTy = getFromTargetType(Ty);
13704 if (!QualTy && DestWidth == 128)
13705 return Signed ? Int128Ty : UnsignedInt128Ty;
13706 return QualTy;
13707}
13708
13710 unsigned Signed) const {
13711 return getFromTargetType(
13712 getTargetInfo().getLeastIntTypeByWidth(DestWidth, Signed));
13713}
13714
13715/// getRealTypeForBitwidth -
13716/// sets floating point QualTy according to specified bitwidth.
13717/// Returns empty type if there is no appropriate target types.
13719 FloatModeKind ExplicitType) const {
13720 FloatModeKind Ty =
13721 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
13722 switch (Ty) {
13724 return HalfTy;
13726 return FloatTy;
13728 return DoubleTy;
13730 return LongDoubleTy;
13732 return Float128Ty;
13734 return Ibm128Ty;
13736 return {};
13737 }
13738
13739 llvm_unreachable("Unhandled TargetInfo::RealType value");
13740}
13741
13742void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
13743 if (Number <= 1)
13744 return;
13745
13746 MangleNumbers[ND] = Number;
13747
13748 if (Listener)
13749 Listener->AddedManglingNumber(ND, Number);
13750}
13751
13753 bool ForAuxTarget) const {
13754 auto I = MangleNumbers.find(ND);
13755 unsigned Res = I != MangleNumbers.end() ? I->second : 1;
13756 // CUDA/HIP host compilation encodes host and device mangling numbers
13757 // as lower and upper half of 32 bit integer.
13758 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
13759 Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
13760 } else {
13761 assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
13762 "number for aux target");
13763 }
13764 return Res > 1 ? Res : 1;
13765}
13766
13767void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
13768 if (Number <= 1)
13769 return;
13770
13771 StaticLocalNumbers[VD] = Number;
13772
13773 if (Listener)
13774 Listener->AddedStaticLocalNumbers(VD, Number);
13775}
13776
13778 auto I = StaticLocalNumbers.find(VD);
13779 return I != StaticLocalNumbers.end() ? I->second : 1;
13780}
13781
13783 bool IsDestroying) {
13784 if (!IsDestroying) {
13785 assert(!DestroyingOperatorDeletes.contains(FD->getCanonicalDecl()));
13786 return;
13787 }
13788 DestroyingOperatorDeletes.insert(FD->getCanonicalDecl());
13789}
13790
13792 return DestroyingOperatorDeletes.contains(FD->getCanonicalDecl());
13793}
13794
13796 bool IsTypeAware) {
13797 if (!IsTypeAware) {
13798 assert(!TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl()));
13799 return;
13800 }
13801 TypeAwareOperatorNewAndDeletes.insert(FD->getCanonicalDecl());
13802}
13803
13805 return TypeAwareOperatorNewAndDeletes.contains(FD->getCanonicalDecl());
13806}
13807
13809 FunctionDecl *OperatorDelete,
13810 OperatorDeleteKind K) const {
13811 switch (K) {
13813 OperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] = OperatorDelete;
13814 break;
13816 GlobalOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13817 OperatorDelete;
13818 break;
13820 ArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13821 OperatorDelete;
13822 break;
13824 GlobalArrayOperatorDeletesForVirtualDtor[Dtor->getCanonicalDecl()] =
13825 OperatorDelete;
13826 break;
13827 }
13828}
13829
13831 OperatorDeleteKind K) const {
13832 switch (K) {
13834 return OperatorDeletesForVirtualDtor.contains(Dtor->getCanonicalDecl());
13836 return GlobalOperatorDeletesForVirtualDtor.contains(
13837 Dtor->getCanonicalDecl());
13839 return ArrayOperatorDeletesForVirtualDtor.contains(
13840 Dtor->getCanonicalDecl());
13842 return GlobalArrayOperatorDeletesForVirtualDtor.contains(
13843 Dtor->getCanonicalDecl());
13844 }
13845 return false;
13846}
13847
13850 OperatorDeleteKind K) const {
13851 const CXXDestructorDecl *Canon = Dtor->getCanonicalDecl();
13852 switch (K) {
13854 if (OperatorDeletesForVirtualDtor.contains(Canon))
13855 return OperatorDeletesForVirtualDtor[Canon];
13856 return nullptr;
13858 if (GlobalOperatorDeletesForVirtualDtor.contains(Canon))
13859 return GlobalOperatorDeletesForVirtualDtor[Canon];
13860 return nullptr;
13862 if (ArrayOperatorDeletesForVirtualDtor.contains(Canon))
13863 return ArrayOperatorDeletesForVirtualDtor[Canon];
13864 return nullptr;
13866 if (GlobalArrayOperatorDeletesForVirtualDtor.contains(Canon))
13867 return GlobalArrayOperatorDeletesForVirtualDtor[Canon];
13868 return nullptr;
13869 }
13870 return nullptr;
13871}
13872
13874 const CXXRecordDecl *RD) {
13875 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13876 return false;
13877
13878 return MaybeRequireVectorDeletingDtor.count(RD);
13879}
13880
13882 const CXXRecordDecl *RD) {
13883 if (!getTargetInfo().emitVectorDeletingDtors(getLangOpts()))
13884 return;
13885
13886 MaybeRequireVectorDeletingDtor.insert(RD);
13887}
13888
13891 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13892 // Reopened namespaces share a mangling context so that declarations in
13893 // different namespace blocks do not receive duplicate mangling numbers.
13894 DC = DC->getPrimaryContext();
13895 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
13896 if (!MCtx)
13898 return *MCtx;
13899}
13900
13903 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
13904 std::unique_ptr<MangleNumberingContext> &MCtx =
13905 ExtraMangleNumberingContexts[D];
13906 if (!MCtx)
13908 return *MCtx;
13909}
13910
13911std::unique_ptr<MangleNumberingContext>
13913 return ABI->createMangleNumberingContext();
13914}
13915
13916const CXXConstructorDecl *
13918 return ABI->getCopyConstructorForExceptionObject(
13920}
13921
13923 CXXConstructorDecl *CD) {
13924 return ABI->addCopyConstructorForExceptionObject(
13927}
13928
13930 TypedefNameDecl *DD) {
13931 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
13932}
13933
13936 return ABI->getTypedefNameForUnnamedTagDecl(TD);
13937}
13938
13940 DeclaratorDecl *DD) {
13941 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
13942}
13943
13945 return ABI->getDeclaratorForUnnamedTagDecl(TD);
13946}
13947
13949 ParamIndices[D] = index;
13950}
13951
13953 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
13954 assert(I != ParamIndices.end() &&
13955 "ParmIndices lacks entry set by ParmVarDecl");
13956 return I->second;
13957}
13958
13960 unsigned Length) const {
13961 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
13962 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
13963 EltTy = EltTy.withConst();
13964
13965 EltTy = adjustStringLiteralBaseType(EltTy);
13966
13967 // Get an array type for the string, according to C99 6.4.5. This includes
13968 // the null terminator character.
13969 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
13970 ArraySizeModifier::Normal, /*IndexTypeQuals*/ 0);
13971}
13972
13975 StringLiteral *&Result = StringLiteralCache[Key];
13976 if (!Result)
13978 *this, Key, StringLiteralKind::Ordinary,
13979 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
13980 SourceLocation());
13981 return Result;
13982}
13983
13984MSGuidDecl *
13986 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
13987
13988 llvm::FoldingSetNodeID ID;
13989 MSGuidDecl::Profile(ID, Parts);
13990
13991 llvm::FoldingSetInsertToken Token;
13992 if (MSGuidDecl *Existing = MSGuidDecls.lookup(ID, Token))
13993 return Existing;
13994
13995 QualType GUIDType = getMSGuidType().withConst();
13996 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
13997 MSGuidDecls.insert(New, Token);
13998 return New;
13999}
14000
14003 const APValue &APVal) const {
14004 llvm::FoldingSetNodeID ID;
14006
14007 llvm::FoldingSetInsertToken Token;
14008 if (UnnamedGlobalConstantDecl *Existing =
14009 UnnamedGlobalConstantDecls.lookup(ID, Token))
14010 return Existing;
14011
14013 UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
14014 UnnamedGlobalConstantDecls.insert(New, Token);
14015 return New;
14016}
14017
14020 assert(T->isRecordType() && "template param object of unexpected type");
14021
14022 // C++ [temp.param]p8:
14023 // [...] a static storage duration object of type 'const T' [...]
14024 T.addConst();
14025
14026 llvm::FoldingSetNodeID ID;
14028
14029 llvm::FoldingSetInsertToken Token;
14030 if (TemplateParamObjectDecl *Existing =
14031 TemplateParamObjectDecls.lookup(ID, Token))
14032 return Existing;
14033
14034 TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
14035 TemplateParamObjectDecls.insert(New, Token);
14036 return New;
14037}
14038
14040 const llvm::Triple &T = getTargetInfo().getTriple();
14041 if (!T.isOSDarwin())
14042 return false;
14043
14044 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
14045 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
14046 return false;
14047
14048 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
14049 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
14050 uint64_t Size = sizeChars.getQuantity();
14051 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
14052 unsigned Align = alignChars.getQuantity();
14053 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
14054 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
14055}
14056
14057bool
14059 const ObjCMethodDecl *MethodImpl) {
14060 // No point trying to match an unavailable/deprecated mothod.
14061 if (MethodDecl->hasAttr<UnavailableAttr>()
14062 || MethodDecl->hasAttr<DeprecatedAttr>())
14063 return false;
14064 if (MethodDecl->getObjCDeclQualifier() !=
14065 MethodImpl->getObjCDeclQualifier())
14066 return false;
14067 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
14068 return false;
14069
14070 if (MethodDecl->param_size() != MethodImpl->param_size())
14071 return false;
14072
14073 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
14074 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
14075 EF = MethodDecl->param_end();
14076 IM != EM && IF != EF; ++IM, ++IF) {
14077 const ParmVarDecl *DeclVar = (*IF);
14078 const ParmVarDecl *ImplVar = (*IM);
14079 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
14080 return false;
14081 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
14082 return false;
14083 }
14084
14085 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
14086}
14087
14089 LangAS AS;
14091 AS = LangAS::Default;
14092 else
14093 AS = QT->getPointeeType().getAddressSpace();
14094
14096}
14097
14100}
14101
14102bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
14103 if (X == Y)
14104 return true;
14105 if (!X || !Y)
14106 return false;
14107 llvm::FoldingSetNodeID IDX, IDY;
14108 X->Profile(IDX, *this, /*Canonical=*/true);
14109 Y->Profile(IDY, *this, /*Canonical=*/true);
14110 return IDX == IDY;
14111}
14112
14113// The getCommon* helpers return, for given 'same' X and Y entities given as
14114// inputs, another entity which is also the 'same' as the inputs, but which
14115// is closer to the canonical form of the inputs, each according to a given
14116// criteria.
14117// The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
14118// the regular ones.
14119
14121 if (!declaresSameEntity(X, Y))
14122 return nullptr;
14123 for (const Decl *DX : X->redecls()) {
14124 // If we reach Y before reaching the first decl, that means X is older.
14125 if (DX == Y)
14126 return X;
14127 // If we reach the first decl, then Y is older.
14128 if (DX->isFirstDecl())
14129 return Y;
14130 }
14131 llvm_unreachable("Corrupt redecls chain");
14132}
14133
14134template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14135static T *getCommonDecl(T *X, T *Y) {
14136 return cast_or_null<T>(
14137 getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
14138 const_cast<Decl *>(cast_or_null<Decl>(Y))));
14139}
14140
14141template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
14142static T *getCommonDeclChecked(T *X, T *Y) {
14143 return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
14144 const_cast<Decl *>(cast<Decl>(Y))));
14145}
14146
14148 TemplateName Y,
14149 bool IgnoreDeduced = false) {
14150 if (X.getAsVoidPointer() == Y.getAsVoidPointer())
14151 return X;
14152 // FIXME: There are cases here where we could find a common template name
14153 // with more sugar. For example one could be a SubstTemplateTemplate*
14154 // replacing the other.
14155 TemplateName CX = Ctx.getCanonicalTemplateName(X, IgnoreDeduced);
14156 if (CX.getAsVoidPointer() !=
14158 return TemplateName();
14159 return CX;
14160}
14161
14164 bool IgnoreDeduced) {
14165 TemplateName R = getCommonTemplateName(Ctx, X, Y, IgnoreDeduced);
14166 assert(R.getAsVoidPointer() != nullptr);
14167 return R;
14168}
14169
14171 ArrayRef<QualType> Ys, bool Unqualified = false) {
14172 assert(Xs.size() == Ys.size());
14173 SmallVector<QualType, 8> Rs(Xs.size());
14174 for (size_t I = 0; I < Rs.size(); ++I)
14175 Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
14176 return Rs;
14177}
14178
14179template <class T>
14180static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
14181 return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
14182 : SourceLocation();
14183}
14184
14186 const TemplateArgument &X,
14187 const TemplateArgument &Y) {
14188 if (X.getKind() != Y.getKind())
14189 return TemplateArgument();
14190
14191 switch (X.getKind()) {
14193 if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
14194 return TemplateArgument();
14195 return TemplateArgument(
14196 Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
14198 if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
14199 return TemplateArgument();
14200 return TemplateArgument(
14201 Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
14202 /*Unqualified=*/true);
14204 if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
14205 return TemplateArgument();
14206 // FIXME: Try to keep the common sugar.
14207 return X;
14209 TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
14210 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14211 if (!CTN.getAsVoidPointer())
14212 return TemplateArgument();
14213 return TemplateArgument(CTN);
14214 }
14216 TemplateName TX = X.getAsTemplateOrTemplatePattern(),
14218 TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
14219 if (!CTN.getAsVoidPointer())
14220 return TemplateName();
14221 auto NExpX = X.getNumTemplateExpansions();
14222 assert(NExpX == Y.getNumTemplateExpansions());
14223 return TemplateArgument(CTN, NExpX);
14224 }
14225 default:
14226 // FIXME: Handle the other argument kinds.
14227 return X;
14228 }
14229}
14230
14235 if (Xs.size() != Ys.size())
14236 return true;
14237 R.resize(Xs.size());
14238 for (size_t I = 0; I < R.size(); ++I) {
14239 R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
14240 if (R[I].isNull())
14241 return true;
14242 }
14243 return false;
14244}
14245
14250 bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
14251 assert(!Different);
14252 (void)Different;
14253 return R;
14254}
14255
14256template <class T>
14258 bool IsSame) {
14259 ElaboratedTypeKeyword KX = X->getKeyword(), KY = Y->getKeyword();
14260 if (KX == KY)
14261 return KX;
14263 assert(!IsSame || KX == getCanonicalElaboratedTypeKeyword(KY));
14264 return KX;
14265}
14266
14267/// Returns a NestedNameSpecifier which has only the common sugar
14268/// present in both NNS1 and NNS2.
14271 NestedNameSpecifier NNS2, bool IsSame) {
14272 // If they are identical, all sugar is common.
14273 if (NNS1 == NNS2)
14274 return NNS1;
14275
14276 // IsSame implies both Qualifiers are equivalent.
14277 NestedNameSpecifier Canon = NNS1.getCanonical();
14278 if (Canon != NNS2.getCanonical()) {
14279 assert(!IsSame && "Should be the same NestedNameSpecifier");
14280 // If they are not the same, there is nothing to unify.
14281 return std::nullopt;
14282 }
14283
14284 NestedNameSpecifier R = std::nullopt;
14285 NestedNameSpecifier::Kind Kind = NNS1.getKind();
14286 assert(Kind == NNS2.getKind());
14287 switch (Kind) {
14289 auto [Namespace1, Prefix1] = NNS1.getAsNamespaceAndPrefix();
14290 auto [Namespace2, Prefix2] = NNS2.getAsNamespaceAndPrefix();
14291 auto Kind = Namespace1->getKind();
14292 if (Kind != Namespace2->getKind() ||
14293 (Kind == Decl::NamespaceAlias &&
14294 !declaresSameEntity(Namespace1, Namespace2))) {
14296 Ctx,
14297 ::getCommonDeclChecked(Namespace1->getNamespace(),
14298 Namespace2->getNamespace()),
14299 /*Prefix=*/std::nullopt);
14300 break;
14301 }
14302 // The prefixes for namespaces are not significant, its declaration
14303 // identifies it uniquely.
14304 NestedNameSpecifier Prefix = ::getCommonNNS(Ctx, Prefix1, Prefix2,
14305 /*IsSame=*/false);
14306 R = NestedNameSpecifier(Ctx, ::getCommonDeclChecked(Namespace1, Namespace2),
14307 Prefix);
14308 break;
14309 }
14311 const Type *T1 = NNS1.getAsType(), *T2 = NNS2.getAsType();
14312 const Type *T = Ctx.getCommonSugaredType(QualType(T1, 0), QualType(T2, 0),
14313 /*Unqualified=*/true)
14314 .getTypePtr();
14316 break;
14317 }
14319 // FIXME: Can __super even be used with data members?
14320 // If it's only usable in functions, we will never see it here,
14321 // unless we save the qualifiers used in function types.
14322 // In that case, it might be possible NNS2 is a type,
14323 // in which case we should degrade the result to
14324 // a CXXRecordType.
14326 NNS2.getAsMicrosoftSuper()));
14327 break;
14328 }
14331 // These are singletons.
14332 llvm_unreachable("singletons did not compare equal");
14333 }
14334 assert(R.getCanonical() == Canon);
14335 return R;
14336}
14337
14338template <class T>
14340 const T *Y, bool IsSame) {
14341 return ::getCommonNNS(Ctx, X->getQualifier(), Y->getQualifier(), IsSame);
14342}
14343
14344template <class T>
14345static QualType getCommonElementType(const ASTContext &Ctx, const T *X,
14346 const T *Y) {
14347 return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
14348}
14349
14351 QualType X, QualType Y,
14352 Qualifiers &QX,
14353 Qualifiers &QY) {
14354 QualType R = Ctx.getCommonSugaredType(X, Y,
14355 /*Unqualified=*/true);
14356 // Qualifiers common to both element types.
14357 Qualifiers RQ = R.getQualifiers();
14358 // For each side, move to the top level any qualifiers which are not common to
14359 // both element types. The caller must assume top level qualifiers might
14360 // be different, even if they are the same type, and can be treated as sugar.
14361 QX += X.getQualifiers() - RQ;
14362 QY += Y.getQualifiers() - RQ;
14363 return R;
14364}
14365
14366template <class T>
14368 Qualifiers &QX, const T *Y,
14369 Qualifiers &QY) {
14370 return getCommonTypeWithQualifierLifting(Ctx, X->getElementType(),
14371 Y->getElementType(), QX, QY);
14372}
14373
14374template <class T>
14375static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X,
14376 const T *Y) {
14377 return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
14378}
14379
14380template <class T>
14381static auto *getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y) {
14382 assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
14383 return X->getSizeExpr();
14384}
14385
14386static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
14387 assert(X->getSizeModifier() == Y->getSizeModifier());
14388 return X->getSizeModifier();
14389}
14390
14392 const ArrayType *Y) {
14393 assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
14394 return X->getIndexTypeCVRQualifiers();
14395}
14396
14397// Merges two type lists such that the resulting vector will contain
14398// each type (in a canonical sense) only once, in the order they appear
14399// from X to Y. If they occur in both X and Y, the result will contain
14400// the common sugared type between them.
14401static void mergeTypeLists(const ASTContext &Ctx,
14404 llvm::DenseMap<QualType, unsigned> Found;
14405 for (auto Ts : {X, Y}) {
14406 for (QualType T : Ts) {
14407 auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
14408 if (!Res.second) {
14409 QualType &U = Out[Res.first->second];
14410 U = Ctx.getCommonSugaredType(U, T);
14411 } else {
14412 Out.emplace_back(T);
14413 }
14414 }
14415 }
14416}
14417
14418FunctionProtoType::ExceptionSpecInfo
14421 SmallVectorImpl<QualType> &ExceptionTypeStorage,
14422 bool AcceptDependent) const {
14423 ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
14424
14425 // If either of them can throw anything, that is the result.
14426 for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
14427 if (EST1 == I)
14428 return ESI1;
14429 if (EST2 == I)
14430 return ESI2;
14431 }
14432
14433 // If either of them is non-throwing, the result is the other.
14434 for (auto I :
14436 if (EST1 == I)
14437 return ESI2;
14438 if (EST2 == I)
14439 return ESI1;
14440 }
14441
14442 // If we're left with value-dependent computed noexcept expressions, we're
14443 // stuck. Before C++17, we can just drop the exception specification entirely,
14444 // since it's not actually part of the canonical type. And this should never
14445 // happen in C++17, because it would mean we were computing the composite
14446 // pointer type of dependent types, which should never happen.
14447 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
14448 assert(AcceptDependent &&
14449 "computing composite pointer type of dependent types");
14451 }
14452
14453 // Switch over the possibilities so that people adding new values know to
14454 // update this function.
14455 switch (EST1) {
14456 case EST_None:
14457 case EST_DynamicNone:
14458 case EST_MSAny:
14459 case EST_BasicNoexcept:
14461 case EST_NoexceptFalse:
14462 case EST_NoexceptTrue:
14463 case EST_NoThrow:
14464 llvm_unreachable("These ESTs should be handled above");
14465
14466 case EST_Dynamic: {
14467 // This is the fun case: both exception specifications are dynamic. Form
14468 // the union of the two lists.
14469 assert(EST2 == EST_Dynamic && "other cases should already be handled");
14470 mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
14471 ESI2.Exceptions);
14473 Result.Exceptions = ExceptionTypeStorage;
14474 return Result;
14475 }
14476
14477 case EST_Unevaluated:
14478 case EST_Uninstantiated:
14479 case EST_Unparsed:
14480 llvm_unreachable("shouldn't see unresolved exception specifications here");
14481 }
14482
14483 llvm_unreachable("invalid ExceptionSpecificationType");
14484}
14485
14487 Qualifiers &QX, const Type *Y,
14488 Qualifiers &QY) {
14489 Type::TypeClass TC = X->getTypeClass();
14490 assert(TC == Y->getTypeClass());
14491 switch (TC) {
14492#define UNEXPECTED_TYPE(Class, Kind) \
14493 case Type::Class: \
14494 llvm_unreachable("Unexpected " Kind ": " #Class);
14495
14496#define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
14497#define TYPE(Class, Base)
14498#include "clang/AST/TypeNodes.inc"
14499
14500#define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
14502 SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
14503 SUGAR_FREE_TYPE(DependentBitInt)
14505 SUGAR_FREE_TYPE(ObjCInterface)
14506 SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
14507 SUGAR_FREE_TYPE(SubstBuiltinTemplatePack)
14508 SUGAR_FREE_TYPE(UnresolvedUsing)
14509 SUGAR_FREE_TYPE(HLSLAttributedResource)
14510 SUGAR_FREE_TYPE(HLSLInlineSpirv)
14511#undef SUGAR_FREE_TYPE
14512#define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
14513 NON_UNIQUE_TYPE(TypeOfExpr)
14514 NON_UNIQUE_TYPE(VariableArray)
14515#undef NON_UNIQUE_TYPE
14516
14517 UNEXPECTED_TYPE(TypeOf, "sugar")
14518
14519#undef UNEXPECTED_TYPE
14520
14521 case Type::Auto: {
14522 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14523 assert(AX->getDeducedKind() == AY->getDeducedKind());
14524 assert(AX->getDeducedKind() != DeducedKind::Deduced);
14525 assert(AX->getKeyword() == AY->getKeyword());
14526 TemplateDecl *CD =
14527 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14528 AY->getTypeConstraintConcept().getAsTemplateDecl());
14530 if (CD &&
14531 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14532 AY->getTypeConstraintArguments())) {
14533 CD = nullptr; // The arguments differ, so make it unconstrained.
14534 As.clear();
14535 }
14536 return Ctx.getAutoType(AX->getDeducedKind(), QualType(), AX->getKeyword(),
14537 TemplateName(CD), As);
14538 }
14539 case Type::IncompleteArray: {
14540 const auto *AX = cast<IncompleteArrayType>(X),
14542 return Ctx.getIncompleteArrayType(
14543 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14545 }
14546 case Type::DependentSizedArray: {
14547 const auto *AX = cast<DependentSizedArrayType>(X),
14549 return Ctx.getDependentSizedArrayType(
14550 getCommonArrayElementType(Ctx, AX, QX, AY, QY),
14551 getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
14553 }
14554 case Type::ConstantArray: {
14555 const auto *AX = cast<ConstantArrayType>(X),
14556 *AY = cast<ConstantArrayType>(Y);
14557 assert(AX->getSize() == AY->getSize());
14558 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14559 ? AX->getSizeExpr()
14560 : nullptr;
14561 return Ctx.getConstantArrayType(
14562 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14564 }
14565 case Type::ArrayParameter: {
14566 const auto *AX = cast<ArrayParameterType>(X),
14567 *AY = cast<ArrayParameterType>(Y);
14568 assert(AX->getSize() == AY->getSize());
14569 const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
14570 ? AX->getSizeExpr()
14571 : nullptr;
14572 auto ArrayTy = Ctx.getConstantArrayType(
14573 getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
14575 return Ctx.getArrayParameterType(ArrayTy);
14576 }
14577 case Type::Atomic: {
14578 const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
14579 return Ctx.getAtomicType(
14580 Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
14581 }
14582 case Type::Complex: {
14583 const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
14584 return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
14585 }
14586 case Type::Pointer: {
14587 const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
14588 return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
14589 }
14590 case Type::BlockPointer: {
14591 const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
14592 return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
14593 }
14594 case Type::ObjCObjectPointer: {
14595 const auto *PX = cast<ObjCObjectPointerType>(X),
14597 return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
14598 }
14599 case Type::MemberPointer: {
14600 const auto *PX = cast<MemberPointerType>(X),
14601 *PY = cast<MemberPointerType>(Y);
14602 assert(declaresSameEntity(PX->getMostRecentCXXRecordDecl(),
14603 PY->getMostRecentCXXRecordDecl()));
14604 return Ctx.getMemberPointerType(
14605 getCommonPointeeType(Ctx, PX, PY),
14606 getCommonQualifier(Ctx, PX, PY, /*IsSame=*/true),
14607 PX->getMostRecentCXXRecordDecl());
14608 }
14609 case Type::LValueReference: {
14610 const auto *PX = cast<LValueReferenceType>(X),
14612 // FIXME: Preserve PointeeTypeAsWritten.
14613 return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
14614 PX->isSpelledAsLValue() ||
14615 PY->isSpelledAsLValue());
14616 }
14617 case Type::RValueReference: {
14618 const auto *PX = cast<RValueReferenceType>(X),
14620 // FIXME: Preserve PointeeTypeAsWritten.
14621 return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
14622 }
14623 case Type::DependentAddressSpace: {
14624 const auto *PX = cast<DependentAddressSpaceType>(X),
14626 assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
14627 return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
14628 PX->getAddrSpaceExpr(),
14629 getCommonAttrLoc(PX, PY));
14630 }
14631 case Type::FunctionNoProto: {
14632 const auto *FX = cast<FunctionNoProtoType>(X),
14634 assert(FX->getExtInfo() == FY->getExtInfo());
14635 return Ctx.getFunctionNoProtoType(
14636 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
14637 FX->getExtInfo());
14638 }
14639 case Type::FunctionProto: {
14640 const auto *FX = cast<FunctionProtoType>(X),
14641 *FY = cast<FunctionProtoType>(Y);
14642 FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
14643 EPIY = FY->getExtProtoInfo();
14644 assert(EPIX.ExtInfo == EPIY.ExtInfo);
14645 assert(!EPIX.ExtParameterInfos == !EPIY.ExtParameterInfos);
14646 assert(!EPIX.ExtParameterInfos ||
14647 llvm::equal(
14648 llvm::ArrayRef(EPIX.ExtParameterInfos, FX->getNumParams()),
14649 llvm::ArrayRef(EPIY.ExtParameterInfos, FY->getNumParams())));
14650 assert(EPIX.RefQualifier == EPIY.RefQualifier);
14651 assert(EPIX.TypeQuals == EPIY.TypeQuals);
14652 assert(EPIX.Variadic == EPIY.Variadic);
14653
14654 // FIXME: Can we handle an empty EllipsisLoc?
14655 // Use emtpy EllipsisLoc if X and Y differ.
14656
14657 EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
14658
14659 QualType R =
14660 Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
14661 auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
14662 /*Unqualified=*/true);
14663
14664 SmallVector<QualType, 8> Exceptions;
14666 EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
14667 return Ctx.getFunctionType(R, P, EPIX);
14668 }
14669 case Type::ObjCObject: {
14670 const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
14671 assert(
14672 std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
14673 OY->getProtocols().begin(), OY->getProtocols().end(),
14674 [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
14675 return P0->getCanonicalDecl() == P1->getCanonicalDecl();
14676 }) &&
14677 "protocol lists must be the same");
14678 auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
14679 OY->getTypeArgsAsWritten());
14680 return Ctx.getObjCObjectType(
14681 Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
14682 OX->getProtocols(),
14683 OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
14684 }
14685 case Type::ConstantMatrix: {
14686 const auto *MX = cast<ConstantMatrixType>(X),
14687 *MY = cast<ConstantMatrixType>(Y);
14688 assert(MX->getNumRows() == MY->getNumRows());
14689 assert(MX->getNumColumns() == MY->getNumColumns());
14690 return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
14691 MX->getNumRows(), MX->getNumColumns());
14692 }
14693 case Type::DependentSizedMatrix: {
14694 const auto *MX = cast<DependentSizedMatrixType>(X),
14696 assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
14697 assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
14698 return Ctx.getDependentSizedMatrixType(
14699 getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
14700 MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
14701 }
14702 case Type::Vector: {
14703 const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
14704 assert(VX->getNumElements() == VY->getNumElements());
14705 assert(VX->getVectorKind() == VY->getVectorKind());
14706 return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
14707 VX->getNumElements(), VX->getVectorKind());
14708 }
14709 case Type::ExtVector: {
14710 const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
14711 assert(VX->getNumElements() == VY->getNumElements());
14712 return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
14713 VX->getNumElements());
14714 }
14715 case Type::DependentSizedExtVector: {
14716 const auto *VX = cast<DependentSizedExtVectorType>(X),
14719 getCommonSizeExpr(Ctx, VX, VY),
14720 getCommonAttrLoc(VX, VY));
14721 }
14722 case Type::DependentVector: {
14723 const auto *VX = cast<DependentVectorType>(X),
14725 assert(VX->getVectorKind() == VY->getVectorKind());
14726 return Ctx.getDependentVectorType(
14727 getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
14728 getCommonAttrLoc(VX, VY), VX->getVectorKind());
14729 }
14730 case Type::Enum:
14731 case Type::Record:
14732 case Type::InjectedClassName: {
14733 const auto *TX = cast<TagType>(X), *TY = cast<TagType>(Y);
14734 return Ctx.getTagType(::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14735 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false),
14736 ::getCommonDeclChecked(TX->getDecl(), TY->getDecl()),
14737 /*OwnedTag=*/false);
14738 }
14739 case Type::TemplateSpecialization: {
14740 const auto *TX = cast<TemplateSpecializationType>(X),
14742 auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
14743 TY->template_arguments());
14745 getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14746 ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
14747 TY->getTemplateName(),
14748 /*IgnoreDeduced=*/true),
14749 As, /*CanonicalArgs=*/{}, X->getCanonicalTypeInternal());
14750 }
14751 case Type::Decltype: {
14752 const auto *DX = cast<DecltypeType>(X);
14753 [[maybe_unused]] const auto *DY = cast<DecltypeType>(Y);
14754 assert(DX->isDependentType());
14755 assert(DY->isDependentType());
14756 assert(Ctx.hasSameExpr(DX->getUnderlyingExpr(), DY->getUnderlyingExpr()));
14757 // As Decltype is not uniqued, building a common type would be wasteful.
14758 return QualType(DX, 0);
14759 }
14760 case Type::PackIndexing: {
14761 const auto *DX = cast<PackIndexingType>(X);
14762 [[maybe_unused]] const auto *DY = cast<PackIndexingType>(Y);
14763 assert(DX->isDependentType());
14764 assert(DY->isDependentType());
14765 assert(Ctx.hasSameExpr(DX->getIndexExpr(), DY->getIndexExpr()));
14766 return QualType(DX, 0);
14767 }
14768 case Type::DependentName: {
14769 const auto *NX = cast<DependentNameType>(X),
14770 *NY = cast<DependentNameType>(Y);
14771 assert(NX->getIdentifier() == NY->getIdentifier());
14772 return Ctx.getDependentNameType(
14773 getCommonTypeKeyword(NX, NY, /*IsSame=*/true),
14774 getCommonQualifier(Ctx, NX, NY, /*IsSame=*/true), NX->getIdentifier());
14775 }
14776 case Type::OverflowBehavior: {
14777 const auto *NX = cast<OverflowBehaviorType>(X),
14779 assert(NX->getBehaviorKind() == NY->getBehaviorKind());
14780 return Ctx.getOverflowBehaviorType(
14781 NX->getBehaviorKind(),
14782 getCommonTypeWithQualifierLifting(Ctx, NX->getUnderlyingType(),
14783 NY->getUnderlyingType(), QX, QY));
14784 }
14785 case Type::UnaryTransform: {
14786 const auto *TX = cast<UnaryTransformType>(X),
14787 *TY = cast<UnaryTransformType>(Y);
14788 assert(TX->getUTTKind() == TY->getUTTKind());
14789 return Ctx.getUnaryTransformType(
14790 Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
14791 Ctx.getCommonSugaredType(TX->getUnderlyingType(),
14792 TY->getUnderlyingType()),
14793 TX->getUTTKind());
14794 }
14795 case Type::PackExpansion: {
14796 const auto *PX = cast<PackExpansionType>(X),
14797 *PY = cast<PackExpansionType>(Y);
14798 assert(PX->getNumExpansions() == PY->getNumExpansions());
14799 return Ctx.getPackExpansionType(
14800 Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
14801 PX->getNumExpansions(), false);
14802 }
14803 case Type::Pipe: {
14804 const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
14805 assert(PX->isReadOnly() == PY->isReadOnly());
14806 auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
14808 return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
14809 }
14810 case Type::TemplateTypeParm: {
14811 const auto *TX = cast<TemplateTypeParmType>(X),
14813 assert(TX->getDepth() == TY->getDepth());
14814 assert(TX->getIndex() == TY->getIndex());
14815 assert(TX->isParameterPack() == TY->isParameterPack());
14816 return Ctx.getTemplateTypeParmType(
14817 TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
14818 getCommonDecl(TX->getDecl(), TY->getDecl()));
14819 }
14820 }
14821 llvm_unreachable("Unknown Type Class");
14822}
14823
14825 const Type *Y,
14826 SplitQualType Underlying) {
14827 Type::TypeClass TC = X->getTypeClass();
14828 if (TC != Y->getTypeClass())
14829 return QualType();
14830 switch (TC) {
14831#define UNEXPECTED_TYPE(Class, Kind) \
14832 case Type::Class: \
14833 llvm_unreachable("Unexpected " Kind ": " #Class);
14834#define TYPE(Class, Base)
14835#define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
14836#include "clang/AST/TypeNodes.inc"
14837
14838#define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
14841 CANONICAL_TYPE(BlockPointer)
14844 CANONICAL_TYPE(ConstantArray)
14845 CANONICAL_TYPE(ArrayParameter)
14846 CANONICAL_TYPE(ConstantMatrix)
14848 CANONICAL_TYPE(ExtVector)
14849 CANONICAL_TYPE(FunctionNoProto)
14850 CANONICAL_TYPE(FunctionProto)
14851 CANONICAL_TYPE(IncompleteArray)
14852 CANONICAL_TYPE(HLSLAttributedResource)
14853 CANONICAL_TYPE(HLSLInlineSpirv)
14854 CANONICAL_TYPE(LValueReference)
14855 CANONICAL_TYPE(ObjCInterface)
14856 CANONICAL_TYPE(ObjCObject)
14857 CANONICAL_TYPE(ObjCObjectPointer)
14858 CANONICAL_TYPE(OverflowBehavior)
14862 CANONICAL_TYPE(RValueReference)
14863 CANONICAL_TYPE(VariableArray)
14865#undef CANONICAL_TYPE
14866
14867#undef UNEXPECTED_TYPE
14868
14869 case Type::Adjusted: {
14870 const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
14871 QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
14872 if (!Ctx.hasSameType(OX, OY))
14873 return QualType();
14874 // FIXME: It's inefficient to have to unify the original types.
14875 return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
14876 Ctx.getQualifiedType(Underlying));
14877 }
14878 case Type::Decayed: {
14879 const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
14880 QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
14881 if (!Ctx.hasSameType(OX, OY))
14882 return QualType();
14883 // FIXME: It's inefficient to have to unify the original types.
14884 return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
14885 Ctx.getQualifiedType(Underlying));
14886 }
14887 case Type::Attributed: {
14888 const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
14889 AttributedType::Kind Kind = AX->getAttrKind();
14890 if (Kind != AY->getAttrKind())
14891 return QualType();
14892 QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
14893 if (!Ctx.hasSameType(MX, MY))
14894 return QualType();
14895 // FIXME: It's inefficient to have to unify the modified types.
14896 return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
14897 Ctx.getQualifiedType(Underlying),
14898 AX->getAttr());
14899 }
14900 case Type::BTFTagAttributed: {
14901 const auto *BX = cast<BTFTagAttributedType>(X);
14902 const BTFTypeTagAttr *AX = BX->getAttr();
14903 // The attribute is not uniqued, so just compare the tag.
14904 if (AX->getBTFTypeTag() !=
14905 cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
14906 return QualType();
14907 return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
14908 }
14909 case Type::Auto: {
14910 const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
14911 assert(AX->getDeducedKind() == DeducedKind::Deduced);
14912 assert(AY->getDeducedKind() == DeducedKind::Deduced);
14913
14914 AutoTypeKeyword KW = AX->getKeyword();
14915 if (KW != AY->getKeyword())
14916 return QualType();
14917
14918 TemplateDecl *CD =
14919 ::getCommonDecl(AX->getTypeConstraintConcept().getAsTemplateDecl(),
14920 AY->getTypeConstraintConcept().getAsTemplateDecl());
14922 if (CD &&
14923 getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
14924 AY->getTypeConstraintArguments())) {
14925 CD = nullptr; // The arguments differ, so make it unconstrained.
14926 As.clear();
14927 }
14928
14929 // Both auto types can't be dependent, otherwise they wouldn't have been
14930 // sugar. This implies they can't contain unexpanded packs either.
14932 Ctx.getQualifiedType(Underlying), AX->getKeyword(),
14933 TemplateName(CD), As);
14934 }
14935 case Type::PackIndexing:
14936 case Type::Decltype:
14937 return QualType();
14938 case Type::DeducedTemplateSpecialization:
14939 // FIXME: Try to merge these.
14940 return QualType();
14941 case Type::MacroQualified: {
14942 const auto *MX = cast<MacroQualifiedType>(X),
14943 *MY = cast<MacroQualifiedType>(Y);
14944 const IdentifierInfo *IX = MX->getMacroIdentifier();
14945 if (IX != MY->getMacroIdentifier())
14946 return QualType();
14947 return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
14948 }
14949 case Type::SubstTemplateTypeParm: {
14950 const auto *SX = cast<SubstTemplateTypeParmType>(X),
14952 Decl *CD =
14953 ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
14954 if (!CD)
14955 return QualType();
14956 unsigned Index = SX->getIndex();
14957 if (Index != SY->getIndex())
14958 return QualType();
14959 auto PackIndex = SX->getPackIndex();
14960 if (PackIndex != SY->getPackIndex())
14961 return QualType();
14962 return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
14963 CD, Index, PackIndex,
14964 SX->getFinal() && SY->getFinal());
14965 }
14966 case Type::ObjCTypeParam:
14967 // FIXME: Try to merge these.
14968 return QualType();
14969 case Type::Paren:
14970 return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
14971
14972 case Type::TemplateSpecialization: {
14973 const auto *TX = cast<TemplateSpecializationType>(X),
14975 TemplateName CTN =
14976 ::getCommonTemplateName(Ctx, TX->getTemplateName(),
14977 TY->getTemplateName(), /*IgnoreDeduced=*/true);
14978 if (!CTN.getAsVoidPointer())
14979 return QualType();
14981 if (getCommonTemplateArguments(Ctx, As, TX->template_arguments(),
14982 TY->template_arguments()))
14983 return QualType();
14985 getCommonTypeKeyword(TX, TY, /*IsSame=*/false), CTN, As,
14986 /*CanonicalArgs=*/{}, Ctx.getQualifiedType(Underlying));
14987 }
14988 case Type::Typedef: {
14989 const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
14990 const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
14991 if (!CD)
14992 return QualType();
14993 return Ctx.getTypedefType(
14994 ::getCommonTypeKeyword(TX, TY, /*IsSame=*/false),
14995 ::getCommonQualifier(Ctx, TX, TY, /*IsSame=*/false), CD,
14996 Ctx.getQualifiedType(Underlying));
14997 }
14998 case Type::TypeOf: {
14999 // The common sugar between two typeof expressions, where one is
15000 // potentially a typeof_unqual and the other is not, we unify to the
15001 // qualified type as that retains the most information along with the type.
15002 // We only return a typeof_unqual type when both types are unqual types.
15007 return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
15008 }
15009 case Type::TypeOfExpr:
15010 return QualType();
15011
15012 case Type::UnaryTransform: {
15013 const auto *UX = cast<UnaryTransformType>(X),
15014 *UY = cast<UnaryTransformType>(Y);
15015 UnaryTransformType::UTTKind KX = UX->getUTTKind();
15016 if (KX != UY->getUTTKind())
15017 return QualType();
15018 QualType BX = UX->getBaseType(), BY = UY->getBaseType();
15019 if (!Ctx.hasSameType(BX, BY))
15020 return QualType();
15021 // FIXME: It's inefficient to have to unify the base types.
15022 return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
15023 Ctx.getQualifiedType(Underlying), KX);
15024 }
15025 case Type::Using: {
15026 const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
15027 const UsingShadowDecl *CD = ::getCommonDecl(UX->getDecl(), UY->getDecl());
15028 if (!CD)
15029 return QualType();
15030 return Ctx.getUsingType(::getCommonTypeKeyword(UX, UY, /*IsSame=*/false),
15031 ::getCommonQualifier(Ctx, UX, UY, /*IsSame=*/false),
15032 CD, Ctx.getQualifiedType(Underlying));
15033 }
15034 case Type::MemberPointer: {
15035 const auto *PX = cast<MemberPointerType>(X),
15036 *PY = cast<MemberPointerType>(Y);
15037 CXXRecordDecl *Cls = PX->getMostRecentCXXRecordDecl();
15038 assert(Cls == PY->getMostRecentCXXRecordDecl());
15039 return Ctx.getMemberPointerType(
15040 ::getCommonPointeeType(Ctx, PX, PY),
15041 ::getCommonQualifier(Ctx, PX, PY, /*IsSame=*/false), Cls);
15042 }
15043 case Type::CountAttributed: {
15044 const auto *DX = cast<CountAttributedType>(X),
15046 if (DX->isCountInBytes() != DY->isCountInBytes())
15047 return QualType();
15048 if (DX->isOrNull() != DY->isOrNull())
15049 return QualType();
15050 Expr *CEX = DX->getCountExpr();
15051 Expr *CEY = DY->getCountExpr();
15052 ArrayRef<clang::TypeCoupledDeclRefInfo> CDX = DX->getCoupledDecls();
15053 if (Ctx.hasSameExpr(CEX, CEY))
15054 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15055 DX->isCountInBytes(), DX->isOrNull(),
15056 CDX);
15057 if (!CEX->isIntegerConstantExpr(Ctx) || !CEY->isIntegerConstantExpr(Ctx))
15058 return QualType();
15059 // Two declarations with the same integer constant may still differ in their
15060 // expression pointers, so we need to evaluate them.
15061 llvm::APSInt VX = *CEX->getIntegerConstantExpr(Ctx);
15062 llvm::APSInt VY = *CEY->getIntegerConstantExpr(Ctx);
15063 if (VX != VY)
15064 return QualType();
15065 return Ctx.getCountAttributedType(Ctx.getQualifiedType(Underlying), CEX,
15066 DX->isCountInBytes(), DX->isOrNull(),
15067 CDX);
15068 }
15069
15070 case Type::LateParsedAttr:
15071 return QualType();
15072
15073 case Type::PredefinedSugar:
15074 assert(cast<PredefinedSugarType>(X)->getKind() !=
15076 return QualType();
15077 }
15078 llvm_unreachable("Unhandled Type Class");
15079}
15080
15081static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
15083 while (true) {
15084 QTotal.addConsistentQualifiers(T.Quals);
15085 QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
15086 if (NT == QualType(T.Ty, 0))
15087 break;
15088 R.push_back(T);
15089 T = NT.split();
15090 }
15091 return R;
15092}
15093
15095 bool Unqualified) const {
15096 assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
15097 if (X == Y)
15098 return X;
15099 if (!Unqualified) {
15100 if (X.isCanonical())
15101 return X;
15102 if (Y.isCanonical())
15103 return Y;
15104 }
15105
15106 SplitQualType SX = X.split(), SY = Y.split();
15107 Qualifiers QX, QY;
15108 // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
15109 // until we reach their underlying "canonical nodes". Note these are not
15110 // necessarily canonical types, as they may still have sugared properties.
15111 // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
15112 auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
15113
15114 // If this is an ArrayType, the element qualifiers are interchangeable with
15115 // the top level qualifiers.
15116 // * In case the canonical nodes are the same, the elements types are already
15117 // the same.
15118 // * Otherwise, the element types will be made the same, and any different
15119 // element qualifiers will be moved up to the top level qualifiers, per
15120 // 'getCommonArrayElementType'.
15121 // In both cases, this means there may be top level qualifiers which differ
15122 // between X and Y. If so, these differing qualifiers are redundant with the
15123 // element qualifiers, and can be removed without changing the canonical type.
15124 // The desired behaviour is the same as for the 'Unqualified' case here:
15125 // treat the redundant qualifiers as sugar, remove the ones which are not
15126 // common to both sides.
15127 bool KeepCommonQualifiers =
15129
15130 if (SX.Ty != SY.Ty) {
15131 // The canonical nodes differ. Build a common canonical node out of the two,
15132 // unifying their sugar. This may recurse back here.
15133 SX.Ty =
15134 ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
15135 } else {
15136 // The canonical nodes were identical: We may have desugared too much.
15137 // Add any common sugar back in.
15138 while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
15139 QX -= SX.Quals;
15140 QY -= SY.Quals;
15141 SX = Xs.pop_back_val();
15142 SY = Ys.pop_back_val();
15143 }
15144 }
15145 if (KeepCommonQualifiers)
15147 else
15148 assert(QX == QY);
15149
15150 // Even though the remaining sugar nodes in Xs and Ys differ, some may be
15151 // related. Walk up these nodes, unifying them and adding the result.
15152 while (!Xs.empty() && !Ys.empty()) {
15153 auto Underlying = SplitQualType(
15154 SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
15155 SX = Xs.pop_back_val();
15156 SY = Ys.pop_back_val();
15157 SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
15159 // Stop at the first pair which is unrelated.
15160 if (!SX.Ty) {
15161 SX.Ty = Underlying.Ty;
15162 break;
15163 }
15164 QX -= Underlying.Quals;
15165 };
15166
15167 // Add back the missing accumulated qualifiers, which were stripped off
15168 // with the sugar nodes we could not unify.
15169 QualType R = getQualifiedType(SX.Ty, QX);
15170 assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
15171 return R;
15172}
15173
15175 assert(Ty->isFixedPointType());
15176
15178 return Ty;
15179
15180 switch (Ty->castAs<BuiltinType>()->getKind()) {
15181 default:
15182 llvm_unreachable("Not a saturated fixed point type!");
15183 case BuiltinType::SatShortAccum:
15184 return ShortAccumTy;
15185 case BuiltinType::SatAccum:
15186 return AccumTy;
15187 case BuiltinType::SatLongAccum:
15188 return LongAccumTy;
15189 case BuiltinType::SatUShortAccum:
15190 return UnsignedShortAccumTy;
15191 case BuiltinType::SatUAccum:
15192 return UnsignedAccumTy;
15193 case BuiltinType::SatULongAccum:
15194 return UnsignedLongAccumTy;
15195 case BuiltinType::SatShortFract:
15196 return ShortFractTy;
15197 case BuiltinType::SatFract:
15198 return FractTy;
15199 case BuiltinType::SatLongFract:
15200 return LongFractTy;
15201 case BuiltinType::SatUShortFract:
15202 return UnsignedShortFractTy;
15203 case BuiltinType::SatUFract:
15204 return UnsignedFractTy;
15205 case BuiltinType::SatULongFract:
15206 return UnsignedLongFractTy;
15207 }
15208}
15209
15211 assert(Ty->isFixedPointType());
15212
15213 if (Ty->isSaturatedFixedPointType()) return Ty;
15214
15215 switch (Ty->castAs<BuiltinType>()->getKind()) {
15216 default:
15217 llvm_unreachable("Not a fixed point type!");
15218 case BuiltinType::ShortAccum:
15219 return SatShortAccumTy;
15220 case BuiltinType::Accum:
15221 return SatAccumTy;
15222 case BuiltinType::LongAccum:
15223 return SatLongAccumTy;
15224 case BuiltinType::UShortAccum:
15226 case BuiltinType::UAccum:
15227 return SatUnsignedAccumTy;
15228 case BuiltinType::ULongAccum:
15230 case BuiltinType::ShortFract:
15231 return SatShortFractTy;
15232 case BuiltinType::Fract:
15233 return SatFractTy;
15234 case BuiltinType::LongFract:
15235 return SatLongFractTy;
15236 case BuiltinType::UShortFract:
15238 case BuiltinType::UFract:
15239 return SatUnsignedFractTy;
15240 case BuiltinType::ULongFract:
15242 }
15243}
15244
15246 if (LangOpts.OpenCL)
15248
15249 if (LangOpts.CUDA)
15251
15252 return getLangASFromTargetAS(AS);
15253}
15254
15256 assert(Ty->isFixedPointType());
15257
15258 const TargetInfo &Target = getTargetInfo();
15259 switch (Ty->castAs<BuiltinType>()->getKind()) {
15260 default:
15261 llvm_unreachable("Not a fixed point type!");
15262 case BuiltinType::ShortAccum:
15263 case BuiltinType::SatShortAccum:
15264 return Target.getShortAccumScale();
15265 case BuiltinType::Accum:
15266 case BuiltinType::SatAccum:
15267 return Target.getAccumScale();
15268 case BuiltinType::LongAccum:
15269 case BuiltinType::SatLongAccum:
15270 return Target.getLongAccumScale();
15271 case BuiltinType::UShortAccum:
15272 case BuiltinType::SatUShortAccum:
15273 return Target.getUnsignedShortAccumScale();
15274 case BuiltinType::UAccum:
15275 case BuiltinType::SatUAccum:
15276 return Target.getUnsignedAccumScale();
15277 case BuiltinType::ULongAccum:
15278 case BuiltinType::SatULongAccum:
15279 return Target.getUnsignedLongAccumScale();
15280 case BuiltinType::ShortFract:
15281 case BuiltinType::SatShortFract:
15282 return Target.getShortFractScale();
15283 case BuiltinType::Fract:
15284 case BuiltinType::SatFract:
15285 return Target.getFractScale();
15286 case BuiltinType::LongFract:
15287 case BuiltinType::SatLongFract:
15288 return Target.getLongFractScale();
15289 case BuiltinType::UShortFract:
15290 case BuiltinType::SatUShortFract:
15291 return Target.getUnsignedShortFractScale();
15292 case BuiltinType::UFract:
15293 case BuiltinType::SatUFract:
15294 return Target.getUnsignedFractScale();
15295 case BuiltinType::ULongFract:
15296 case BuiltinType::SatULongFract:
15297 return Target.getUnsignedLongFractScale();
15298 }
15299}
15300
15302 assert(Ty->isFixedPointType());
15303
15304 const TargetInfo &Target = getTargetInfo();
15305 switch (Ty->castAs<BuiltinType>()->getKind()) {
15306 default:
15307 llvm_unreachable("Not a fixed point type!");
15308 case BuiltinType::ShortAccum:
15309 case BuiltinType::SatShortAccum:
15310 return Target.getShortAccumIBits();
15311 case BuiltinType::Accum:
15312 case BuiltinType::SatAccum:
15313 return Target.getAccumIBits();
15314 case BuiltinType::LongAccum:
15315 case BuiltinType::SatLongAccum:
15316 return Target.getLongAccumIBits();
15317 case BuiltinType::UShortAccum:
15318 case BuiltinType::SatUShortAccum:
15319 return Target.getUnsignedShortAccumIBits();
15320 case BuiltinType::UAccum:
15321 case BuiltinType::SatUAccum:
15322 return Target.getUnsignedAccumIBits();
15323 case BuiltinType::ULongAccum:
15324 case BuiltinType::SatULongAccum:
15325 return Target.getUnsignedLongAccumIBits();
15326 case BuiltinType::ShortFract:
15327 case BuiltinType::SatShortFract:
15328 case BuiltinType::Fract:
15329 case BuiltinType::SatFract:
15330 case BuiltinType::LongFract:
15331 case BuiltinType::SatLongFract:
15332 case BuiltinType::UShortFract:
15333 case BuiltinType::SatUShortFract:
15334 case BuiltinType::UFract:
15335 case BuiltinType::SatUFract:
15336 case BuiltinType::ULongFract:
15337 case BuiltinType::SatULongFract:
15338 return 0;
15339 }
15340}
15341
15342llvm::FixedPointSemantics
15344 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
15345 "Can only get the fixed point semantics for a "
15346 "fixed point or integer type.");
15347 if (Ty->isIntegerType())
15348 return llvm::FixedPointSemantics::GetIntegerSemantics(
15349 getIntWidth(Ty), Ty->isSignedIntegerType());
15350
15351 bool isSigned = Ty->isSignedFixedPointType();
15352 return llvm::FixedPointSemantics(
15353 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
15355 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
15356}
15357
15358llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
15359 assert(Ty->isFixedPointType());
15360 return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
15361}
15362
15363llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
15364 assert(Ty->isFixedPointType());
15365 return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
15366}
15367
15369 assert(Ty->isUnsignedFixedPointType() &&
15370 "Expected unsigned fixed point type");
15371
15372 switch (Ty->castAs<BuiltinType>()->getKind()) {
15373 case BuiltinType::UShortAccum:
15374 return ShortAccumTy;
15375 case BuiltinType::UAccum:
15376 return AccumTy;
15377 case BuiltinType::ULongAccum:
15378 return LongAccumTy;
15379 case BuiltinType::SatUShortAccum:
15380 return SatShortAccumTy;
15381 case BuiltinType::SatUAccum:
15382 return SatAccumTy;
15383 case BuiltinType::SatULongAccum:
15384 return SatLongAccumTy;
15385 case BuiltinType::UShortFract:
15386 return ShortFractTy;
15387 case BuiltinType::UFract:
15388 return FractTy;
15389 case BuiltinType::ULongFract:
15390 return LongFractTy;
15391 case BuiltinType::SatUShortFract:
15392 return SatShortFractTy;
15393 case BuiltinType::SatUFract:
15394 return SatFractTy;
15395 case BuiltinType::SatULongFract:
15396 return SatLongFractTy;
15397 default:
15398 llvm_unreachable("Unexpected unsigned fixed point type");
15399 }
15400}
15401
15402// Given a list of FMV features, return a concatenated list of the
15403// corresponding backend features (which may contain duplicates).
15404static std::vector<std::string> getFMVBackendFeaturesFor(
15405 const llvm::SmallVectorImpl<StringRef> &FMVFeatStrings) {
15406 std::vector<std::string> BackendFeats;
15407 llvm::AArch64::ExtensionSet FeatureBits;
15408 for (StringRef F : FMVFeatStrings)
15409 if (auto FMVExt = llvm::AArch64::parseFMVExtension(F))
15410 if (FMVExt->ID)
15411 FeatureBits.enable(*FMVExt->ID);
15412 FeatureBits.toLLVMFeatureList(BackendFeats);
15413 return BackendFeats;
15414}
15415
15416ParsedTargetAttr
15417ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
15418 assert(TD != nullptr);
15419 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
15420
15421 llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
15422 return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
15423 });
15424 return ParsedAttr;
15425}
15426
15427void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15428 const FunctionDecl *FD) const {
15429 if (FD)
15430 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
15431 else
15432 Target->initFeatureMap(FeatureMap, getDiagnostics(),
15433 Target->getTargetOpts().CPU,
15434 Target->getTargetOpts().Features);
15435}
15436
15437// Fills in the supplied string map with the set of target features for the
15438// passed in function.
15439void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
15440 GlobalDecl GD) const {
15441 StringRef TargetCPU = Target->getTargetOpts().CPU;
15442 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
15443 if (const auto *TD = FD->getAttr<TargetAttr>()) {
15445
15446 // Make a copy of the features as passed on the command line into the
15447 // beginning of the additional features from the function to override.
15448 // AArch64 handles command line option features in parseTargetAttr().
15449 if (!Target->getTriple().isAArch64())
15450 ParsedAttr.Features.insert(
15451 ParsedAttr.Features.begin(),
15452 Target->getTargetOpts().FeaturesAsWritten.begin(),
15453 Target->getTargetOpts().FeaturesAsWritten.end());
15454
15455 if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
15456 TargetCPU = ParsedAttr.CPU;
15457
15458 // Now populate the feature map, first with the TargetCPU which is either
15459 // the default or a new one from the target attribute string. Then we'll use
15460 // the passed in features (FeaturesAsWritten) along with the new ones from
15461 // the attribute.
15462 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
15463 ParsedAttr.Features);
15464 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
15466 Target->getCPUSpecificCPUDispatchFeatures(
15467 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
15468 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
15469 Features.insert(Features.begin(),
15470 Target->getTargetOpts().FeaturesAsWritten.begin(),
15471 Target->getTargetOpts().FeaturesAsWritten.end());
15472 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15473 } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
15474 if (Target->getTriple().isAArch64()) {
15476 TC->getFeatures(Feats, GD.getMultiVersionIndex());
15477 std::vector<std::string> Features = getFMVBackendFeaturesFor(Feats);
15478 Features.insert(Features.begin(),
15479 Target->getTargetOpts().FeaturesAsWritten.begin(),
15480 Target->getTargetOpts().FeaturesAsWritten.end());
15481 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15482 } else if (Target->getTriple().isRISCV()) {
15483 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15484 std::vector<std::string> Features;
15485 if (VersionStr != "default") {
15486 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(VersionStr);
15487 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15488 ParsedAttr.Features.end());
15489 }
15490 Features.insert(Features.begin(),
15491 Target->getTargetOpts().FeaturesAsWritten.begin(),
15492 Target->getTargetOpts().FeaturesAsWritten.end());
15493 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15494 } else if (Target->getTriple().isOSAIX()) {
15495 std::vector<std::string> Features;
15496 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15497 if (VersionStr.starts_with("cpu="))
15498 TargetCPU = VersionStr.drop_front(sizeof("cpu=") - 1);
15499 else if (VersionStr != "default")
15500 Features = Target->parseTargetAttr(VersionStr).Features;
15501 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15502 } else {
15503 std::vector<std::string> Features;
15504 StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
15505 if (VersionStr.starts_with("arch="))
15506 TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
15507 else if (VersionStr != "default")
15508 Features.push_back((StringRef{"+"} + VersionStr).str());
15509 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15510 }
15511 } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
15512 std::vector<std::string> Features;
15513 if (Target->getTriple().isRISCV()) {
15514 ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TV->getName());
15515 Features.insert(Features.begin(), ParsedAttr.Features.begin(),
15516 ParsedAttr.Features.end());
15517 } else {
15518 assert(Target->getTriple().isAArch64());
15520 TV->getFeatures(Feats);
15521 Features = getFMVBackendFeaturesFor(Feats);
15522 }
15523 Features.insert(Features.begin(),
15524 Target->getTargetOpts().FeaturesAsWritten.begin(),
15525 Target->getTargetOpts().FeaturesAsWritten.end());
15526 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
15527 } else {
15528 FeatureMap = Target->getTargetOpts().FeatureMap;
15529 }
15530}
15531
15533 CanQualType KernelNameType,
15534 const FunctionDecl *FD) {
15535 // Host and device compilation may use different ABIs and different ABIs
15536 // may allocate name mangling discriminators differently. A discriminator
15537 // override is used to ensure consistent discriminator allocation across
15538 // host and device compilation.
15539 auto DeviceDiscriminatorOverrider =
15540 [](ASTContext &Ctx, const NamedDecl *ND) -> UnsignedOrNone {
15541 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
15542 if (RD->isLambda())
15543 return RD->getDeviceLambdaManglingNumber();
15544 return std::nullopt;
15545 };
15546 std::unique_ptr<MangleContext> MC{ItaniumMangleContext::create(
15547 Context, Context.getDiagnostics(), DeviceDiscriminatorOverrider)};
15548
15549 // Construct a mangled name for the SYCL kernel caller offload entry point.
15550 // FIXME: The Itanium typeinfo mangling (_ZTS<type>) is currently used to
15551 // name the SYCL kernel caller offload entry point function. This mangling
15552 // does not suffice to clearly identify symbols that correspond to SYCL
15553 // kernel caller functions, nor is this mangling natural for targets that
15554 // use a non-Itanium ABI.
15555 std::string Buffer;
15556 Buffer.reserve(128);
15557 llvm::raw_string_ostream Out(Buffer);
15558 MC->mangleCanonicalTypeName(KernelNameType, Out);
15559 std::string KernelName = Out.str();
15560
15561 return {KernelNameType, FD, KernelName};
15562}
15563
15565 // If the function declaration to register is invalid or dependent, the
15566 // registration attempt is ignored.
15567 if (FD->isInvalidDecl() || FD->isTemplated())
15568 return;
15569
15570 const auto *SKEPAttr = FD->getAttr<SYCLKernelEntryPointAttr>();
15571 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
15572
15573 // Be tolerant of multiple registration attempts so long as each attempt
15574 // is for the same entity. Callers are obligated to detect and diagnose
15575 // conflicting kernel names prior to calling this function.
15576 CanQualType KernelNameType = getCanonicalType(SKEPAttr->getKernelName());
15577 auto IT = SYCLKernels.find(KernelNameType);
15578 assert((IT == SYCLKernels.end() ||
15579 declaresSameEntity(FD, IT->second.getKernelEntryPointDecl())) &&
15580 "SYCL kernel name conflict");
15581 (void)IT;
15582 SYCLKernels.insert(std::make_pair(
15583 KernelNameType, BuildSYCLKernelInfo(*this, KernelNameType, FD)));
15584}
15585
15587 CanQualType KernelNameType = getCanonicalType(T);
15588 return SYCLKernels.at(KernelNameType);
15589}
15590
15592 CanQualType KernelNameType = getCanonicalType(T);
15593 auto IT = SYCLKernels.find(KernelNameType);
15594 if (IT != SYCLKernels.end())
15595 return &IT->second;
15596 return nullptr;
15597}
15598
15600 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
15601 return *OMPTraitInfoVector.back();
15602}
15603
15606 const ASTContext::SectionInfo &Section) {
15607 if (Section.Decl)
15608 return DB << Section.Decl;
15609 return DB << "a prior #pragma section";
15610}
15611
15612bool ASTContext::mayExternalize(const Decl *D) const {
15613 bool IsInternalVar =
15614 isa<VarDecl>(D) &&
15616 bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
15617 !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
15618 (D->hasAttr<CUDAConstantAttr>() &&
15619 !D->getAttr<CUDAConstantAttr>()->isImplicit());
15620 // CUDA/HIP: managed variables need to be externalized since it is
15621 // a declaration in IR, therefore cannot have internal linkage. Kernels in
15622 // anonymous name space needs to be externalized to avoid duplicate symbols.
15623 return (IsInternalVar &&
15624 (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
15625 (D->hasAttr<CUDAGlobalAttr>() &&
15627 GVA_Internal);
15628}
15629
15631 return mayExternalize(D) &&
15632 (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
15634}
15635
15636StringRef ASTContext::getCUIDHash() const {
15637 if (!CUIDHash.empty())
15638 return CUIDHash;
15639 if (LangOpts.CUID.empty())
15640 return StringRef();
15641 CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
15642 return CUIDHash;
15643}
15644
15645const CXXRecordDecl *
15647 assert(ThisClass);
15648 assert(ThisClass->isPolymorphic());
15649 const CXXRecordDecl *PrimaryBase = ThisClass;
15650 while (1) {
15651 assert(PrimaryBase);
15652 assert(PrimaryBase->isPolymorphic());
15653 auto &Layout = getASTRecordLayout(PrimaryBase);
15654 auto Base = Layout.getPrimaryBase();
15655 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
15656 break;
15657 PrimaryBase = Base;
15658 }
15659 return PrimaryBase;
15660}
15661
15663 StringRef MangledName) {
15664 auto *Method = cast<CXXMethodDecl>(VirtualMethodDecl.getDecl());
15665 assert(Method->isVirtual());
15666 bool DefaultIncludesPointerAuth =
15667 LangOpts.PointerAuthCalls || LangOpts.PointerAuthIntrinsics;
15668
15669 if (!DefaultIncludesPointerAuth)
15670 return true;
15671
15672 auto Existing = ThunksToBeAbbreviated.find(VirtualMethodDecl);
15673 if (Existing != ThunksToBeAbbreviated.end())
15674 return Existing->second.contains(MangledName.str());
15675
15676 std::unique_ptr<MangleContext> Mangler(createMangleContext());
15677 llvm::StringMap<llvm::SmallVector<std::string, 2>> Thunks;
15678 auto VtableContext = getVTableContext();
15679 if (const auto *ThunkInfos = VtableContext->getThunkInfo(VirtualMethodDecl)) {
15680 auto *Destructor = dyn_cast<CXXDestructorDecl>(Method);
15681 for (const auto &Thunk : *ThunkInfos) {
15682 SmallString<256> ElidedName;
15683 llvm::raw_svector_ostream ElidedNameStream(ElidedName);
15684 if (Destructor)
15685 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15686 Thunk, /* elideOverrideInfo */ true,
15687 ElidedNameStream);
15688 else
15689 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ true,
15690 ElidedNameStream);
15691 SmallString<256> MangledName;
15692 llvm::raw_svector_ostream mangledNameStream(MangledName);
15693 if (Destructor)
15694 Mangler->mangleCXXDtorThunk(Destructor, VirtualMethodDecl.getDtorType(),
15695 Thunk, /* elideOverrideInfo */ false,
15696 mangledNameStream);
15697 else
15698 Mangler->mangleThunk(Method, Thunk, /* elideOverrideInfo */ false,
15699 mangledNameStream);
15700
15701 Thunks[ElidedName].push_back(std::string(MangledName));
15702 }
15703 }
15704 llvm::StringSet<> SimplifiedThunkNames;
15705 for (auto &ThunkList : Thunks) {
15706 llvm::sort(ThunkList.second);
15707 SimplifiedThunkNames.insert(ThunkList.second[0]);
15708 }
15709 bool Result = SimplifiedThunkNames.contains(MangledName);
15710 ThunksToBeAbbreviated[VirtualMethodDecl] = std::move(SimplifiedThunkNames);
15711 return Result;
15712}
15713
15715 // Check for trivially-destructible here because non-trivially-destructible
15716 // types will always cause the type and any types derived from it to be
15717 // considered non-trivially-copyable. The same cannot be said for
15718 // trivially-copyable because deleting special members of a type derived from
15719 // a non-trivially-copyable type can cause the derived type to be considered
15720 // trivially copyable.
15721 if (getLangOpts().PointerFieldProtectionTagged)
15722 return !isa<CXXRecordDecl>(RD) ||
15723 cast<CXXRecordDecl>(RD)->hasTrivialDestructor();
15724 return true;
15725}
15726
15727static void findPFPFields(const ASTContext &Ctx, QualType Ty, CharUnits Offset,
15728 std::vector<PFPField> &Fields, bool IncludeVBases) {
15729 if (auto *AT = Ctx.getAsConstantArrayType(Ty)) {
15730 if (auto *ElemDecl = AT->getElementType()->getAsCXXRecordDecl()) {
15731 const ASTRecordLayout &ElemRL = Ctx.getASTRecordLayout(ElemDecl);
15732 for (unsigned i = 0; i != AT->getSize(); ++i)
15733 findPFPFields(Ctx, AT->getElementType(), Offset + i * ElemRL.getSize(),
15734 Fields, true);
15735 }
15736 }
15737 auto *Decl = Ty->getAsCXXRecordDecl();
15738 // isPFPType() is inherited from bases and members (including via arrays), so
15739 // we can early exit if it is false. Unions are excluded per the API
15740 // documentation.
15741 if (!Decl || !Decl->isPFPType() || Decl->isUnion())
15742 return;
15743 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Decl);
15744 for (FieldDecl *Field : Decl->fields()) {
15745 CharUnits FieldOffset =
15746 Offset +
15747 Ctx.toCharUnitsFromBits(RL.getFieldOffset(Field->getFieldIndex()));
15748 if (Ctx.isPFPField(Field))
15749 Fields.push_back({FieldOffset, Field});
15750 findPFPFields(Ctx, Field->getType(), FieldOffset, Fields,
15751 /*IncludeVBases=*/true);
15752 }
15753 // Pass false for IncludeVBases below because vbases are only included in
15754 // layout for top-level types, i.e. not bases or vbases.
15755 for (CXXBaseSpecifier &Base : Decl->bases()) {
15756 if (Base.isVirtual())
15757 continue;
15758 CharUnits BaseOffset =
15759 Offset + RL.getBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15760 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15761 /*IncludeVBases=*/false);
15762 }
15763 if (IncludeVBases) {
15764 for (CXXBaseSpecifier &Base : Decl->vbases()) {
15765 CharUnits BaseOffset =
15766 Offset + RL.getVBaseClassOffset(Base.getType()->getAsCXXRecordDecl());
15767 findPFPFields(Ctx, Base.getType(), BaseOffset, Fields,
15768 /*IncludeVBases=*/false);
15769 }
15770 }
15771}
15772
15773std::vector<PFPField> ASTContext::findPFPFields(QualType Ty) const {
15774 std::vector<PFPField> PFPFields;
15775 ::findPFPFields(*this, Ty, CharUnits::Zero(), PFPFields, true);
15776 return PFPFields;
15777}
15778
15780 return !findPFPFields(Ty).empty();
15781}
15782
15784 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getParent()))
15785 return RD->isPFPType() && FD->getType()->isPointerType() &&
15786 !FD->hasAttr<NoFieldProtectionAttr>();
15787 return false;
15788}
15789
15791 auto *FD = dyn_cast<FieldDecl>(VD);
15792 if (!FD)
15793 FD = cast<FieldDecl>(cast<IndirectFieldDecl>(VD)->chain().back());
15794 if (isPFPField(FD))
15796}
15797
15799 if (E->getNumComponents() == 0)
15800 return;
15801 OffsetOfNode Comp = E->getComponent(E->getNumComponents() - 1);
15802 if (Comp.getKind() != OffsetOfNode::Field)
15803 return;
15804 if (FieldDecl *FD = Comp.getField(); isPFPField(FD))
15806}
15807
15808namespace {
15809// PaddingCalculator is a utility class that calculates the padding bits in a
15810// c/c++ type. It traverses the type recursively, collecting occupied
15811// bit intervals, and then computes the padding intervals.
15812// If a byte only contains some padding bits, it gets intervals for only those
15813// bits. This is the case for bit-fields.
15814struct PaddingCalculator {
15815 PaddingCalculator(const ASTContext &Ctx) : Ctx(Ctx) {}
15816
15817 void run(QualType Ty) {
15818 OccuppiedIntervals.clear();
15819 Stack.clear();
15820
15821 TySizeInBits = Ctx.getTypeSize(Ty);
15822
15823 Stack.push_back(Data{0, Ty.getCanonicalType(), true});
15824 while (!Stack.empty()) {
15825 Data Current = Stack.back();
15826 Stack.pop_back();
15827 Visit(Current);
15828 }
15829 MergeOccuppiedIntervals();
15830 }
15831
15832 llvm::SmallVector<ASTContext::BitInterval> GetPaddingIntervals() {
15833 llvm::SmallVector<ASTContext::BitInterval> Results;
15834 if (OccuppiedIntervals.size() == 1 &&
15835 OccuppiedIntervals.front().First == 0 &&
15836 OccuppiedIntervals.front().Last == TySizeInBits) {
15837 return Results;
15838 }
15839 Results.reserve(OccuppiedIntervals.size() + 1);
15840 uint64_t CurrentPos = 0;
15841 for (const ASTContext::BitInterval &OccupiedInterval : OccuppiedIntervals) {
15842 if (OccupiedInterval.First > CurrentPos) {
15843 Results.push_back(
15844 ASTContext::BitInterval{CurrentPos, OccupiedInterval.First});
15845 }
15846 CurrentPos = OccupiedInterval.Last;
15847 }
15848 if (TySizeInBits > CurrentPos) {
15849 Results.push_back(ASTContext::BitInterval{CurrentPos, TySizeInBits});
15850 }
15851 return Results;
15852 }
15853
15854private:
15855 struct Data {
15856 uint64_t StartBitOffset;
15857 QualType Ty;
15858 bool VisitVirtualBase;
15859 };
15860
15861 // Return the number of non padding bits of a scalar type.
15862 //
15863 // The property that we specifically care about here is whether the scalar
15864 // type has padding bits, i.e. are there bits in the type which are not
15865 // specified by the ABI.
15866 //
15867 // We currently don't care about this anywhere else in clang: layout cares
15868 // about the ABI size, calling convention code cares about specific types,
15869 // but nothing cares about padding specifically. And it's not something we can
15870 // easily query from LLVM due to the type system mismatches.
15871 // DL.getTypeSizeInBits(convertTypeForLoadStore(T)) is probably close, but the
15872 // DataLayout methods aren't really designed for this usage.
15873 //
15874 // Therefore, it is better to explicitly list all the scalar types
15875 // containing padding bits that we know of, namely, _BitInt(N) and x87 long
15876 // double.
15877 //
15878 // FIXME: There are likely other scalar types we need to think about here, as
15879 // brought up in review for #215823:
15880 // - bool
15881 // - enums(both with/without fixed underlying type)
15882 // - nullptr_t
15883 // - more?
15884 uint64_t getScalarOccupiedSizeInBits(QualType Ty) const {
15885 if (const auto *BIT = Ty->getAs<BitIntType>())
15886 return BIT->getNumBits();
15887
15888 if (const auto *BT = Ty->getAs<BuiltinType>()) {
15889 if (BT->getKind() == BuiltinType::LongDouble &&
15891 &llvm::APFloat::x87DoubleExtended())
15892 return llvm::APFloat::getSizeInBits(
15894 }
15895
15896 return Ctx.getTypeSize(Ty);
15897 }
15898
15899 void Visit(const Data &D) {
15900 if (auto *AT = dyn_cast<ConstantArrayType>(D.Ty)) {
15901 VisitArray(AT, D.StartBitOffset);
15902 return;
15903 }
15904
15905 if (auto *Record = D.Ty->getAsRecordDecl()) {
15906 VisitStruct(Record, D.StartBitOffset, D.VisitVirtualBase);
15907 return;
15908 }
15909
15910 if (D.Ty->isAtomicType()) {
15911 auto Unwrapped = D;
15912 Unwrapped.Ty = D.Ty.getAtomicUnqualifiedType().getCanonicalType();
15913 Stack.push_back(Unwrapped);
15914 return;
15915 }
15916
15917 if (const auto *Complex = D.Ty->getAs<ComplexType>()) {
15918 VisitComplex(Complex, D.StartBitOffset);
15919 return;
15920 }
15921
15922 if (const auto *VT = D.Ty->getAs<clang::VectorType>()) {
15923 VisitVector(VT, D.StartBitOffset);
15924 return;
15925 }
15926
15927 if (const auto *BITy = D.Ty->getAs<BitIntType>()) {
15928 VisitBitInt(BITy, D.StartBitOffset);
15929 return;
15930 }
15931
15932 uint64_t SizeBit = getScalarOccupiedSizeInBits(D.Ty);
15933 OccuppiedIntervals.push_back(
15934 ASTContext::BitInterval{D.StartBitOffset, D.StartBitOffset + SizeBit});
15935 }
15936
15937 void VisitArray(const ConstantArrayType *AT, uint64_t StartBitOffset) {
15938 for (uint64_t ArrIndex = 0; ArrIndex < AT->getSize().getLimitedValue();
15939 ++ArrIndex) {
15940
15941 QualType ElementQualType = AT->getElementType();
15942 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
15943 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
15944 auto Offset = ElementSize.alignTo(ElementAlign);
15945
15946 Stack.push_back(Data{
15947 StartBitOffset + ArrIndex * Offset.getQuantity() * Ctx.getCharWidth(),
15948 ElementQualType.getCanonicalType(), /*VisitVirtualBase*/ true});
15949 }
15950 }
15951
15952 void VisitStruct(const RecordDecl *R, uint64_t StartBitOffset,
15953 bool VisitVirtualBase) {
15954 const ASTRecordLayout &ASTLayout = Ctx.getASTRecordLayout(R);
15955 auto *CXXRecord = dyn_cast<CXXRecordDecl>(R);
15956
15957 unsigned PointerSizeInBits = Ctx.getTypeSize(Ctx.NullPtrTy);
15958
15959 if (CXXRecord) {
15960 if (ASTLayout.hasOwnVFPtr()) {
15961 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15962 StartBitOffset, StartBitOffset + PointerSizeInBits});
15963 }
15964
15965 if (ASTLayout.hasOwnVBPtr()) {
15966 auto Offset = ASTLayout.getVBPtrOffset().getQuantity();
15967 auto StartVBPtr = StartBitOffset + Offset * Ctx.getCharWidth();
15968 OccuppiedIntervals.push_back(ASTContext::BitInterval{
15969 StartVBPtr, StartVBPtr + PointerSizeInBits});
15970 }
15971
15972 const auto VisitBase = [&ASTLayout, StartBitOffset, this](
15973 const CXXBaseSpecifier &Base, auto GetOffset) {
15974 auto *BaseRecord = Base.getType()->getAsCXXRecordDecl();
15975 if (!BaseRecord) {
15976 return;
15977 }
15978 auto BaseOffset =
15979 std::invoke(GetOffset, ASTLayout, BaseRecord).getQuantity();
15980
15981 Stack.push_back(
15982 Data{StartBitOffset + BaseOffset * Ctx.getCharWidth(),
15983 Base.getType().getCanonicalType(), /*VisitVirtualBase*/
15984 false});
15985 };
15986
15987 for (auto Base : CXXRecord->bases()) {
15988 if (!Base.isVirtual()) {
15989 VisitBase(Base, &ASTRecordLayout::getBaseClassOffset);
15990 }
15991 }
15992
15993 if (VisitVirtualBase) {
15994 for (auto VBase : CXXRecord->vbases()) {
15995 VisitBase(VBase, &ASTRecordLayout::getVBaseClassOffset);
15996 }
15997 }
15998 }
15999
16000 for (auto *Field : R->fields()) {
16001 // Treat unnamed bitfields as padding.
16002 if (Field->isUnnamedBitField())
16003 continue;
16004
16005 auto FieldOffset = ASTLayout.getFieldOffset(Field->getFieldIndex());
16006 if (Field->isBitField()) {
16007 VisitBitfield(Field, StartBitOffset + FieldOffset);
16008 } else {
16009 Stack.push_back(Data{StartBitOffset + FieldOffset,
16010 Field->getType().getCanonicalType(),
16011 /*VisitVirtualBase*/ true});
16012 }
16013 }
16014 }
16015
16016 void VisitBitfield(const FieldDecl *Field, uint64_t StartBitOffset) {
16017 assert(Field->isBitField() && !Field->isUnnamedBitField());
16018 if (Field->isZeroLengthBitField())
16019 return;
16020
16021 const uint64_t DeclaredSizeInBits = Field->getBitWidthValue();
16022
16023 // Oversized bit-fields (declared width larger than the field type) occupy
16024 // only the type's width. The extra declared bits are padding and follow
16025 // the occupied bits (Itanium C++ ABI §2.4, II.1(b)).
16026 // In case where the bitfield can only have values with a range smaller than
16027 // the one declared, e.g. bool a : 5 or _BitInt(5) b : 6, the remaining bits
16028 // within the bitfield are for sign or zero extension. These are considered
16029 // occupied as well.
16030 const uint64_t OccupiedSizeInBits =
16031 std::min(DeclaredSizeInBits, Ctx.getTypeSize(Field->getType()));
16032
16033 if (Ctx.getTargetInfo().isLittleEndian()) {
16034 OccuppiedIntervals.push_back(
16035 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16036 return;
16037 }
16038
16039 // In big endian mode, the sequence of occupied bits traverses bytes in
16040 // increasing address order, just like in little endian. However, within
16041 // each byte, the traversal starts from the most significant bit. This is
16042 // where it differs from little endian.
16043 //
16044 // If the interval contains whole bytes in the middle, then for these
16045 // nothing changes, and they constitute a contiguous interval. However for
16046 // the partially occupied bytes in either end, if present, their bit
16047 // intervals need to be adjusted so that they count from the MSB instead.
16048 //
16049 // Occupied bits are allocated first, and any padding follows them.
16050 const uint64_t Start = StartBitOffset;
16051 const uint64_t End = Start + OccupiedSizeInBits;
16052 const uint64_t CharWidth = Ctx.getCharWidth();
16053
16054 // Special case: all the occupied bits are contained within a single byte.
16055 const uint64_t ByteStart = llvm::alignDown(Start, CharWidth);
16056 const uint64_t ByteEnd = llvm::alignTo(End, CharWidth);
16057 if (ByteStart == ByteEnd - CharWidth) {
16058 const uint64_t Length = End - Start;
16059 const uint64_t Offset = Start - ByteStart;
16060 OccuppiedIntervals.push_back(
16061 {ByteEnd - Offset - Length, ByteEnd - Offset});
16062 return;
16063 }
16064
16065 // Compute the contiguous interval in the middle, comprised of whole bytes,
16066 // if any.
16067 const uint64_t MiddleIntervalStart = llvm::alignTo(Start, CharWidth);
16068 const uint64_t MiddleIntervalEnd = llvm::alignDown(End, CharWidth);
16069 if (MiddleIntervalStart != MiddleIntervalEnd)
16070 OccuppiedIntervals.push_back({MiddleIntervalStart, MiddleIntervalEnd});
16071
16072 // Compute the partially occupied first byte's interval, if any, counting
16073 // from the MSB.
16074 if (Start != MiddleIntervalStart) {
16075 const uint64_t Length = MiddleIntervalStart - Start;
16076 OccuppiedIntervals.push_back({ByteStart, ByteStart + Length});
16077 }
16078
16079 // Compute the partially occupied last byte's interval, if any, counting
16080 // from the MSB.
16081 if (End != MiddleIntervalEnd) {
16082 const uint64_t Length = End - MiddleIntervalEnd;
16083 OccuppiedIntervals.push_back({ByteEnd - Length, ByteEnd});
16084 }
16085 }
16086
16087 void VisitComplex(const ComplexType *CT, uint64_t StartBitOffset) {
16088 QualType ElementQualType = CT->getElementType().getCanonicalType();
16089 auto ElementSize = Ctx.getTypeSizeInChars(ElementQualType);
16090 auto ElementAlign = Ctx.getTypeAlignInChars(ElementQualType);
16091 auto ImgOffset = ElementSize.alignTo(ElementAlign);
16092
16093 Stack.push_back(
16094 Data{StartBitOffset, ElementQualType, /*VisitVirtualBase*/ true});
16095 Stack.push_back(
16096 Data{StartBitOffset + ImgOffset.getQuantity() * Ctx.getCharWidth(),
16097 ElementQualType, /*VisitVirtualBase*/ true});
16098 }
16099
16100 void VisitVector(const clang::VectorType *VT, uint64_t StartBitOffset) {
16101 if (VT->isPackedVectorBoolType(Ctx)) {
16102 VisitPackedBooleanVector(VT, StartBitOffset);
16103 return;
16104 }
16105
16106 uint64_t SizeBit = getScalarOccupiedSizeInBits(VT->getElementType()) *
16107 VT->getNumElements();
16108 OccuppiedIntervals.push_back(
16109 ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
16110 }
16111
16112 /// Compute the occupied bit intervals for a BitInt.
16113 ///
16114 /// In the case of little endian, the occupied bits are always contiguous so a
16115 /// single interval is sufficient. However in big endian, the intervals can be
16116 /// disjoint.
16117 void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
16118 const uint64_t OccupiedSizeInBits = Ty->getNumBits();
16119
16120 if (Ctx.getTargetInfo().isLittleEndian()) {
16121 OccuppiedIntervals.push_back(
16122 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16123 return;
16124 }
16125
16126 // In big endian mode, the layout of a BitInt in memory has its bytes in
16127 // reverse order, and is pictured in this order:
16128 // 1. Fully padding bytes.
16129 // 2. One partially occupied byte, with padding at the most significant
16130 // bits. ("remaining occupied bits")
16131 // 3. A sequence of fully occupied bytes up until the end of the storage.
16132 const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
16133 const uint64_t CharWidth = Ctx.getCharWidth();
16134 const uint64_t NumFullyPaddingBytes =
16135 (StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
16136 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16137 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16138
16139 // Partially occupied byte
16140 if (NumRemainingOccupiedBits > 0)
16141 OccuppiedIntervals.push_back(
16142 {StartBitOffset + NumFullyPaddingBytes * CharWidth,
16143 StartBitOffset + NumFullyPaddingBytes * CharWidth +
16144 NumRemainingOccupiedBits});
16145
16146 // Fully occupied bytes
16147 if (NumFullyOccupiedBytes > 0)
16148 OccuppiedIntervals.push_back({StartBitOffset + StorageSizeInBits -
16149 NumFullyOccupiedBytes * CharWidth,
16150 StartBitOffset + StorageSizeInBits});
16151 }
16152
16153 void VisitPackedBooleanVector(const VectorType *VTy,
16154 uint64_t StartBitOffset) {
16155 const uint64_t CharWidth = Ctx.getCharWidth();
16156 assert(StartBitOffset % CharWidth == 0 &&
16157 "Expected aligned packed boolean vector");
16158 assert(VTy->isPackedVectorBoolType(Ctx));
16159 const uint64_t OccupiedSizeInBits = VTy->getNumElements();
16160
16161 if (Ctx.getTargetInfo().isLittleEndian()) {
16162 OccuppiedIntervals.push_back(
16163 {StartBitOffset, StartBitOffset + OccupiedSizeInBits});
16164 return;
16165 }
16166
16167 // Only the sequence of bytes containing occupied bits has its order
16168 // reversed, but the bits within each byte are still counted from the least
16169 // significant bit. So if there are fully padding bytes, they reside at the
16170 // higher addresses in both endiannesses.
16171 const uint64_t NumFullyOccupiedBytes = OccupiedSizeInBits / CharWidth;
16172 const uint64_t NumRemainingOccupiedBits = OccupiedSizeInBits % CharWidth;
16173
16174 uint64_t Start = StartBitOffset;
16175 // Partially occupied byte at the beginning
16176 if (NumRemainingOccupiedBits > 0) {
16177 const uint64_t ByteEnd = Start + CharWidth;
16178 OccuppiedIntervals.push_back({Start, Start + NumRemainingOccupiedBits});
16179 Start = ByteEnd;
16180 }
16181
16182 // The remaining fully occupied bytes form a contiguous interval
16183 if (NumFullyOccupiedBytes > 0) {
16184 OccuppiedIntervals.push_back(
16185 {Start, Start + NumFullyOccupiedBytes * CharWidth});
16186 }
16187 }
16188
16189 void MergeOccuppiedIntervals() {
16190 std::sort(OccuppiedIntervals.begin(), OccuppiedIntervals.end(),
16191 [](const ASTContext::BitInterval &lhs,
16192 const ASTContext::BitInterval &rhs) {
16193 return std::tie(lhs.First, lhs.Last) <
16194 std::tie(rhs.First, rhs.Last);
16195 });
16196
16197 llvm::SmallVector<ASTContext::BitInterval> Merged;
16198 Merged.reserve(OccuppiedIntervals.size());
16199
16200 for (const ASTContext::BitInterval &NextInterval : OccuppiedIntervals) {
16201 if (Merged.empty()) {
16202 Merged.push_back(NextInterval);
16203 continue;
16204 }
16205 auto &LastInterval = Merged.back();
16206
16207 if (NextInterval.First > LastInterval.Last) {
16208 Merged.push_back(NextInterval);
16209 } else {
16210 LastInterval.Last = std::max(LastInterval.Last, NextInterval.Last);
16211 }
16212 }
16213
16214 OccuppiedIntervals = Merged;
16215 }
16216
16217 const ASTContext &Ctx;
16218 // unsigned PointerSizeInBits;
16219 uint64_t TySizeInBits = 0;
16220 llvm::SmallVector<Data> Stack;
16221 llvm::SmallVector<ASTContext::BitInterval> OccuppiedIntervals;
16222};
16223} // namespace
16224
16225llvm::ArrayRef<ASTContext::BitInterval>
16227 Ty = Ty.getCanonicalType();
16228 auto cached = PaddingIntervalCache.find(Ty);
16229 if (cached != PaddingIntervalCache.end())
16230 return cached->second;
16231
16232 PaddingCalculator pc{*this};
16233 pc.run(Ty);
16234
16235 auto [itr, res] =
16236 PaddingIntervalCache.insert_or_assign(Ty, pc.GetPaddingIntervals());
16237 assert(res && "Failed to insert?");
16238
16239 return itr->second;
16240}
This file provides AST data structures related to concepts.
static void SortAndUniqueProtocols(SmallVectorImpl< ObjCProtocolDecl * > &Protocols)
static bool isCanonicalExceptionSpecification(const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType)
static SourceLocation getCommonAttrLoc(const T *X, const T *Y)
static auto getCanonicalTemplateArguments(const ASTContext &C, ArrayRef< TemplateArgument > Args, bool &AnyNonCanonArgs)
static char getObjCEncodingForPrimitiveType(const ASTContext *C, const BuiltinType *BT)
static bool isSameQualifier(const NestedNameSpecifier X, const NestedNameSpecifier Y)
static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static TypedefDecl * CreateHexagonBuiltinVaListDecl(const ASTContext *Context)
#define CANONICAL_TYPE(Class)
static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y, bool IsSame)
static Decl * getCommonDecl(Decl *X, Decl *Y)
static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, const Decl *D, GVALinkage L)
static bool isTypeTypedefedAsBOOL(QualType T)
static void EncodeBitField(const ASTContext *Ctx, std::string &S, QualType T, const FieldDecl *FD)
static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, const VarDecl *VD)
static QualType getCommonArrayElementType(const ASTContext &Ctx, const T *X, Qualifiers &QX, const T *Y, Qualifiers &QY)
static bool hasImplicitAttr(const ValueDecl *D)
#define SUGAR_FREE_TYPE(Class)
static SYCLKernelInfo BuildSYCLKernelInfo(ASTContext &Context, CanQualType KernelNameType, const FunctionDecl *FD)
static bool hasTemplateSpecializationInEncodedString(const Type *T, bool VisitBasesAndFields)
static void getIntersectionOfProtocols(ASTContext &Context, const ObjCInterfaceDecl *CommonBase, const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, SmallVectorImpl< ObjCProtocolDecl * > &IntersectionSet)
getIntersectionOfProtocols - This routine finds the intersection of set of protocols inherited from t...
static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, const ConstantMatrixType *RHS)
areCompatMatrixTypes - Return true if the two specified matrix types are compatible.
static TypedefDecl * CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context)
static bool sameObjCTypeArgs(ASTContext &ctx, const ObjCInterfaceDecl *iface, ArrayRef< QualType > lhsArgs, ArrayRef< QualType > rhsArgs, bool stripKindOf)
static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs)
Determine whether the first type is a subtype of the second.
static const Type * getIntegerTypeForEnum(const EnumType *ET)
static SmallVector< SourceLocation, 2 > getLocsForCommentSearch(ASTContext::RawCommentLookupKey Key, SourceManager &SourceMgr)
static bool hasSameCudaAttrs(const FunctionDecl *A, const FunctionDecl *B)
static TemplateName getCommonTemplateName(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced=false)
static int CmpProtocolNames(ObjCProtocolDecl *const *LHS, ObjCProtocolDecl *const *RHS)
CmpProtocolNames - Comparison predicate for sorting protocols alphabetically.
static auto * getCommonSizeExpr(const ASTContext &Ctx, T *X, T *Y)
static TypedefDecl * CreatePowerABIBuiltinVaListDecl(const ASTContext *Context)
static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y)
static TemplateArgument getCommonTemplateArgument(const ASTContext &Ctx, const TemplateArgument &X, const TemplateArgument &Y)
static std::optional< int64_t > structHasUniqueObjectRepresentations(const ASTContext &Context, const RecordDecl *RD, bool CheckIfTriviallyCopyable)
static bool hasSameOverloadableAttrs(const FunctionDecl *A, const FunctionDecl *B)
Determine whether the attributes we can overload on are identical for A and B.
static T * getCommonDeclChecked(T *X, T *Y)
static NestedNameSpecifier getCommonNNS(const ASTContext &Ctx, NestedNameSpecifier NNS1, NestedNameSpecifier NNS2, bool IsSame)
Returns a NestedNameSpecifier which has only the common sugar present in both NNS1 and NNS2.
static TypedefDecl * CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context)
static int64_t getSubobjectOffset(const FieldDecl *Field, const ASTContext &Context, const clang::ASTRecordLayout &)
static QualType getCommonSugarTypeNode(const ASTContext &Ctx, const Type *X, const Type *Y, SplitQualType Underlying)
static TypedefDecl * CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonNonSugarTypeNode(const ASTContext &Ctx, const Type *X, Qualifiers &QX, const Type *Y, Qualifiers &QY)
static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, QualType other, bool isBlockReturnType)
Given that we have an enum type and a non-enum type, try to merge them.
static GVALinkage adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, GVALinkage L)
Adjust the GVALinkage for a declaration based on what an external AST source knows about whether ther...
static TypedefDecl * CreateSystemZBuiltinVaListDecl(const ASTContext *Context)
static std::optional< int64_t > getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context, bool CheckIfTriviallyCopyable)
static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, const FunctionDecl *FD)
#define NON_UNIQUE_TYPE(Class)
static TypedefDecl * CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context)
static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, const LangOptions &LangOpts)
static ElaboratedTypeKeyword getCanonicalElaboratedTypeKeyword(ElaboratedTypeKeyword Keyword)
static QualType getCommonPointeeType(const ASTContext &Ctx, const T *X, const T *Y)
static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X, const ArrayType *Y)
static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequiresICE, bool AllowTypeModifiers)
DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the pointer over the consume...
FloatingRank
@ FloatRank
@ LongDoubleRank
@ Float16Rank
@ Ibm128Rank
@ Float128Rank
@ BFloat16Rank
@ HalfRank
@ DoubleRank
static TypedefDecl * CreateCharPtrBuiltinVaListDecl(const ASTContext *Context)
static bool areSortedAndUniqued(ArrayRef< ObjCProtocolDecl * > Protocols)
static TypeInfoChars getConstantArrayInfoInChars(const ASTContext &Context, const ConstantArrayType *CAT)
getConstantArrayInfoInChars - Performing the computation in CharUnits instead of in bits prevents ove...
static FloatingRank getFloatingRank(QualType T)
getFloatingRank - Return a relative rank for floating point types.
static bool getCommonTemplateArguments(const ASTContext &Ctx, SmallVectorImpl< TemplateArgument > &R, ArrayRef< TemplateArgument > Xs, ArrayRef< TemplateArgument > Ys)
static TypedefDecl * CreateXtensaABIBuiltinVaListDecl(const ASTContext *Context)
static QualType getCommonElementType(const ASTContext &Ctx, const T *X, const T *Y)
static void mergeTypeLists(const ASTContext &Ctx, SmallVectorImpl< QualType > &Out, ArrayRef< QualType > X, ArrayRef< QualType > Y)
static bool matchesPostDecrInWhile(const UnaryOperator *UO, ASTContext &Ctx)
For the purposes of overflow pattern exclusion, does this match the while(i–) pattern?
static void encodeTypeForFunctionPointerAuth(const ASTContext &Ctx, raw_ostream &OS, QualType QT)
Encode a function type for use in the discriminator of a function pointer type.
static std::optional< int64_t > structSubobjectsHaveUniqueObjectRepresentations(const RangeT &Subobjects, int64_t CurOffsetInBits, const ASTContext &Context, const clang::ASTRecordLayout &Layout, bool CheckIfTriviallyCopyable)
static uint64_t getRVVTypeSize(ASTContext &Context, const BuiltinType *Ty)
getRVVTypeSize - Return RVV vector register size.
static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal)
static TemplateName getCommonTemplateNameChecked(const ASTContext &Ctx, TemplateName X, TemplateName Y, bool IgnoreDeduced)
static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, ObjCProtocolDecl *const *rhs)
Comparison routine for Objective-C protocols to be used with llvm::array_pod_sort.
static const TagDecl * getNonInjectedClassName(const TagDecl *TD)
static TypedefDecl * CreateZOSVaListDecl(const ASTContext *Context)
static bool hasAnyPackExpansions(ArrayRef< TemplateArgument > Args)
static char ObjCEncodingForEnumDecl(const ASTContext *C, const EnumDecl *ED)
static std::string charUnitsToString(CharUnits CU)
static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, SmallVectorImpl< const NamedDecl * > &Redeclared)
static QualType getCommonTypeWithQualifierLifting(const ASTContext &Ctx, QualType X, QualType Y, Qualifiers &QX, Qualifiers &QY)
static auto getCommonTypes(const ASTContext &Ctx, ArrayRef< QualType > Xs, ArrayRef< QualType > Ys, bool Unqualified=false)
static bool isCanonicalResultType(QualType T)
Determine whether T is canonical as the result type of a function.
static TypedefDecl * CreateMSVaListDecl(const ASTContext *Context)
static bool areCompatVectorTypes(const VectorType *LHS, const VectorType *RHS)
areCompatVectorTypes - Return true if the two specified vector types are compatible.
static TypedefDecl * CreateCharPtrNamedVaListDecl(const ASTContext *Context, StringRef Name)
static NestedNameSpecifier getCommonQualifier(const ASTContext &Ctx, const T *X, const T *Y, bool IsSame)
#define UNEXPECTED_TYPE(Class, Kind)
static TypedefDecl * CreateVaListDecl(const ASTContext *Context, TargetInfo::BuiltinVaListKind Kind)
static bool primaryBaseHaseAddressDiscriminatedVTableAuthentication(const ASTContext &Context, const CXXRecordDecl *Class)
static std::vector< std::string > getFMVBackendFeaturesFor(const llvm::SmallVectorImpl< StringRef > &FMVFeatStrings)
Defines the clang::ASTContext interface.
#define V(N, I)
#define BuiltinTemplate(BTName)
Definition ASTContext.h:504
This file provides some common utility functions for processing Lambda related AST Constructs.
Provides definitions for the various language-specific address spaces.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2854
Defines the clang::CommentOptions interface.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static const Decl * getCanonicalDecl(const Decl *D)
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
Definition Module.cpp:96
Defines the clang::Module class, which describes a module in the source code.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static QualType getUnderlyingType(const SubRegion *R)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
@ GE_Missing_stdio
Missing a type from <stdio.h>
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1216
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1223
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CanQualType AccumTy
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, const ObjCMethodDecl *MethodImp)
CanQualType ObjCBuiltinSelTy
TranslationUnitDecl * getTranslationUnitDecl() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
LangAS getOpenCLTypeAddrSpace(const Type *T) const
Get address space for OpenCL type.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
void InitBuiltinTypes(const TargetInfo &Target, const TargetInfo *AuxTarget=nullptr)
Initialize built-in types.
QualType getParenType(QualType NamedType) const
size_t getSideTableAllocatedMemory() const
Return the total memory used for various side tables.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType ARCUnbridgedCastTy
QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr, Expr *ColumnExpr, SourceLocation AttrLoc) const
Return the unique reference to the matrix type of the specified element type and size.
QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr, QualType Wrapped) const
llvm::DenseMap< const Decl *, comments::FullComment * > ParsedComments
Mapping from declarations to parsed comments attached to any redeclaration.
unsigned getManglingNumber(const NamedDecl *ND, bool ForAuxTarget=false) const
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
CanQualType WIntTy
@ Weak
Weak definition of inline variable.
@ WeakUnknown
Weak for now, might become strong later in this TU.
bool dtorHasOperatorDelete(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl)
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
TypedefDecl * getCFConstantStringDecl() const
CanQualType Int128Ty
CanQualType SatUnsignedFractTy
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns, std::optional< MatrixType::LayoutKind > Layout=std::nullopt) const
Return the unique reference to the matrix type of the specified element type and size.
ExternCContextDecl * getExternCContextDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
CanQualType UnsignedShortAccumTy
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType adjustFunctionResultType(QualType FunctionType, QualType NewResultType)
Change the result type of a function type, preserving sugar such as attributed types.
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const
ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the inheritance hierarchy of 'rProto...
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
QualType getCanonicalTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
QualType getAutoRRefDeductType() const
C++11 deduction pattern for 'auto &&' type.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool AllowCXX=false, bool IsConditionalOperator=false)
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:860
comments::FullComment * cloneFullComment(comments::FullComment *FC, const Decl *D) const
CharUnits getObjCEncodingTypeSize(QualType T) const
Return the size of type T for Objective-C encoding purpose, in characters.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
const TemplateArgument * getDefaultTemplateArgumentOrNone(const NamedDecl *P) const
Return the default argument of a template parameter, if one exists.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
void setCurrentNamedModule(Module *M)
Set the (C++20) module we are building.
QualType getProcessIDType() const
Return the unique type for "pid_t" defined in <sys/types.h>.
CharUnits getMemberPointerPathAdjustment(const APValue &MP) const
Find the 'this' offset for the member path in a pointer-to-member APValue.
bool mayExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel may be externalized.
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
CanQualType SatAccumTy
ArrayRef< CXXDefaultArgExpr * > getCtorClosureDefaultArgs(const CXXConstructorDecl *CD)
QualType getUnsignedPointerDiffType() const
Return the unique unsigned counterpart of "ptrdiff_t" integer type.
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
bool hasSameExpr(const Expr *X, const Expr *Y) const
Determine whether the given expressions X and Y are equivalent.
TemplateName getPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< TemplateName > Expansions={}) const
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
RawComment * getRawCommentNoCache(RawCommentLookupKey Key) const
Return the documentation comment attached to a given declaration or macro, without looking into cache...
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
unsigned NumImplicitCopyAssignmentOperatorsDeclared
The number of implicitly-declared copy assignment operators for which declarations were built.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
unsigned getTypeUnadjustedAlign(QualType T) const
Return the ABI-specified natural alignment of a (complete) type T, before alignment adjustments,...
unsigned char getFixedPointIBits(QualType Ty) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
IntrusiveRefCntPtr< ExternalASTSource > ExternalSource
Definition ASTContext.h:861
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned NumImplicitDestructorsDeclared
The number of implicitly-declared destructors for which declarations were built.
bool mergeExtParameterInfo(const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl< FunctionProtoType::ExtParameterInfo > &NewParamInfos)
This function merges the ExtParameterInfo lists of two functions.
bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS)
ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and Class<pr1, ...>.
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
bool propertyTypesAreCompatible(QualType, QualType)
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
CanQualType DoubleTy
QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc, VectorKind VecKind) const
Return the unique reference to the type for a dependently sized vector of the specified element type.
CanQualType SatLongAccumTy
CanQualType getIntMaxType() const
Return the unique type for "intmax_t" (C99 7.18.1.5), defined in <stdint.h>.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
OpenCLTypeKind getOpenCLTypeKind(const Type *T) const
Map an AST Type to an OpenCLTypeKind enum value.
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, std::string &S) const
Put the string version of the type qualifiers QT into S.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
CanQualType LongDoubleTy
CanQualType OMPArrayShapingTy
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents, SelectorTable &sels, Builtin::Context &builtins, TranslationUnitKind TUKind)
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
CanQualType Char16Ty
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
unsigned getStaticLocalNumber(const VarDecl *VD) const
void addComment(const RawComment &RC)
void getLegacyIntegralTypeEncoding(QualType &t) const
getLegacyIntegralTypeEncoding - Another legacy compatibility encoding: 32-bit longs are encoded as 'l...
bool isSameTypeConstraint(const TypeConstraint *XTC, const TypeConstraint *YTC) const
Determine whether two type contraint are similar enough that they could used in declarations of the s...
void setRelocationInfoForCXXRecord(const CXXRecordDecl *, CXXRecordDeclRelocationInfo)
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
Retrieve a substitution-result type.
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
void completeCountAttributedType(CountAttributedType *CATy, Expr *CountExpr, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
Supply the count expression and coupled declarations for a type created by getIncompleteCountAttribut...
CanQualType UnsignedLongFractTy
QualType mergeTagDefinitions(QualType, QualType)
void setClassMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
overridden_method_range overridden_methods(const CXXMethodDecl *Method) const
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const
Return a dependent bit-precise integer type with the specified signedness and bit count.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD, ObjCImplementationDecl *ImplD)
Set the implementation of ObjCInterfaceDecl.
StringRef getCUIDHash() const
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const
Returns true if this is an inline-initialized static data member which is treated as a definition for...
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent) const
llvm::PointerUnion< const Decl *, const MacroInfo * > RawCommentLookupKey
Key used to look up the raw comment attached to a declaration or macro.
void addLazyModuleInitializers(Module *M, ArrayRef< GlobalDeclID > IDs)
bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
CanQualType NullPtrTy
QualType getUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UsingShadowDecl *D, QualType UnderlyingType=QualType()) const
std::optional< QualType > tryMergeOverflowBehaviorTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType, bool IsConditionalOperator)
Attempts to merge two types that may be OverflowBehaviorTypes.
CanQualType WideCharTy
CanQualType OMPIteratorTy
IdentifierTable & Idents
Definition ASTContext.h:856
Builtin::Context & BuiltinInfo
Definition ASTContext.h:858
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
const LangOptions & getLangOpts() const
QualType getFunctionTypeWithoutPtrSizes(QualType T)
Get a function type and produce the equivalent function type where pointer size address spaces in the...
uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID, const ObjCIvarDecl *Ivar) const
Get the offset of an ObjCIvarDecl in bits.
SelectorTable & Selectors
Definition ASTContext.h:857
bool isTypeIgnoredBySanitizer(const SanitizerMask &Mask, const QualType &Ty) const
Check if a type can have its sanitizer instrumentation elided based on its presence within an ignorel...
unsigned getMinGlobalAlignOfVar(uint64_t Size, const VarDecl *VD) const
Return the minimum alignment as specified by the target.
RawCommentList Comments
All comments in this translation unit.
bool isSameDefaultTemplateArgument(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two default template arguments are similar enough that they may be used in declarat...
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType getLateParsedAttrType(QualType Wrapped, LateParsedTypeAttribute *LateParsedAttr) const
Return a placeholder type for a late-parsed type attribute.
QualType removePtrSizeAddrSpace(QualType T) const
Remove the existing address space on the type if it is a pointer size address space and return the ty...
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
llvm::ArrayRef< BitInterval > getPaddingIntervals(QualType Ty) const
CanQualType SatShortFractTy
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
bool canBindObjCObjectType(QualType To, QualType From)
TemplateTemplateParmDecl * insertCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *CanonTTP) const
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const
Return one of the GCNone, Weak or Strong Objective-C garbage collection attributes.
CanQualType Ibm128Ty
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
CanQualType getCanonicalSizeType() const
bool typesAreBlockPointerCompatible(QualType, QualType)
CanQualType SatUnsignedAccumTy
bool useAbbreviatedThunkName(GlobalDecl VirtualMethodDecl, StringRef MangledName)
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
QualType getSignatureParameterType(QualType T) const
Retrieve the parameter type as adjusted for use in the signature of a function, decaying array and fu...
CanQualType ArraySectionTy
CanQualType ObjCBuiltinIdTy
overridden_cxx_method_iterator overridden_methods_end(const CXXMethodDecl *Method) const
VTableContextBase * getVTableContext()
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
bool isNearlyEmpty(const CXXRecordDecl *RD) const
PointerAuthQualifier getObjCMemberSelTypePtrAuth()
QualType AutoDeductTy
CanQualType BoolTy
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
QualType getCFConstantStringType() const
Return the C structure type used to represent constant CFStrings.
void eraseDeclAttrs(const Decl *D)
Erase the attributes corresponding to the given declaration.
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
RecordDecl * getCFConstantStringTagDecl() const
std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const
Emit the encoded type for the function Decl into S.
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
CanQualType MetaInfoTy
CanQualType UnsignedFractTy
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType mergeFunctionParameterTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false)
mergeFunctionParameterTypes - merge two types which appear as function parameter types
void addOverriddenMethod(const CXXMethodDecl *Method, const CXXMethodDecl *Overridden)
Note that the given C++ Method overrides the given Overridden method.
TemplateTemplateParmDecl * findCanonicalTemplateTemplateParmDeclInternal(TemplateTemplateParmDecl *TTP) const
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:976
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:619
CanQualType UnsignedLongTy
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass, SmallVectorImpl< const ObjCIvarDecl * > &Ivars) const
DeepCollectObjCIvars - This routine first collects all declared, but not synthesized,...
bool computeBestEnumTypes(bool IsPacked, unsigned NumNegativeBits, unsigned NumPositiveBits, QualType &BestType, QualType &BestPromotionType)
Compute BestType and BestPromotionType for an enum based on the highest number of negative and positi...
llvm::APFixedPoint getFixedPointMin(QualType Ty) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType adjustType(QualType OldType, llvm::function_ref< QualType(QualType)> Adjust) const
Rebuild a type, preserving any existing type sugar.
void addedLocalImportDecl(ImportDecl *Import)
Notify the AST context that a new import declaration has been parsed or implicitly created within thi...
const TranslationUnitKind TUKind
Definition ASTContext.h:859
CanQualType UnsignedLongAccumTy
QualType AutoRRefDeductTy
RawComment * getRawCommentNoCacheImpl(RawCommentLookupKey Key, const SourceLocation RepresentativeLoc, const std::map< unsigned, RawComment * > &CommentsInFile) const
CountAttributedType * getIncompleteCountAttributedType(QualType WrappedTy, bool CountInBytes, bool OrNull) const
Return a CountAttributedType whose count expression has not been parsed yet, for use by a late-parsed...
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
bool arePFPFieldsTriviallyCopyable(const RecordDecl *RD) const
Returns whether this record's PFP fields (if any) are trivially copyable (i.e.
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
CanQualType BoundMemberTy
CanQualType SatUnsignedShortFractTy
CanQualType CharTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
bool hasSameFunctionTypeIgnoringParamABI(QualType T, QualType U) const
Determine if two function types are the same, ignoring parameter ABI annotations.
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
QualType getObjCSuperType() const
Returns the C struct type for objc_super.
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
bool CommentsLoaded
True if comments are already loaded from ExternalASTSource.
BlockVarCopyInit getBlockVarCopyInit(const VarDecl *VD) const
Get the copy initialization expression of the VarDecl VD, or nullptr if none exists.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
unsigned NumImplicitMoveConstructorsDeclared
The number of implicitly-declared move constructors for which declarations were built.
bool isInSameModule(const Module *M1, const Module *M2) const
If the two module M1 and M2 are in the same module.
unsigned NumImplicitCopyConstructorsDeclared
The number of implicitly-declared copy constructors for which declarations were built.
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
CanQualType PseudoObjectTy
QualType getWebAssemblyExternrefType() const
Return a WebAssembly externref type.
void setTraversalScope(const std::vector< Decl * > &)
CharUnits getTypeUnadjustedAlignInChars(QualType T) const
getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type, in characters,...
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
friend class NestedNameSpecifier
Definition ASTContext.h:246
void PrintStats() const
MangleContext * cudaNVInitDeviceMC()
unsigned getAlignOfGlobalVar(QualType T, const VarDecl *VD) const
Return the alignment in bits that should be given to a global variable with type T.
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
comments::FullComment * getLocalCommentForDeclUncached(const Decl *D) const
Return parsed documentation comment attached to a given declaration.
unsigned NumImplicitDestructors
The number of implicitly-declared destructors.
CanQualType Float16Ty
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
bool isAlignmentRequired(const Type *T) const
Determine if the alignment the type has was required using an alignment attribute.
TagDecl * MSGuidTagDecl
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
MangleContext * createDeviceMangleContext(const TargetInfo &T)
Creates a device mangle context to correctly mangle lambdas in a mixed architecture compile by settin...
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
ASTMutationListener * Listener
Definition ASTContext.h:862
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:909
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:611
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:930
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
bool canBuiltinBeRedeclared(const FunctionDecl *) const
Return whether a declaration to a builtin is allowed to be overloaded/redeclared.
CanQualType UnsignedIntTy
unsigned NumImplicitMoveConstructors
The number of implicitly-declared move constructors.
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl, ArrayRef< ObjCProtocolDecl * > protocols) const
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
static bool isPFPField(const FieldDecl *Field)
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
unsigned overridden_methods_size(const CXXMethodDecl *Method) const
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const
Return the encoded type for this block declaration.
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
bool isSameAssociatedConstraint(const AssociatedConstraint &ACX, const AssociatedConstraint &ACY) const
Determine whether two 'requires' expressions are similar enough that they may be used in re-declarati...
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
CanQualType UnsignedLongLongTy
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
CanQualType OCLReserveIDTy
bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const
Determine whether two template parameters are similar enough that they may be used in declarations of...
void registerSYCLEntryPointFunction(FunctionDecl *FD)
Generates and stores SYCL kernel metadata for the provided SYCL kernel entry point function.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
overridden_cxx_method_iterator overridden_methods_begin(const CXXMethodDecl *Method) const
CanQualType UnsignedShortTy
FunctionDecl * getOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, OperatorDeleteKind K) const
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may both be array types with the same bound (or both be array types ...
bool isRepresentableIntegerValue(llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
llvm::DenseMap< RawCommentLookupKey, const RawComment * > RawComments
Mapping from declaration or macro to directly attached comment.
const SYCLKernelInfo & getSYCLKernelInfo(QualType T) const
Given a type used as a SYCL kernel name, returns a reference to the metadata generated from the corre...
bool canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT, bool BlockReturnType)
canAssignObjCInterfacesInBlockPointer - This routine is specifically written for providing type-safet...
CanQualType SatUnsignedLongFractTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const CXXConstructorDecl * getCopyConstructorForExceptionObject(CXXRecordDecl *RD)
QualType getDependentAddressSpaceType(QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const
QualType getTagType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TagDecl *TD, bool OwnsTag) const
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
void setExternalSource(IntrusiveRefCntPtr< ExternalASTSource > Source)
Attach an external AST source to the AST context.
const ObjCInterfaceDecl * getObjContainingInterface(const NamedDecl *ND) const
Returns the Objective-C interface that ND belongs to if it is an Objective-C method/property/ivar etc...
CanQualType ShortTy
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
CanQualType getCanonicalUnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool classMaybeNeedsVectorDeletingDestructor(const CXXRecordDecl *RD)
QualType getTemplateTypeParmType(int Depth, int Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
void deduplicateMergedDefinitionsFor(NamedDecl *ND)
Clean up the merged definition list.
static uint64_t getConstantArrayElementCount(const ConstantArrayType *CA)
Return number of (potentially nested) constant array elements.
DiagnosticsEngine & getDiagnostics() const
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
CanQualType LongAccumTy
CanQualType Char32Ty
void recordOffsetOfEvaluation(const OffsetOfExpr *E)
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
UnnamedGlobalConstantDecl * getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const
Return a declaration for a uniquified anonymous global constant corresponding to a given APValue.
CanQualType SatFractTy
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
QualType getUnresolvedUsingType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D) const
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
void getOverriddenMethods(const NamedDecl *Method, SmallVectorImpl< const NamedDecl * > &Overridden) const
Return C++ or ObjC overridden methods for the given Method.
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
CanQualType SatLongFractTy
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:975
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl)
CanQualType OCLQueueTy
CanQualType LongFractTy
OBTAssignResult checkOBTAssignmentCompatibility(QualType LHS, QualType RHS)
Check overflow behavior type compatibility for assignments.
CanQualType SatShortAccumTy
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType BFloat16Ty
unsigned NumImplicitCopyConstructors
The number of implicitly-declared copy constructors.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
static uint64_t getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE)
Return number of elements initialized in a (potentially nested) ArrayInitLoopExpr.
void addExplicitInstantiationDecl(const NamedDecl *Spec, ExplicitInstantiationDecl *EID)
Add an ExplicitInstantiationDecl for a given specialization.
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
CanQualType IncompleteMatrixIdxTy
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
CanQualType getNSIntegerType() const
QualType getCorrespondingUnsignedType(QualType T) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
bool shouldEmitCUDADecl(const ValueDecl *D) const
Determines if the global variable or function D is emitted on the side of the CUDA/HIP compilation,...
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
QualType getHLSLAttributedResourceType(QualType Wrapped, QualType Contained, const HLSLAttributedResourceType::Attributes &Attrs)
bool UnwrapSimilarTypes(QualType &T1, QualType &T2, bool AllowPiMismatch=true) const
Attempt to unwrap two types that may be similar (C++ [conv.qual]).
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
CanQualType SatUnsignedLongAccumTy
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
QualType getCorrespondingSignedType(QualType T) const
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
llvm::DenseMap< const Decl *, const Decl * > CommentlessRedeclChains
Keeps track of redeclaration chains that don't have any comment attached.
unsigned getTargetAddressSpace(LangAS AS) const
ParentMapContext & getParentMapContext()
Returns the dynamic AST node parent map context.
Definition ASTContext.h:882
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M, bool NotifyListeners=true)
Note that the definition ND has been merged into module M, and should be visible whenever M is visibl...
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
void addTranslationUnitDecl()
CanQualType WCharTy
void getObjCEncodingForPropertyType(QualType T, std::string &S) const
Emit the Objective-C property type encoding for the given type T into S.
unsigned NumImplicitCopyAssignmentOperators
The number of implicitly-declared copy assignment operators.
void CollectInheritedProtocols(const Decl *CDecl, llvm::SmallPtrSet< ObjCProtocolDecl *, 8 > &Protocols)
CollectInheritedProtocols - Collect all protocols in current class and those inherited by it.
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
llvm::DenseMap< const Decl *, const Decl * > RedeclChainComments
Mapping from canonical declaration to the first redeclaration in chain that has a comment attached.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
std::optional< CXXRecordDeclRelocationInfo > getRelocationInfoForCXXRecord(const CXXRecordDecl *) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
InlineVariableDefinitionKind getInlineVariableDefinitionKind(const VarDecl *VD) const
Determine whether a definition of this inline variable should be treated as a weak or strong definiti...
const RawComment * getRawCommentForAnyRedecl(RawCommentLookupKey Key, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration or macro.
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, bool Final) const
CanQualType getUIntMaxType() const
Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in <stdint.h>.
friend class DeclContext
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const
Loading virtual member pointers using the virtual inheritance model always results in an adjustment u...
LangAS getLangASForBuiltinAddressSpace(unsigned AS) const
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
void addOperatorDeleteForVDtor(const CXXDestructorDecl *Dtor, FunctionDecl *OperatorDelete, OperatorDeleteKind K) const
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
QualType DecodeTypeStr(const char *&Str, const ASTContext &Context, ASTContext::GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
@ GE_None
No error.
@ GE_Missing_type
Missing a type.
QualType adjustStringLiteralBaseType(QualType StrLTy) const
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
llvm::SetVector< const FieldDecl * > PFPFieldsWithEvaluatedOffset
uint16_t getPointerAuthVTablePointerDiscriminator(const CXXRecordDecl *RD, bool IsVTTEntry)
Return the "other" discriminator used for the pointer auth schema used for vtable pointers using the ...
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
QualType getMatrixTypeWithLayout(QualType T, MatrixType::LayoutKind Layout) const
CanQualType Char8Ty
bool isUnaryOverflowPatternExcluded(const UnaryOperator *UO)
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
ObjCImplementationDecl * getObjCImplementation(ObjCInterfaceDecl *D)
Get the implementation of the ObjCInterfaceDecl D, or nullptr if none exists.
CanQualType HalfTy
CanQualType UnsignedAccumTy
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD, const ObjCMethodDecl *Redecl)
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
const CXXRecordDecl * baseForVTableAuthentication(const CXXRecordDecl *ThisClass) const
Resolve the root record to be used to derive the vtable pointer authentication policy for the specifi...
void cacheRawComment(RawCommentLookupKey Original, const RawComment &Comment) const
Attaches Comment to Original (a declaration or macro), and to its redeclaration chain when Original i...
QualType getVariableArrayDecayedType(QualType Ty) const
Returns a vla type where known sizes are replaced with [*].
void setCFConstantStringType(QualType T)
const SYCLKernelInfo * findSYCLKernelInfo(QualType T) const
Returns a pointer to the metadata generated from the corresponding SYCLkernel entry point if the prov...
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
CanQualType OCLEventTy
void AddDeallocation(void(*Callback)(void *), void *Data) const
Add a deallocation callback that will be invoked when the ASTContext is destroyed.
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:3605
Represents a loop initializing the elements of an array.
Definition Expr.h:6022
llvm::APInt getArraySize() const
Definition Expr.h:6044
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6042
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3990
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
Qualifiers getIndexTypeQualifiers() const
Definition TypeBase.h:3838
QualType getElementType() const
Definition TypeBase.h:3832
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3842
A structure for storing the information associated with a name that has been assumed to be a template...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6982
Expr * getPtr() const
Definition Expr.h:7013
Attr - This represents one attribute.
Definition Attr.h:46
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8304
unsigned getNumBits() const
Definition TypeBase.h:8316
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4814
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6726
Pointer to a block type.
Definition TypeBase.h:3653
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
static BuiltinTemplateDecl * Create(const ASTContext &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK)
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
Kind getKind() const
Definition TypeBase.h:3299
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition Builtins.h:237
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:2642
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:2263
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1196
SplitQualType split() const
static CanQual< Type > CreateUnsafe(QualType Other)
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
Test whether the quantity is greater than zero.
Definition CharUnits.h:107
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
bool hasExplicitTemplateArgs() const
Whether or not template arguments were explicitly specified in the concept reference (they might not ...
Definition ASTConcept.h:209
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:203
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition TypeBase.h:3954
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition TypeBase.h:3973
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4512
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4560
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4509
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition TypeBase.h:3509
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3554
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2120
bool isFileContext() const
Definition DeclBase.h:2211
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2136
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Decl::Kind getDeclKind() const
Definition DeclBase.h:2113
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
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)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:871
static Decl * castFromDeclContext(const DeclContext *)
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition DeclBase.h:1001
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
The name of a declaration.
static int compare(DeclarationName LHS, DeclarationName RHS)
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:781
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
TemplateName getUnderlying() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
DefaultArguments getDefaultArguments() const
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4159
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4181
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:8343
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4109
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4138
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4199
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4224
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4582
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4602
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:6360
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:6365
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4325
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition TypeBase.h:4350
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
A dynamically typed AST node container.
Represents an enum.
Definition Decl.h:4150
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4368
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4382
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4266
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4323
Represents an explicit instantiation of a template entity in source code.
This represents one expression.
Definition Expr.h:113
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:855
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:224
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4110
QualType getType() const
Definition Expr.h:145
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
We can encode up to four bits in the low bits of a type pointer, but there are many more type qualifi...
Definition TypeBase.h:1736
void Profile(llvm::FoldingSetNodeID &ID) const
Definition TypeBase.h:1783
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:248
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition Decl.cpp:5627
Abstract interface for external sources of AST nodes.
Represents a member of a struct/union/class.
Definition Decl.h:3299
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3402
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4825
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3384
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3535
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:4773
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Represents a function declaration or definition.
Definition Decl.h:2059
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2820
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3807
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3056
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition Decl.cpp:3941
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3792
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4464
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2537
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition Decl.cpp:4125
FunctionDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5384
static FunctionEffectSet getIntersection(FunctionEffectsRef LHS, FunctionEffectsRef RHS)
Definition Type.cpp:6057
static FunctionEffectSet getUnion(FunctionEffectsRef LHS, FunctionEffectsRef RHS, Conflicts &Errs)
Definition Type.cpp:6095
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5216
ArrayRef< EffectConditionExpr > conditions() const
Definition TypeBase.h:5250
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4994
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:5010
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5920
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5723
unsigned getNumParams() const
Definition TypeBase.h:5694
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition Type.cpp:4239
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5729
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5820
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
Definition TypeBase.h:5889
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Definition TypeBase.h:5885
Declaration of a template function.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4723
CallingConv getCC() const
Definition TypeBase.h:4782
unsigned getRegParm() const
Definition TypeBase.h:4775
bool getNoCallerSavedRegs() const
Definition TypeBase.h:4771
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4794
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4638
ExtParameterInfo withIsNoEscape(bool NoEscape) const
Definition TypeBase.h:4678
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
ExtInfo getExtInfo() const
Definition TypeBase.h:4968
QualType getReturnType() const
Definition TypeBase.h:4952
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
unsigned getMultiVersionIndex() const
Definition GlobalDecl.h:134
CXXDtorType getDtorType() const
Definition GlobalDecl.h:122
const Decl * getDecl() const
Definition GlobalDecl.h:115
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
StringRef getName() const
Return the actual identifier string.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5195
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4024
static ItaniumMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
@ Swift
Interoperability with the latest known version of the Swift runtime.
@ Swift4_2
Interoperability with the Swift 4.2 runtime.
@ Swift4_1
Interoperability with the Swift 4.1 runtime.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
@ PostDecrInWhile
while (count–)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::optional< TargetCXXABI::Kind > CXXABI
C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
clang::ObjCRuntime ObjCRuntime
CoreFoundationABI CFRuntime
bool isOverflowPatternExcluded(OverflowPatternExclusionKind Kind) const
Represents a placeholder type for late-parsed type attributes.
Definition TypeBase.h:3577
A global _GUID constant.
Definition DeclCXX.h:4451
static void Profile(llvm::FoldingSetNodeID &ID, Parts P)
Definition DeclCXX.h:4488
MSGuidDeclParts Parts
Definition DeclCXX.h:4453
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6294
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:4461
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4454
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:3794
Provides information a specialization of a member of a class template, which may be a member function...
static MicrosoftMangleContext * create(ASTContext &Context, DiagnosticsEngine &Diags, bool IsAux=false)
Describes a module or submodule.
Definition Module.h:340
bool isNamedModule() const
Does this Module is a named module of a standard named module?
Definition Module.h:426
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1096
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:318
bool isExternallyVisible() const
Definition Decl.h:434
Represent a C++ namespace.
Definition Decl.h:593
static NamespaceDecl * Create(ASTContext &C, DeclContext *DC, bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested)
Definition DeclCXX.cpp:3374
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NestedNameSpecifier getCanonical() const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
CXXRecordDecl * getAsMicrosoftSuper() const
NamespaceAndPrefix getAsNamespaceAndPrefix() const
Kind
The kind of specifier that completes this nested name specifier.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2551
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition DeclObjC.cpp:319
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1534
ivar_range ivars() const
Definition DeclObjC.h:1457
bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, bool lookupCategory, bool RHSIsQualifiedID=false)
ClassImplementsProtocol - Checks that 'lProto' protocol has been implemented in IDecl class,...
StringRef getObjCRuntimeNameAsString() const
Produce a name to be used for class's metadata.
ObjCImplementationDecl * getImplementation() const
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition DeclObjC.h:1816
known_extensions_range known_extensions() const
Definition DeclObjC.h:1768
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8031
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition Type.cpp:1084
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclObjC.h:246
unsigned param_size() const
Definition DeclObjC.h:350
param_const_iterator param_end() const
Definition DeclObjC.h:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
bool isVariadic() const
Definition DeclObjC.h:434
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
QualType getReturnType() const
Definition DeclObjC.h:332
Represents a pointer to an Objective C object.
Definition TypeBase.h:8087
bool isObjCQualifiedClassType() const
True if this is equivalent to 'Class.
Definition TypeBase.h:8168
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition Type.cpp:1091
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8162
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8124
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8145
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8099
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8139
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2011
qual_range quals() const
Definition TypeBase.h:8206
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8151
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:2575
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2622
unsigned getNumComponents() const
Definition Expr.h:2630
Helper class for OffsetOfExpr.
Definition Expr.h:2469
@ Field
A field.
Definition Expr.h:2476
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4417
A structure for storing a pack-index-template-name ([temp.names]).
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
ArrayRef< TemplateName > getExpansions() const
Sugar for parentheses used when specifying types.
Definition TypeBase.h:3383
void clear()
Clear parent maps.
DynTypedNodeList getParents(const NodeT &Node)
Returns the parents of the given node (within the traversal scope).
Represents a parameter to a function.
Definition Decl.h:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
QualType getOriginalType() const
Definition Decl.cpp:2955
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PredefinedSugarKind Kind
Definition TypeBase.h:8357
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:8530
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3094
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition TypeBase.h:8577
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8535
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:8446
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8467
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
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:8503
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8450
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:3237
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8478
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:8386
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8393
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition TypeBase.h:385
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool hasNonFastQualifiers() const
Return true if the set contains any qualifiers which require an ExtQuals node to be allocated.
Definition TypeBase.h:639
void addConsistentQualifiers(Qualifiers qs)
Add the qualifiers from the given set to this set, given that they don't conflict.
Definition TypeBase.h:690
void removeFastQualifiers(unsigned mask)
Definition TypeBase.h:625
bool hasUnaligned() const
Definition TypeBase.h:512
bool hasAddressSpace() const
Definition TypeBase.h:571
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
unsigned getFastQualifiers() const
Definition TypeBase.h:620
void removeAddressSpace()
Definition TypeBase.h:597
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
bool hasObjCGCAttr() const
Definition TypeBase.h:519
uint64_t getAsOpaqueValue() const
Definition TypeBase.h:456
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:529
bool empty() const
Definition TypeBase.h:648
void addObjCGCAttr(GC type)
Definition TypeBase.h:525
LangAS getAddressSpace() const
Definition TypeBase.h:572
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
bool isTrailingComment() const LLVM_READONLY
Returns true if it is a comment that should be put after a member:
SourceRange getSourceRange() const LLVM_READONLY
bool isDocumentation() const LLVM_READONLY
Returns true if this comment any kind of a documentation comment.
comments::FullComment * parse(const ASTContext &Context, const Preprocessor *PP, const Decl *D) const
Parse the comment, assuming it is attached to decl D.
Represents a struct/union/class.
Definition Decl.h:4464
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition Decl.cpp:5325
bool hasFlexibleArrayMember() const
Definition Decl.h:4497
field_range fields() const
Definition Decl.h:4667
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition Decl.cpp:5311
RecordDecl * getMostRecentDecl()
Definition Decl.h:4490
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition Decl.cpp:5370
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4648
bool field_empty() const
Definition Decl.h:4675
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
This table allows us to fully hide how we implement multi-keyword caching.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
The streaming interface shared between DiagnosticBuilder and PartialDiagnostic.
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1823
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
A structure for storing an already-substituted template template parameter pack.
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
void Profile(llvm::FoldingSetNodeID &ID, ASTContext &Context)
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
A structure for storing the information associated with a substituted template template parameter.
void Profile(llvm::FoldingSetNodeID &ID)
TemplateTemplateParmDecl * getParameter() const
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3856
TagTypeKind TagKind
Definition Decl.h:3861
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4093
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4985
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4978
bool isUnion() const
Definition Decl.h:4067
TagKind getTagKind() const
Definition Decl.h:4056
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Kind
The basic C++ ABI kind.
static Kind getKind(StringRef Name)
Exposes information about the current target.
Definition TargetInfo.h:228
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getMaxAtomicInlineWidth() const
Return the maximum width lock-free atomic operation which can be inlined given the supported features...
Definition TargetInfo.h:854
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const
Map from the address space field in builtin description strings to the language address space.
unsigned getDefaultAlignForAttributeAligned() const
Return the default alignment for attribute((aligned)) on this target, to be used if no alignment valu...
Definition TargetInfo.h:747
BuiltinVaListKind
The different kinds of __builtin_va_list types defined by the target implementation.
Definition TargetInfo.h:341
@ AArch64ABIBuiltinVaList
__builtin_va_list as defined by the AArch64 ABI http://infocenter.arm.com/help/topic/com....
Definition TargetInfo.h:350
@ PowerABIBuiltinVaList
__builtin_va_list as defined by the Power ABI: https://www.power.org /resources/downloads/Power-Arch-...
Definition TargetInfo.h:355
@ AAPCSABIBuiltinVaList
__builtin_va_list as defined by ARM AAPCS ABI http://infocenter.arm.com
Definition TargetInfo.h:364
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:343
@ VoidPtrBuiltinVaList
typedef void* __builtin_va_list;
Definition TargetInfo.h:346
@ X86_64ABIBuiltinVaList
__builtin_va_list as defined by the x86-64 ABI: http://refspecs.linuxbase.org/elf/x86_64-abi-0....
Definition TargetInfo.h:359
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const
Get integer value for null pointer.
Definition TargetInfo.h:513
static bool isTypeSigned(IntType T)
Returns true if the type is signed; false otherwise.
IntType getPtrDiffType(LangAS AddrSpace) const
Definition TargetInfo.h:415
bool isLittleEndian() const
IntType getSizeType() const
Definition TargetInfo.h:396
FloatModeKind getRealTypeByWidth(unsigned BitWidth, FloatModeKind ExplicitType) const
Return floating point type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const
Return integer type with specified width.
unsigned getMaxAlignedAttribute() const
Get the maximum alignment in bits for a static variable with aligned attribute.
Definition TargetInfo.h:974
virtual unsigned getMinGlobalAlign(uint64_t Size, bool HasNonWeakDef) const
getMinGlobalAlign - Return the minimum alignment of a global variable, unless its alignment is explic...
Definition TargetInfo.h:755
unsigned getTargetAddressSpace(LangAS AS) const
IntType getSignedSizeType() const
Definition TargetInfo.h:397
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:805
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool useAddressSpaceMapMangling() const
Specify if mangling based on address space map should be used or not for language specific address sp...
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
UnsignedOrNone getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
QualType getIntegralType() const
Retrieve the type of the integral value.
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
std::optional< TemplateName > desugar(bool IgnoreDeduced) const
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
void * getAsVoidPointer() const
Retrieve the template name as a void pointer.
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
@ OverloadedTemplate
A set of overloaded template declarations.
@ PackIndexingTemplate
A pack-index-template-name.
@ Template
A single template declaration.
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
@ DeducedTemplate
A template name that refers to another TemplateName with deduced default arguments.
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
PackIndexingTemplateStorage * getAsPackIndexingTemplate() const
Retrieve the pack-index-template-name storage, if any.
A template parameter object.
static void Profile(llvm::FoldingSetNodeID &ID, QualType T, const APValue &V)
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
ArrayRef< NamedDecl * > asArray()
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Token - This structure provides full information about a lexed token.
Definition Token.h:36
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
TemplateName getNamedConcept() const
Definition ASTConcept.h:254
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
Represents a declaration of a type.
Definition Decl.h:3652
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:6326
A container of type source information.
Definition TypeBase.h:8417
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:8703
bool isVoidType() const
Definition TypeBase.h:9068
bool isObjCBuiltinType() const
Definition TypeBase.h:8913
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2899
bool isIncompleteArrayType() const
Definition TypeBase.h:8790
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isFloat16Type() const
Definition TypeBase.h:9081
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:8786
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:8782
bool isCharType() const
Definition Type.cpp:2319
bool isPointerType() const
Definition TypeBase.h:8683
TagDecl * castAsTagDecl() const
Definition Type.h:69
bool isArrayParameterType() const
Definition TypeBase.h:8798
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
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:9160
bool isEnumeralType() const
Definition TypeBase.h:8814
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8883
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isBitIntType() const
Definition TypeBase.h:8958
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8806
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
bool isHalfType() const
Definition TypeBase.h:9076
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9148
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
@ PtrdiffT
The "ptrdiff_t" type.
Definition TypeBase.h:2344
@ SizeT
The "size_t" type.
Definition TypeBase.h:2338
@ SignedSizeT
The signed integer type corresponding to "size_t".
Definition TypeBase.h:2341
bool isObjCIdType() const
Definition TypeBase.h:8895
bool isOverflowBehaviorType() const
Definition TypeBase.h:8854
bool isUnsaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9156
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8679
bool isObjCObjectPointerType() const
Definition TypeBase.h:8862
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:9174
bool isVectorType() const
Definition TypeBase.h:8822
bool isObjCClassType() const
Definition TypeBase.h:8901
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2881
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2816
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2460
bool isAnyPointerType() const
Definition TypeBase.h:8691
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:9299
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
bool isObjCRetainableType() const
Definition Type.cpp:5611
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5327
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3806
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5845
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3701
QualType getUnderlyingType() const
Definition Decl.h:3756
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType Underlying)
Definition TypeBase.h:6270
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2292
Opcode getOpcode() const
Definition Expr.h:2328
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
static void Profile(llvm::FoldingSetNodeID &ID, QualType Ty, const APValue &APVal)
Definition DeclCXX.h:4536
The iterator over UnresolvedSets.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6131
static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const UnresolvedUsingTypenameDecl *D)
Definition TypeBase.h:6168
Represents a dependent using declaration which was marked with typename.
Definition DeclCXX.h:4067
UnresolvedUsingTypenameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this declaration.
Definition DeclCXX.h:4132
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3822
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
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:6208
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5660
void clear()
Definition Value.cpp:217
Represents a variable declaration or definition.
Definition Decl.h:933
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition Decl.cpp:2785
bool hasInit() const
Definition Decl.cpp:2383
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:2446
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1215
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2360
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:2754
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Represents a GCC generic vector type.
Definition TypeBase.h:4273
unsigned getNumElements() const
Definition TypeBase.h:4288
void Profile(llvm::FoldingSetNodeID &ID)
Definition TypeBase.h:4297
VectorKind getVectorKind() const
Definition TypeBase.h:4293
QualType getElementType() const
Definition TypeBase.h:4287
A full comment attached to a declaration, contains block content.
Definition Comment.h:1097
ArrayRef< BlockContentComment * > getBlocks() const
Definition Comment.h:1135
const DeclInfo * getDeclInfo() const LLVM_READONLY
Definition Comment.h:1129
const Decl * getDecl() const LLVM_READONLY
Definition Comment.h:1125
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
mlir::Type getBaseType(mlir::Value varPtr)
const AstTypeMatcher< TagType > tagType
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus17
GVALinkage
A more specific kind of linkage than enum Linkage.
Definition Linkage.h:72
@ GVA_StrongODR
Definition Linkage.h:77
@ GVA_StrongExternal
Definition Linkage.h:76
@ GVA_AvailableExternally
Definition Linkage.h:74
@ GVA_DiscardableODR
Definition Linkage.h:75
@ GVA_Internal
Definition Linkage.h:73
AutoTypeKeyword
Which keyword(s) were used to create an AutoType.
Definition TypeBase.h:1838
OpenCLTypeKind
OpenCL type kinds.
Definition TargetInfo.h:214
@ OCLTK_ReserveID
Definition TargetInfo.h:221
@ OCLTK_Sampler
Definition TargetInfo.h:222
@ OCLTK_Pipe
Definition TargetInfo.h:219
@ OCLTK_ClkEvent
Definition TargetInfo.h:216
@ OCLTK_Event
Definition TargetInfo.h:217
@ OCLTK_Default
Definition TargetInfo.h:215
@ OCLTK_Queue
Definition TargetInfo.h:220
constexpr llvm::StringLiteral VTTVTablePointerDiscriminatorSuffix
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition TypeBase.h:8581
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:359
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
std::pair< FileID, unsigned > FileIDAndOffset
CXXABI * CreateMicrosoftCXXABI(ASTContext &Ctx)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
@ AS_public
Definition Specifiers.h:128
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Register
Definition Specifiers.h:261
@ SC_Static
Definition Specifiers.h:256
CXXABI * CreateItaniumCXXABI(ASTContext &Ctx)
Creates an instance of a C++ ABI class.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition Linkage.h:24
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ TypeAlignment
Definition TypeBase.h:77
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3817
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6044
@ Struct
The "struct" keyword.
Definition TypeBase.h:6041
@ Class
The "class" keyword.
Definition TypeBase.h:6050
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:492
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
LangAS
Defines the address space values used by the address space qualifier of QualType.
TranslationUnitKind
Describes the kind of translation unit being processed.
DeducedKind
Definition TypeBase.h:1811
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
const Decl & adjustDeclToTemplate(const Decl &D)
If we have a 'templated' declaration for a template, adjust 'D' to refer to the actual template.
FloatModeKind
Definition TargetInfo.h:76
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h: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:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_M68kRTD
Definition Specifiers.h:302
@ CC_X86RegCall
Definition Specifiers.h:291
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:558
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:566
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:562
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4243
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4240
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4258
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4261
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
AlignRequirementKind
Definition ASTContext.h:174
@ ResistPragmaPack
The type's natural alignment is preserved under pragma pack in MSVC record layout (e....
Definition ASTContext.h:189
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ RequiredByEnum
The alignment comes from an alignment attribute on a enum type.
Definition ASTContext.h:185
@ RequiredByTypedef
The alignment comes from an alignment attribute on a typedef.
Definition ASTContext.h:179
@ RequiredByRecord
The alignment comes from an alignment attribute on a record type.
Definition ASTContext.h:182
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:6014
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
@ Union
The "union" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6022
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6032
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
unsigned long uint64_t
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
Copy initialization expr of a __block variable and a boolean flag that indicates whether the expressi...
Definition Expr.h:6772
Expr * getCopyExpr() const
Definition Expr.h:6779
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:5473
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5475
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5478
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition TypeBase.h:5481
Extra information about a function prototype.
Definition TypeBase.h:5501
bool requiresFunctionProtoTypeArmAttributes() const
Definition TypeBase.h:5547
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5506
bool requiresFunctionProtoTypeExtraAttributeInfo() const
Definition TypeBase.h:5551
bool requiresFunctionProtoTypeExtraBitfields() const
Definition TypeBase.h:5540
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:3520
A late-parsed attribute that will be applied as a type attribute.
Definition Parser.h:238
constexpr underlying_type toInternalRepresentation() const
Contains information gathered from parsing the contents of TargetAttr.
Definition TargetInfo.h:59
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:871
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
A this pointer adjustment.
Definition Thunk.h:92
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:148
AlignRequirementKind AlignRequirement
Definition ASTContext.h:210
bool isAlignRequired()
Definition ASTContext.h:201
AlignRequirementKind AlignRequirement
Definition ASTContext.h:195
Information about the declaration, useful to clients of FullComment.
Definition Comment.h:974
const TemplateParameterList * TemplateParameters
Template parameters that can be referenced by \tparam if CommentDecl is a template (IsTemplateDecl or...
Definition Comment.h:1000
const Decl * CommentDecl
Declaration the comment is actually attached to (in the source).
Definition Comment.h:977